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

Viewed 14486

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.

4 Answers

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

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

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

A shorter example:

const fullText = document.getText()

const fullRange = new vscode.Range(
    document.positionAt(0),
    document.positionAt(fullText.length - 1)
)
Related