获取 VS 代码扩展中的当前亮点

Get current Highlight in VS Code Extension

我说的不是当前选择,可以通过vscode.window.activeTextEditor.selection访问。

当光标在标识符、变量名等内部时,它会高亮显示,如截图所示:

这个高亮对象叫什么?我如何访问它?

搜索从 "highlight" 到 "identifier" 以及其他任何内容,答案更加明显。 TextDocument 有一个 getWordRangeAtPosition 方法,它获取一个位置和 returns 单词的范围。

const editor = vscode.window.activeTextEditor;
let cursorPosition = editor.selection.start;
let wordRange = editor.document.getWordRangeAtPosition(cursorPosition);
let highlight = editor.document.getText(wordRange);
// highlight will now contain the currently highlighted word

您正在展示的东西叫做 Document Highlight。其他实例(在本例中为 colorData)也将突出显示。 @Rene Roth 的回答可能就是你想要的答案。正如@Gama11 所写,使用不带第二个参数的 getWordRangeAtPosition 使用语言的 "word pattern"。然而,文档突出显示不一定是单个单词。

据我所知,您无法列出所有亮点? (我只是想出它们用于我的第一个扩展。)

要像这样突出显示,您需要使用 registerDocumentHighlightProviderprovideDocumentHighlightsDocumentHighlightKind 可用于提供不同的突出显示颜色(例如,当突出显示的变量的实例位于等号的右侧或左侧时,即读取或写入,或出于其他一些区分原因)。我已成功使用 DocumentHighlightKind 来显示包含在另一个中的突出显示。