monaco-editor: [Bug] Multiple editor instances only latest created instance is working properly

Reproducible in vscode.dev or in VS Code Desktop?

  • Not reproducible in vscode.dev or VS Code Desktop

Reproducible in the monaco editor playground?

Monaco Editor Playground Code

/* HTML CONTENT
<div id="container" style="height: 50%"></div>
<div id="container2" style="height: 50%"></div>
*/

const model = monaco.editor.createModel("function hello() {\n\talert('Hello world!');\n}", 'javascript');
const model1 = monaco.editor.createModel("function test() {\n\talert('Hello test!');\n}", 'javascript');
const editor = monaco.editor.create(document.getElementById('container'), {
    model
});
const editor2 = monaco.editor.create(document.getElementById('container2'), {
    model:model1
});

editor.addCommand(monaco.KeyMod.CtrlCmd|monaco.KeyMod.Shift|monaco.KeyCode.KeyF, ()=> {
    const pos = editor.getPosition();
    console.log('pos', pos)
});
editor2.addCommand(monaco.KeyMod.CtrlCmd|monaco.KeyMod.Shift|monaco.KeyCode.KeyF, ()=> {
    const pos = editor2.getPosition();
    console.log('pos2', pos)
});

Actual Behavior

Triggering crtl + shift + f in the first instance, the custom command of the second instance will be triggered.

Expected Behavior

Triggering crtl + shift + f in any editor instance should trigger the command of the correct editor instance.

Additional Context

No response

About this issue

  • Original URL
  • State: open
  • Created 5 years ago
  • Reactions: 21
  • Comments: 21 (3 by maintainers)

Most upvoted comments

A simpler workaround than the ones I’ve seen above might be to use actions instead of commands:

Playground link

This has also been impacting us for the last few months since updating to a newer release of the editor (we are currently using 0.34.1). In our case a user may have multiple editors open (i.e. editing multiple source file). We use custom key binding CTRL + S to save the model displayed in the “active” editor. In prior versions this worked as expected, now the CTRL + S command is routed to the most-recently-opened editor instance rather than the active/in-focus editor instance, meaning that:

  • users are accidently saving files they do not intend to save, and
  • files that users think they have saved are not actually saved (i.e. they lose work) This is making our users quite unhappy.

@stoanarrr You can re add the command when the editor focus, it works for me:

addCommand () {
    this.editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, () => {
    });
    this.editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyR, () => {
    });
    this.editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyMod.Shift | monaco.KeyCode.KeyR, () => {
    });
    this.editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.Period, () => {
    });
  }
this.editor.onDidFocusEditorText(() => {
        this.addCommand();
    });

Hello everyone, Several months have passed. How is this problem fixed?

Hello,The latest version I am currently using still has this issue. Is there a plan to fix it, or is there currently any other solution available

So it is a regression in 0.32.0?

Both editor instances get injected the same instance of StandaloneKeybindingService. Thus, this is currently by design. However, I can see that this looks like a bug.

I’ll tag this as feature request to use independent keybinding services for different editors.

Still occurs in v0.51.0-dev-20240807. Since the editors now share the keybinding service, it might make sense to not use the standalone editor’s addCommand at all in multi-editor setups, and instead do something like:

// Track focused editor ourselves:

let focusedEditor;

// Handle Cmd/Ctrl + S globally instead of per editor:

monaco.editor.addCommand({
    id: "myapp.save",
    run: (...args: unknown[]) => {
        if (!focusedEditor) return
        saveContents(focusedEditor.getModel())
    },
});

monaco.editor.addKeybindingRule({
    keybinding: monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS,
    command: "myapp.save",
});

// Make each editor report when it's focused:

const editor1 = monaco.editor.create(…)
editor1.onDidFocusEditorText(() => {
    focusedEditor = editor1
});

const editor2 = monaco.editor.create(…)
editor2.onDidFocusEditorText(() => {
    focusedEditor = editor2
});

// In theory you don't need to track on blur if you are doing this to all
// your editors because the commands only run while an editor has focus.

My understanding is that editor.addAction(…) is always per editor and its keybindings will be unique to that editor instance, so if you don’t need a command at all (I believe they are required in some contexts), then using addAction instead is probably the way to go:

const editor1 = monaco.editor.create(…)
editor1.addAction({
    id: "myapp.save",
    label: "Save",
    keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS],
    async run(editor) {
        saveContents(editor.getModel())
    },
});

const editor2 = monaco.editor.create(…)
editor2.addAction({
    id: "myapp.save",
    label: "Save",
    keybindings: [monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS],
    async run(editor) {
        saveContents(editor.getModel())
    },
});

As a bonus, this approach will make the “Save” action show up in the command palette of the editor.

Just tested in the playground with the latest dev build and still seems to be an issue.

The workaround to switch addCommand -> addAction seems to have worked well for us. We were using the context option of addCommand as suggested here, and it appears that precondition of addAction works similarly.

Ok, thats weird. Because currently I’m using the 0.31.1 version in my project with multiple editor instances and the behaviour is like the expected one.