Search code examples
javascriptmonaco-editor

Allowing characters in eg variable names in Monaco editor


Is there a Monaco option to treat non-ascii characters as valid in variable names in the Monaco editor? In VSCode the below code would have been formatted as a valid variable name, but when using MonacoEditor it stumbles on valid characters like ö.

I have tried toggling the unicodeHighlight: nonBasicASCII option, but that seems to be something else, and neither does unicodeHighlight: allowedLocales do any good here. The red color has the classname .mtk11, but I haven't been able to find a list of what those classnames actually mean.

enter image description here

The code language is set to javascript which inherits language settings from typescript.

I'm using monaco-editor@0.52.0 (in a Nuxt4 project through nuxt-monaco-editor@1.3.1, but options are forwarded as-is, so that probably doesn't matter.)


Solution

  • It's probably dictated by the language definition file. What language did you set for this code? Look in monaco-editor/esm/vs/basic-languages/. For each supported language there's a simple highlighter declaration js file.

    Check out the Monarch playground for details about this highlighter. You can also use it to test your own rules.

    To change the highlighter behavior you have two options:

    1. Change the javascript.ts file (for javascript) in the basic-languages folder.
    2. Create your own language with the changes and register that in monaco-editor.

    The first option is probably not a good idea. For the second create your own highlighting file (just like what is shown in the playground) and load that when your new language is actived:

            languages.onLanguage("mysql", () => {
                void mysql.loader().then((definition: ILanguageDefinition) => {
                    languages.setMonarchTokensProvider("mysql", definition.language);
                    languages.setLanguageConfiguration("mysql", definition.languageConfiguration);
                });
            });
    

    Here I loaded an own language description for "mysql". The implementation for mysql is in a mysql.contribution.ts file imported in that file with the language registration. Here's what I have there:

    import { languages, ILanguageDefinition } from "../../index.js";
    
    export const mysql: languages.ILanguageExtensionPoint & { loader: () => Promise<ILanguageDefinition>; } = {
        id: "mysql",
        extensions: [],
        aliases: ["MySQL", "mysql"],
        loader: (): Promise<ILanguageDefinition> => {
            return import("./mysql.js");
        },
    };
    

    where mysql.js (actually mysql.ts) is the file with the monarch defintion. Check any of the other languages in the monaco sub folder for more ideas. Since these are all js/ts files, you can simply import an existing definition (e.g. for javascript) and just override the parts you want to change.