Updating editor.selections in vscode Extension

Viewed 504

I am currently working on a small vscode extension. Within the extension code I want to move every selection of a multi selection one character to the right by accordingly updating the TextEditor.selections array that holds all selections that are currently present in the GUI.

Setting TextEditor.selection to a new vscode.Selection allows updating the primary selection of the TextEditor.selections array. This way, the primary selection in the GUI is updated correctly. However, setting TextEditor.selections[n] to a new selection does not result in an update in the GUI. Hence, I can currently only update the primary selection instead of all of them. It seems like setting the shorthand TextEditor.selection issues a GUI update whereas setting TextEditor.selections[n] does not.

So, how can I update all selections in TextEditor.selections?

Here is my code for updating the selections:

import * as vscode from "vscode";

function updateSelections(
  editor: vscode.TextEditor,
  selections: vscode.Selection[]
) {
  selections.forEach((sel) => {
    const selStart = sel.start;
    const selEnd = sel.end;

    // TODO: only primary selection appears to be editable ; "editor.selections[n] = something" does not change anything
    // This works
    editor.selection = new vscode.Selection(
      selStart.translate(0, 1),
      selEnd.translate(0, 1)
    );
    // This does not work
    editor.selections[0] = new vscode.Selection(
      selStart.translate(0, 1),
      selEnd.translate(0, 1)
    );
  });
}

1 Answers

If you assign a new Array with the updated selections it works

editor.selections = editor.selections.map( sel => new vscode.Selection(sel.start.translate(0,1), sel.end.translate(0,1)));
Related