How to get highlighted text from VSCode Extension API

Viewed 95

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:

enter image description here

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.

2 Answers

The solution is a modified version of Mark's answer here.

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

You can use the active text editor using the activeTextEditor API call and then use the selections field to get your selection ranges. 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

Related