如何在VSCode语法高亮的TextMate语言定义中配置模板字符串规则
问题核心原因
你当前配置的问题是 <> 包裹的字符串规则没有配置内部插值结构的解析逻辑,所有 <> 内的内容都会被默认判定为普通字符串文本,不会触发 terms、numbers 的高亮规则,同时 terms 下的大括号全局匹配规则也存在逻辑错误。
调整方案
1. 新增模板插值规则
在 repository 下新增插值匹配块,用来识别 {} 包裹的嵌套内容,内部复用已有的 terms、numbers、strings 规则实现嵌套高亮。
2. 调整字符串规则的内部匹配逻辑
给 strings 节点的 patterns 数组添加插值规则的引用,让字符串内部遇到 { 时自动进入插值解析流程。
3. 清理 terms 下的错误规则
删除 terms 中匹配 {[^}]+} 的规则,避免全局匹配大括号块和插值逻辑冲突。
调整后的完整配置
{ "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json", "name": "myscript", "patterns": [ { "include": "#terms" }, { "include": "#strings" }, { "include": "#numbers" } ], "repository": { "terms": { "patterns": [ { "name": "term.control.myscript", "match": "\\b([a-z][a-z0-9]*(?:-[a-z0-9]+)*)\\b" } ] }, "numbers": { "patterns": [ { "name": "constant.numeric.decimal.myscript", "match": "\\b(\\d+\\.\\d+)\\b" }, { "name": "constant.numeric.integer.myscript", "match": "\\b(\\d+)\\b" } ] }, "interpolation": { "name": "meta.interpolation.myscript", "begin": "\\{", "end": "\\}", "patterns": [ { "include": "#terms" }, { "include": "#numbers" }, { "include": "#strings" } ] }, "strings": { "name": "string.quoted.double.myscript", "begin": "<", "end": ">", "patterns": [ { "name": "constant.character.escape.myscript", "match": "\\\\." }, { "include": "#interpolation" } ] } }, "scopeName": "source.myscript" }
修改后重启VSCode扩展开发宿主即可生效,示例代码 <string {term(another-term, 123)}> 里的 term、another-term 会被识别为term,123 会被识别为数字,其余部分保留字符串高亮。
内容的提问来源于stack exchange,提问作者Lance Pollard
相关产品推荐
相关产品推荐

