I want to make a small VS Code extension to add syntax highlighting to a handful of custom keywords in C/C++ code.
I am trying to do that with an injection grammar into the source.c
and source.cpp
language scopes, following the VS Code syntax highlighting guide. Per the guide, prefixing the injection selector scope with L:
means that "[the] injected grammar's rules will be applied before any existing grammar rules". This seems to work fine with C code, but in C++ it some (but not all) grammar rules override my injected grammar.
For a MWE, suppose I want to add a par_for
keyword for parallel loops.
I define the extension in package.json
:
{
...
"contributes": {
"grammars": [{
"scopeName": "parfor.injection",
"path": "./syntaxes/parfor.injection.json",
"injectTo": ["source.c", "source.cpp"]
}]
}
}
and the injected grammar in syntaxes/parfor.injection.json
to apply my new scope keyword.control.parfor
to all instances of par_for
(except in strings and comments):
{
"scopeName": "parfor.injection",
"injectionSelector": [
"L:source.c -string -comment",
"L:source.cpp -string -comment"
],
"patterns": [
{ "include": "#parfor-keyword" }
],
"repository": {
"parfor-keyword": {
"name": "keyword.control.parfor",
"match": "\\bpar_for\\b"
}
}
}
In C, things work as expected:
But in C++, par_for
gets treated like a function name:
The screenshots were taken from a VS Code testing instance with all extensions disabled.
The issue in C++ is apparently triggered by the parenthesis following par_for
; if I write, say, par_for foo
, then the keyword.control.parfor
scope is applied to par_for
as expected.
Is there a way to ensure my injected grammar pattern takes precedence over whatever the C++ grammar is doing?