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

How to set multiline rule in 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"

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

// 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' },
    ]
});

问题是多行引用不起作用。我怀疑 Monaco 逐行解析 text/code 导致了问题,但我肯定不能独自解决这个问题。 有没有我必须设置的标志或其他东西?

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

查看 Monarch 文档

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

        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" }],
        ],

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

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