Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove selection after replace in vscode API

while creating an extension for vscode I got stuck in selection, now the problem is when I replace some range of textEditor through an api it replaces that range as well as make that range selected. For snippets this is a good idea but my extension requirement is not to select replaced text, I searched in api but did't find anything related to remove text selection (Selection occurs when the document is empty)

editor.edit((editBuilder)=>{ //editor is an object of active text editor
        editBuilder.replace(textRange,text)   // text = 'dummydummydummy'
    }) //after this I got the following output

enter image description here

like image 666
Adi Avatar asked Jan 19 '18 05:01

Adi


People also ask

How do you replace a word in VS Code?

You can use the Find control in code or text windows, such as Output windows and Find Results windows, by selecting Edit > Find and Replace or pressing Ctrl+F.


3 Answers

editor.edit(builder => {
    builder.replace(selection, newStr);
})
// The edit call returns a promise. When that resolves you can set 
// the selection otherwise you interfere with the edit itself. 
// So use "then" to sure edit call is done; 
.then(success => {
    console.log("success:", success);
    // Change the selection: start and end position of the new
    // selection is same, so it is not to select replaced text;
    var postion = editor.selection.end; 
    editor.selection = new vscode.Selection(postion, postion);
});
like image 78
fun90 Avatar answered Nov 07 '22 17:11

fun90


I believe that this is happening because the edit is being applied within the current selection. edit returns a promise that is resolved when the edit is applied, and you can use this to set the selection after the edit is successful:

editor.edit((editBuilder) => {
    editBuilder.replace(textRange, text)
}).then(success => {
    if (success) {
        // make selection empty
        editor.selection.active = editor.selection.anchor
    }
})
like image 32
Matt Bierner Avatar answered Nov 07 '22 17:11

Matt Bierner


let editor = vscode.window.activeTextEditor;
let selection = editor.selection;
editor.edit(builder => {
    builder.replace(selection, newStr);
});

see: TextEditorEdit API Doc

like image 38
熊玲聪 Avatar answered Nov 07 '22 16:11

熊玲聪