简体   繁体   English

如何从 VSCode 扩展 API 中获取突出显示的文本

[英]How to get highlighted text from VSCode Extension API

I'm using the VSCode API to build an extension, but I've found no documentation that covers how to grab the user's highlighted text, such as that shown below:我正在使用 VSCode API 来构建扩展,但我没有找到任何文档涵盖如何获取用户突出显示的文本,如下所示:

在此处输入图像描述

There is a similar question regarding the word the cursor is currently on , but I would like to grab the entirety of the highlighted text. 关于光标当前所在的单词有一个类似的问题,但我想获取整个突出显示的文本。

You can use the active text editor using the activeTextEditor API call and then use the selections field to get your selection ranges.您可以使用activeTextEditor API 调用来使用活动文本编辑器,然后使用selections字段来获取您的选择范围。 Your code would look something like this:您的代码将如下所示:

let editor = vscode.window.activeTextEditor
let selections = editor.selections

VSCode API Docs: https://code.visualstudio.com/api/references/vscode-api#TextEditor VSCode API 文档: https ://code.visualstudio.com/api/references/vscode-api#TextEditor

The solution is a modified version of Mark's answer here.解决方案是Mark's answer here 的修改版本。

const editor = vscode.window.activeTextEditor;
const selection = editor.selection;
if (selection && !selection.isEmpty) {
    const firstSelectedCharacter = selection.start.character;
    const selectionRange = new vscode.Range(selection.start.line, firstSelectedCharacter, selection.end.line, selection.end.character);
    const highlighted = editor.document.getText(selectionRange);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM