我正在此处查看 Monaco 编辑器的沙箱: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' },
]
});
问题是多行引号不起作用。我怀疑摩纳哥逐行解析文本/代码会导致问题,但我肯定不能独自解决这个问题。 有一个标志或我必须设置的东西吗?
最佳答案
诀窍是使用分词器状态和分词器堆栈。查看 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" }],
],
当找到引号字符时,会设置它的关联标记类型,并将新状态推送到标记生成器堆栈上。分词器继续保持此状态(例如stringSingelSql
),直到找到另一个引号。无论由此处理多少行,它们都会获得分配的字符串标记类型。一旦找到收盘价,分词器堆栈就会返回到之前的状态。
您还可以处理引号字符和双引号字符的转义(如示例所示)。
关于javascript - 如何在 Monaco Editor 中设置多行规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66278203/