You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在VS Code扩展中获取光标所在单词的TextMateScope

在VS Code扩展中获取TextMate Scope信息

完全可以做到。VS Code的扩展API提供了对应的能力,能获取和「Developer: Inspect Editor Tokens and Scopes」命令完全一致的TextMate Scope信息。

具体实现步骤如下:

  • 获取当前激活的文本编辑器实例
  • 拿到光标所在的精确位置
  • 调用文档的token化方法,获取对应位置的token数据,其中包含层级化的Scope信息(比如keyword、comment这类标记)

举个简单的代码片段示例:

const editor = vscode.window.activeTextEditor;
if (editor) {
  const position = editor.selection.active;
  // 对光标位置所在行进行token化
  const lineTokens = editor.document.tokenizeRange(new vscode.Range(position.line, 0, position.line + 1, 0));
  // 遍历该行的token,找到包含光标位置的那个
  const targetToken = lineTokens[0].find(token => 
    token.start <= position.character && token.end >= position.character
  );
  if (targetToken) {
    // targetToken.scopes就是当前位置的TextMate Scope数组,和命令显示的层级一致
    console.log(targetToken.scopes);
  }
}

这段代码就能拿到光标位置对应的Scope信息,和内置命令展示的内容完全匹配。

内容的提问来源于stack exchange,提问作者rioV8

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 06:52:34