Home > Net >  How to highlight variable name dynamically using the VS Code Extension API?
How to highlight variable name dynamically using the VS Code Extension API?

Time:10-28

I want my VS Code extension to be able to highlight a variable name when it is initialized. For example, when x = 4, I want x to be highlighted in red. This is the code I have written so far:

extension.ts

context.subscriptions.push(
    vscode.workspace.onDidChangeTextDocument((event) => {
        const activeEditor = vscode.window.activeTextEditor;
        if(activeEditor){
            const currentLineIndex = activeEditor.selection.active.line;
            const lineContent = activeEditor.document.lineAt(currentLineIndex);
            const variableRegularExpression = new RegExp("^\\s{0,}[a-zA-Z]{1,}[0-9]{0,}\\s{0,}=\\s{0,}[a-zA-Z0-9]{1,}\\s{0,}(//[a-zA-Z0-9]){0,}$");
            if(variableRegularExpression.test(lineContent.text)){
                const variableName = lineContent.text.split('=')[0].trim();
                const startIndex = lineContent.text.indexOf(variableName);
                const endIndex = startIndex   variableName.length;
                const variableRange = new vscode.Range(currentLineIndex, startIndex, currentLineIndex, endIndex);
            }
        }
    })
);

As you can see, I am trying to get the extension to understand dynamically when a variable is initialized. I compare the line currently being edited to a regular expression, and if there is a match, the range of the variable is extracted.

Is there a way to highlight this range with a color dynamically? Is this a good way of implementing dynamic highlighting for variable initialization?

CodePudding user response:

What you are looking for is Semantic Token Highlighting.

You can implement a Semantic Token Highlighter which reads from an array of objects with the position of the text you wish to highlight.

  • Related