How to create VS Code Extension #3 (Syntax Highlight)
INTRODUCTION
Colourful things attract human
To make your extension visually appealing, you need syntax highlighting—a way to color-code different parts of your code.
In simple terms, syntax highlighting tells VS Code how to recognise and style specific elements in your code.
Sounds complicated? Let’s break it down with an example:
To highlight integers, you first need to define what counts as an integer—numbers like 1, 2, 3, …. Then, you tell VS Code to apply a specific colour to them.
Understanding miniscript.tmlanguage.json
In Part 2 I explained that the miniscript.tmlanguage.json file handles syntax highlighting. Now, let's understand how it works.
When you open this file, you'll see a patterns block that looks something like this:
"patterns": [
{"include": "#keywords"},
{"include": "#strings"},
],
Currently, it defines two classes:
Keywords (e.g., if, while)
Strings (a data type for text values)
{"include":"nameofyourclass"},
But how do you create and define a class for syntax highlighting? Let's dive into that next.
Defining Class
In a syntax highlighting definition, you may also see a repository block below "patterns". This is where we define classes for different syntax elements.
"keywords": {
"patterns": [{
"name": "keyword.control.miniscript",
"match": "......."
}]
I haven’t included the full "match" pattern because it can be quite long.
The "name" field is crucial—it assigns a scope name (also called a class name) to the matched pattern. This tells MiniScript that the words or symbols captured in "match" belong to a specific category, such as keywords.
There are many predefined scope names available. To explore them, check out VS Syntax Highlighting
The "match" field contains a regular expression (regex) that defines which words or symbols belong to the class you're creating. This is how you specify what should be highlighted.
There are multiple ways to write a "match" pattern. If you want to learn more about writing effective regex for syntax highlighting, refer to VS Syntax Highlighting for it
And that’s it! With this setup, your syntax highlighting should work seamlessly. 🚀