Execute “go to Symbol in File” programmatically in

2020-05-03 12:07发布

问题:

Is it possible to jump to an existing symbol in file from Extension?

Something of the sort:

goToSymbol(symbol: string)

P.S. I don't want to provide a DocumentSymbolProvider. How to use existing ones?

回答1:

async function getSymbols(document: TextDocument): Promise<DocumentSymbol[]> {
    return await commands.executeCommand<DocumentSymbol[]>('vscode.executeDocumentSymbolProvider', document.uri) || [];
}

async function goToSymbol(document: TextDocument, symbolName: string) {
    const symbols = await getSymbols(document);
    const findSymbol = symbols.find(symbol => symbol.name === symbolName);
    const activeTextEditor = window.activeTextEditor;
    if (findSymbol && activeTextEditor) {
        activeTextEditor.revealRange(findSymbol.range, vscode.TextEditorRevealType.AtTop);
        activeTextEditor.selection = new Selection(findSymbol.range.start, findSymbol.range.start);
    }
}

Note: the code above should be enough to go to symbol of 1 lvl.

Nested symbols accessible as .children (on every element of symbols)