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:
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.
CodePudding user response:
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
CodePudding user response:
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 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);
}