Trigger event in my extension on save editor

I would like to trigger an event from my extension when the save event happens. Is there any way to bind to this?

[original thread by Eiso Kant]

Hi, for any editor or for a particular?

In Theia an editor is backed up by a model, the same model can be used by many different widgets.

So one saves not an editor, but an underlying model.

You can listen to all save events on the workspace: https://github.com/theia-ide/theia/blob/0953ba77fe0b9c90bd7c122355acedc177ea5d0b/packages/monaco/src/browser/monaco-workspace.ts#L75-L79

Alternatively you can get a model from an editor or a create a new reference to a model: https://github.com/theia-ide/theia/blob/0953ba77fe0b9c90bd7c122355acedc177ea5d0b/packages/monaco/src/browser/monaco-text-model-service.ts#L55-L57

it allows you to listen to save events directly on the model.

It’s important to release a reference when you don’t need it anymore, otherwise a model will hang in the memory forever.

[Eiso Kant]

Thank you very much Anton! It’s for any editor. I am going to try this out now.

[Eiso Kant]

It worked well to bind to a Monaco editor:

@injectable()
export class MyWidget extends ReactWidget {
    ...

    @inject(WorkspaceService)
    protected readonly workspaceService: WorkspaceService;

    @inject(MonacoWorkspace)
    protected readonly MonacoWorkspace: MonacoWorkspace;

    @postConstruct()
    protected async init(): Promise<void> {
        ...
        this.onWorkspaceSave();
    }

    onWorkspaceSave(): void {
        this.MonacoWorkspace.onWillSaveTextDocument(event => {
            this.saveSpreadsheet()
        });
    }

    saveSpreadsheet = () => {
        socket.emit('save', {});
    }

However, now I need to change it to capture any save event (even when no Monaco editor is open). I looked at the second link you shared but wasn’t able to figure out how to approach it. Would you be willing to give me more guidance?

Do you mean when no your widget is opened?

You can create a frontend application contribution which listens to all changes. It gets initialized on the frontend app start up.

[Eiso Kant]

Exactly, when my widget is open I want to listen to all changes. Any examples of a frontend application contribution? If not, I’ll happily figure it out.

You can have a look at any implementation of https://github.com/502647092/theia/blob/fda5b557e08f98de6e0f94ed41f405187b3fcfbc/packages/core/src/browser/frontend-application.ts#L32