Search code examples
visual-studio-codevscode-extensionsvscode-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:

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.


Solution

  • 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);
    }