Home > Net >  API for getting language server info from extension (bracket pairs, function begin/end, ...)
API for getting language server info from extension (bracket pairs, function begin/end, ...)

Time:05-18

I'm currently writing an extension for VSCode which needs to have some good knowledge about the currently shown code in the editor and I'm wondering if there is some API available which can give me the needed information (e.g. from the current language server) or if I have to do the heavy lifting myself by implementing all the needed code parsing etc.

What I need in detail is the following:

  • Given is a position in code (line col no)
  • What I'd like to know about the given position:
    • Is pos inside a function and if so, where does the function start & end?
    • Is pos inside a string and if so, where does the string start & end?

The extension is going to provide some kind of "vim selection light".

CodePudding user response:

You can have only half of that via VS Code APIs.

Is pos inside a function and if so, where does the function start & end?

Using the vscode.executeDocumentSymbolProvider command, you can gather all functions from a file and check if the current position is inside one of the functions.

Something like this to retrieve the functions:


    const symbolsToFind = [SymbolKind.Function, SymbolKind.Method, SymbolKind.Constructor];

    const docSymbols = await commands.executeCommand(
        'vscode.executeDocumentSymbolProvider',
        window.activeTextEditor.document.uri
    ) as DocumentSymbol[];

    const docSymbolsFunctionsMethods = docSymbols
        ? docSymbols.filter(symbol => symbolsToFind.includes(symbol.kind))
        : undefined;

Each Symbol provides you with a Range, which defines the start and end of the function declaration and body.

Be aware that you will probably need a recursive approach (each Symbol can contain other Symbols). A complete sample is available on my Separators extension (https://github.com/alefragnani/vscode-separators/blob/b6d515847bbaccf6395b24f9fdf82c373cb24fd7/src/symbols.ts#L51)

Is pos inside a string and if so, where does the string start & end?

Unfortunately, there is no API for that, as VS Code does not expose language tokens or the AST. So, you will have to deal with it yourself, maybe using regex.

Hope this helps

  • Related