Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 380
Jeremy Meng Avatar asked Jul 20 '17 01:07

Jeremy Meng


People also ask

How do you select all text in VS Code?

Ctrl + Shift + L to select all occurrences of current selection.

How do you wrap long lines in VS Code?

You can toggle word wrap for the VS Code session by pressing a key combination. On Windows or Linux, simply press Alt+Z. On MacOS, you can also press Option ⌥ + Z.


3 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);
like image 139
RichS Avatar answered Oct 22 '22 13:10

RichS


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

like image 21
js-kyle Avatar answered Oct 22 '22 14:10

js-kyle


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));
like image 10
Jan Dolejsi Avatar answered Oct 22 '22 13:10

Jan Dolejsi