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.