在 Visual Studio 代码中自定义语法突出显示

Customizing syntax highlighting in Visual Studio Code

我目前正在尝试为新文件类型 (ANTLR) 编写扩展名,想知道如何更改 Visual Studio 代码中用于语法突出显示的颜色。在我看来,它似乎没有在扩展中定义,而是在其他地方定义。没有颜色的首选项条目,我也没有找到定义它的 CSS 文件(这是我期望的,因为 vscode 使用的是 Electron)。我还查看了生成的设置文件 vscode 和它附带的文件,但也没有任何线索。网络搜索也没有帮助。所以,我现在有点迷路了。

有人可以给我一些提示或指出相关文档吗?

语法高亮显示 规则存储在.plist 文件中(或者在.tmLanguage 文件中)。在这些文件中,为语法高亮声明了不同的标记类型:

  • 什么是关键字?
  • 什么是字符串文字?
  • 什么是评论?
  • 等等

点击此处了解更多信息:https://code.visualstudio.com/Docs/customization/colorizer

您没有在 .plist 个文件中定义颜色!

令牌类型和颜色之间的关系在颜色主题声明中完成。

在此处了解更多信息 https://code.visualstudio.com/Docs/customization/themes and here

一般来说,当您尝试扩展 VSCode 时,此文档也很有帮助:https://code.visualstudio.com/docs/extensionAPI/overview

这里有两个概念:

  • 语言语法,将文本文件转换为具有不同范围
  • 的标记
  • 主题,以(希望)赏心悦目的方式为这些 范围 着色。

如果您正在编写自己的语法,或从 TextMate 等进行转换,则您使用的范围可能与主题定义的范围不同。在那种情况下,你定义的标记之间不会有明显的区别,即使它们实际上是定义的。

有两种解决方法。第一个是,使用您的自定义范围扩展主题并根据需要为它们着色。这不是一个好方法,除非使用您的语言的每个人也喜欢您的配色方案。另一种是,使用已经由 VSCode 和主题作者定义和着色的(有限的)范围。很有可能,您的语言在您选择的主题中看起来不错,在其他主题中也足够好。

举个例子,这是默认深色 VSCode 主题定义的 comment 范围。

"name": "Dark Visual Studio",
"settings": [
    {
        "scope": "comment",
        "settings": {
            "foreground": "#608b4e"
        }
    },

这里是 C++ 语法的等效语言片段:

"comments": {
    "patterns": [
        {
            "captures": {
                "0": {
                    "name": "punctuation.definition.comment.java"
                }
            },
            "match": "/\*\*/",
            "name": "comment.block.empty.java"
        },

基本上,该语言根据需要在 comment 下定义了多个标记,并且由于主题表明 comment.* 将是绿色,因此它们都具有相同的颜色。

主题不需要打补丁,来自official documentation:

To tune the editor's syntax highlighting colors, use editor.tokenColorCustomizations in your user settings settings.json file

除了简单的令牌自定义之外,您还可以使用稍微复杂的设置完全覆盖 TextMate 规则,例如:

"editor.tokenColorCustomizations": {"textMateRules": [{
        "scope": "keyword.control.ref.latex",
        "settings": {
            "foreground": "#FF0000"
        }
    }]}

您可以考虑使用 color theme

VSCode 1.44 (March 2020) 开始,您现在有

Theme Support for Semantic Tokens

Color themes can now write rules to color semantic tokens reported by language extensions like TypeScript.

"semanticHighlighting": true,
"semanticTokenColors": {
    "variable.declaration.readonly:java": { "foreground": "#00ff00" "fontStyle": "bold" }
}

The rule above defines that all declarations of readonly variables in Java shoud be colored greed and bold

See the Semantic Highlighting Wiki Page for more information.