Getting locations of the variable declarations

流过昼夜 提交于 2019-12-24 07:35:19

问题


I am developing an extension which requires me to get the locations of the variable declarations. For example,

var x = 5;
console.log(x);

Does the VS Code API provide functionality like getVariableLocations() which will return the position of the var x = 5;?


回答1:


You can get the document symbols by running 'vscode.executeDocumentSymbolProvider'.

Here's an example that executes the command on the active document, and then converts the nested list of symbols (each DocumentSymbol can have children) into a flat list filtered by SymbolKind.Variable:

function findVars(symbols: vscode.DocumentSymbol[]): vscode.DocumentSymbol[] {
  var vars =
      symbols.filter(symbol => symbol.kind === vscode.SymbolKind.Variable);
  return vars.concat(symbols.map(symbol => findVars(symbol.children))
                         .reduce((a, b) => a.concat(b), []));
}
var activeEditor = vscode.window.activeTextEditor;
if (activeEditor !== undefined) {
  vscode.commands
      .executeCommand<vscode.DocumentSymbol[]>(
          'vscode.executeDocumentSymbolProvider', activeEditor.document.uri)
      .then(symbols => {
        if (symbols !== undefined) {
          for (const variable of findVars(symbols)) {
            console.log(variable.name);
          }
        }
      });
}

When running this on this code snippet itself, it logs activeEditor, vars and variable. You can check the position with DocumentSymbol.range.



来源:https://stackoverflow.com/questions/57345173/getting-locations-of-the-variable-declarations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!