如何在摩纳哥编辑器中设置多行规则

Maf*_*elu 2 javascript monaco-editor

我正在此处查看摩纳哥编辑器的沙箱: https: //microsoft.github.io/monaco-editor/playground.html#extending-language-services-custom-languages

我试图支持以下案例:

"A single line quote"
"But also a slightly weird
multi line quote"
Run Code Online (Sandbox Code Playgroud)

我需要同时支持两者,因为我正在使用的语言都支持两者。现在,我设置的规则如下所示:

// Register a tokens provider for the language
monaco.languages.setMonarchTokensProvider('mySpecialLanguage', {
    tokenizer: {
        root: [
            [/"(?:[^"\\]|\\.\n{0,})*"/gi, 'my-string'],
        ]
    }
});

// Define a new theme that contains only rules that match this language
monaco.editor.defineTheme('myCoolTheme', {
    base: 'vs',
    inherit: false,
    rules: [
        { token: 'my-string', foreground: '0000FF' },
    ]
});
Run Code Online (Sandbox Code Playgroud)

问题是多行引用不起作用。我怀疑摩纳哥逐行解析文本/代码会导致问题,但我肯定不能独自解决这个问题。有一个标志或我必须设置的东西吗?

Mik*_*hke 5

诀窍是使用分词器状态和分词器堆栈。查看 Monarch 文档:https://microsoft.github.io/monaco-editor/monarch.html

在我的分词器中,我对 3 种可能的 (MySQL) 字符串类型有 3 条规则,即单引号、双引号和反引号:

        stringsSql: [
            [/'/, { token: "string.quoted.single.sql", next: "@stringSingleSql" }],
            [/"/, { token: "string.quoted.double.sql", next: "@stringDoubleSql" }],
            [/`/, { token: "string.quoted.other.sql", next: "@stringBacktickSql" }],
        ],
        stringSingleSql: [
            [/[^']+/, "string.quoted.single.sql"],
            [/(''|\\')/, "string.quoted.single.sql"],
            [/'/, { token: "string.quoted.single.sql", next: "@pop" }],
        ],
        stringDoubleSql: [
            [/[^"]+/, "string.quoted.double.sql"],
            [/(''|\\")/, "string.quoted.double.sql"],
            [/"/, { token: "string.quoted.double.sql", next: "@pop" }],
        ],
        stringBacktickSql: [
            [/[^`]+/, "string.quoted.other.sql"],
            [/``/, "string.quoted.other.sql"],
            [/`/, { token: "string.quoted.other.sql", next: "@pop" }],
        ],
Run Code Online (Sandbox Code Playgroud)

当找到引号字符时,会设置它的关联标记类型,并且我会在标记器堆栈上推送一个新状态。分词器继续保持此状态(例如stringSingelSql),直到找到另一个引用。无论由此处理多少行,它们都会获得分配的字符串标记类型。一旦找到收盘价,分词器堆栈就会返回到之前的状态。

您还可以处理引号字符和双引号字符的转义(如示例中所示)。