Monaco: comment keyboard-shortcut for custom language

497 views Asked by At

I am using monaco ("monaco-editor": "^0.38.0") with a custom language profile and I want cmd+/ to toggle line commenting.

My main js file has

import { monaco } from "./customMonaco";

customMonaco has

import "monaco-editor/esm/vs/editor/editor.all.js";
import "monaco-editor/esm/vs/editor/contrib/comment/browser/comment.js";
...
import * as monaco from "monaco-editor/esm/vs/editor/editor.api.js";
import "./mix.contribution.js";
export { monaco };

mix.contribution reads

import {language} from "./mix.js"

monaco.languages.register({
    id: "mix",
    extensions: [".mix"],
    aliases: ["Mix", "mix"],
});

monaco.languages.setMonarchTokensProvider('mix', language);

and mix.js includes

export const language = {
  ...
  comment: [[/[^\/\/*]+/, "comment"]],
  ...
}

some key bindings work (e.g. cmd+z) but not the one I want. What might I be missing?

I tried adding this after the code instantiating monaco

        const blockContext = "editorTextFocus";
        this.editor.addAction({
            id: "toggleComment",
            label: "Toggle Comment",
            keybindings: [KeyMod.CtrlCmd | KeyCode.Slash],
            // contextMenuGroupId: "2_execution",
            precondition: blockContext,
            run: () => {
                console.log("comment toggle");
            },
        });

This does log to the console but I can't find a command to toggle comments that i could add

1

There are 1 answers

1
4seconds On BEST ANSWER

In addition to tokenisation, you also need to set the comment rules of your language in the language configuration:

const languageConfiguration: monaco.languages.LanguageConfiguration = {
    comments: {
      lineComment: "//",
      blockComment: [ "/*", "*/" ]
    },
    ... //The rest of your language configuration
}

And then apply the configuration:

monaco.languages.setLanguageConfiguration('mix', languageConfiguration)