Home > Back-end >  How to get range of custom word in my VS Code Extension?
How to get range of custom word in my VS Code Extension?

Time:11-06

I want to get the range of a custom word in my VS Code extension, if I hover on it, and if the line of text matches a pattern. This is what I've written so far:

vscode.languages.registerHoverProvider('.mylanguage', {
    provideHover(document, position, token) {
        // define `hoverRange` somewhere here
        const hoverLineText = document.lineAt(position.line).text;
        const pattern = new RegExp("\\w \\s{0,}\\(.{0,}\\s{0,}\\)");
        if(pattern.test(hoverLineText)){
            hoverRange = document.getWordRangeAtPosition(position, pattern);
        }
        console.log(hoverRange);
        //etc. ...

I am expecting that, if you write in the editor something like myFunction ( ), and you hover on any position of that string (e.g. even on the whitespace), the console will output hoverRange, which will take into account the position of the closing parenthesis ), as well.

However, if I hover on the whitespace, nothing is outputted to the console. Instead, I need to hover on myFunction, so that I can get the whole range of the string.

How can I make my VS Code extension treat myFunction ( ) as one single word?

CodePudding user response:

This works for me:

let disposable3 = vscode.languages.registerHoverProvider('plaintext', {
    provideHover(document, position) {

        let hoverRange;
        const hoverLineText = document.lineAt(position.line).text;
        const pattern = new RegExp("\\w \\s*\\(.*\\s*\\)");

        if (pattern.test(hoverLineText)){
            hoverRange = document.getWordRangeAtPosition(position, pattern);
            if (hoverRange) return new vscode.Hover(document.getText(hoverRange), new vscode.Range(position, position));
            else return null;
        }
        else return null;
    }
});
context.subscriptions.push(disposable3);

As you can see the hover works over spaces. But the regex is too lenient so that it does pick up things like

if (asdasdasd)
while(adasd)

since those look like a function calls too.

hover with range

  • Related