VS Code extension Api to get the Range of the whole text of a document?

12,639

Solution 1

This may not be robust, but I've been using this:

var firstLine = textEditor.document.lineAt(0);
var lastLine = textEditor.document.lineAt(textEditor.document.lineCount - 1);
var textRange = new vscode.Range(firstLine.range.start, lastLine.range.end);

Solution 2

I'm hoping this example might help:

var editor = vscode.window.activeTextEditor;
if (!editor) {
    return; // No open text editor
}

var selection = editor.selection;
var text = editor.document.getText(selection);

Source: vscode extension samples > document editing sample

Solution 3

You could create a Range, which is just one character longer than the document text and use validateRange to trim it to the correct Range. The method finds the last line of text and uses the last character as the end Position of the Range.

let invalidRange = new Range(0, 0, textDocument.lineCount /*intentionally missing the '-1' */, 0);
let fullRange = textDocument.validateRange(invalidRange);
editor.edit(edit => edit.replace(fullRange, newText));

Solution 4

A shorter example:

const fullText = document.getText()

const fullRange = new vscode.Range(
    document.positionAt(0),
    document.positionAt(fullText.length - 1)
)
Share:
12,639
Jeremy Meng
Author by

Jeremy Meng

Updated on July 01, 2022

Comments

  • Jeremy Meng
    Jeremy Meng almost 2 years

    I haven't found a good way to do it. My current approach is to select all first:

    vscode.commands.executeCommand("editor.action.selectAll").then(() =>{
        textEditor.edit(editBuilder => editBuilder.replace(textEditor.selection, code));
        vscode.commands.executeCommand("cursorMove", {"to": "viewPortTop"});
    });
    

    which is not ideal because it flashes when doing selection then replacement.