如何在 vscode 扩展中使用多个 tmLanguage 文件

How to use multiple tmLanguage files in vscode extension

我正在 vscode 中为自己创建一个语言扩展。因为会关联不同的文件类型,所以我打算针对特定的规则制作不同的tmlanguge文件。根据 this,我可以扩展 scopeName 来实现。

所以我在 ./package.json 文件中创建了如下内容:

{
    "name": "tst",
    "displayName": "Test Language",
    "description": "A test for language extension",
    "version": "0.0.1",
    "engines": {
        "vscode": "^1.34.0"
    },
    "contributes": {
        "languages": [{
            "id": "tst",
            "aliases": ["Test", "tst"],
            "extensions": [".tst",".type1",".type2"],
            "configuration": "./language-configuration.json"
        }],
        "grammars": [{
            "language": "tst",
            "scopeName": "source.tst",
            "path": "./syntaxes/tst.tmLanguage.json"
        },
        {
            "scopeName": "source.tst.type1",
            "path": "./syntaxes/type1.tmLanguage.json"
        },
        {
            "scopeName": "source.tst.type2",
            "path": "./syntaxes/type2.tmLanguage.json"
        }]
    }
}

然后我在 ./syntaxes/tst.tmLanguage.json 中创建基本规则并且 .type1.type2 都已应用到我的语法中。

{
    "name": "Test",
    "patterns": [
        {
            "match": "test",
            "name": "constant.character"
        }
    ],
    "scopeName": "source.tst"
}

之后我也做了./syntaxes/type1.tmLanguage.json这样的东西:

{
    "name": "type1",
    "patterns": [
        {
            "match": "type1",
            "name": "constant.language"
        }
    ],  
    "scopeName": "source.tst.type1"
}

.type1 中的任何规则均无效。

希望图中的两个文件都能识别testtype1。 我检查了 vscode 预装的 cpp 语言扩展。 他们还对 source.csource.c.platform 使用 scopeName。 我猜是为了类似的目的吧?

我是不是忽略了什么? 感谢您的帮助。

如果你想在主语法中使用来自不同 tmLanguage 文件的这些作用域,你必须显式 include 它们:

{
    "name": "Test",
    "patterns": [
        {
            "match": "test",
            "name": "constant.character"
        },
        {
            "include": "source.tst.type1"
        },
        {
            "include": "source.tst.type2"
        }
    ],
    "scopeName": "source.tst"
}


关于 built-in cpp 扩展和 platform.tmLanguage.json - 据我所知,c 和 cpp 语法并未主动使​​用它。 cpp/build/update-grammars.js 中有此评论:

// `source.c.platform` which is still included by other grammars

所以这听起来更像是一个 backwards-compatibility 措施,以防任何 third-party 语法仍然使用它。