获取变量声明的位置 [英] Getting locations of the variable declarations

查看:40
本文介绍了获取变量声明的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个需要我获取变量声明位置的扩展.例如,

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

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

VS Code API 是否提供像 getVariableLocations() 这样的功能,它会返回 var x = 5; 的位置?

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

推荐答案

您可以获得 文档符号 通过运行 'vscode.executeDocumentSymbolProvider'.

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

这里有一个例子,它在活动文档上执行命令,然后将嵌套的符号列表(每个 DocumentSymbol 可以有 children)转换成一个由SymbolKind.Variable:

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);
          }
        }
      });
}

在这个代码片段本身上运行它时,它会记录 activeEditorvarsvariable.您可以使用 DocumentSymbol.range 检查位置.

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

这篇关于获取变量声明的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆