Home > Software engineering >  How do I add extra syntax highlighting to an existing language?
How do I add extra syntax highlighting to an existing language?

Time:05-03

I want to add some extra language features, such as liquid language support inside JavaScript:

var firstName = "<% User.firstName %>";
var lastName = "<% User.firstName %>";

I browsed around a bit and I found this folder in the vscode repository: https://github.com/microsoft/vscode/tree/main/extensions/javascript

It's basically the JavaScript tmLanguage grammar rules, so I had this idea to create a new javascript file format (.pjs) and apply the same tmLanguage file as well as add these new rules:

    "pk-liquid-expression": {
        "begin": "<%",
        "beginCaptures": {
            "0": {
                "name": "storage.type.primitive.java"
            }
        },
        "end": "%>",
        "endCaptures": {
            "0": {
                "name": "storage.type.primitive.java"
            }
        },
        "name": "storage.type.primitive.java"
    },

And this worked, however now my pjs files don't have any of the language features such as errors and warnings.

I think my solution is not very forward-thinking however, so is it possible to just edit the current JavaScript tmLanguage rules and add these new tokens?

Thank you.

CodePudding user response:

One solution is to inject the "liquid language" into the Javascript language definition. Main steps for that is to define a grammar to inject and creating a selector which defines when to inject your grammar:

{
  "contributes": {
    "grammars": [
      {
        "path": "./syntaxes/injection.json",
        "scopeName": "todo-comment.injection",
        "injectTo": ["source.js"]
      }
    ]
  }
}

See also: How to properly inject grammar extension in vscode (so it works)?

  • Related