如何通过TreeSitter注入为JS对象template键值添加HTML语法高亮?
TreeSitter注入规则:让JS对象的template属性值获得HTML语法高亮
想要实现的效果是:当JavaScript对象中属性键为template时,它对应的模板字符串值自动应用HTML语法高亮。示例代码如下:
export default { name: "CreativeBatcher", components: { IframePreview, }, template: ` <div>this has<span>highlighting!</span></div> `, }
目前只能写出让所有模板字符串都高亮的规则:
; extends ((template_string) @html (#set! language "html"))
尝试过的规则能匹配到template键,但错误地把HTML高亮应用到了键名上,而非对应的值:
((object (pair key: (property_identifier) @key value: (template_string) @html)) (#match? @key "template") (#set! language "html" @html))
正确规则写法
问题出在#set!的语法上,需要将语言设置直接关联到捕获的@html节点,调整后的规则如下:
; extends ((object (pair key: (property_identifier) @key value: (template_string) @html) (#match? @key "template")) (#set! language "html" @html))
或者更简洁的写法:
; extends (object (pair key: (property_identifier) @key value: (template_string) @html (#match? @key "template")) (#set! language "html" @html))
这个规则会先匹配对象中键为template的键值对,将对应模板字符串捕获为@html,最后通过#set!把HTML语言注入到该节点上,实现仅高亮属性值的效果。
内容的提问来源于stack exchange,提问作者Tallboy
相关产品推荐
相关产品推荐

