How to get range of custom word in my VS Code Extension?


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,}\\)");
            hoverRange = document.getWordRangeAtPosition(position, pattern);
        //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?


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;

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)

since those look like a function calls too.

hover with range

Answered By – Mark

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published