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