Search code examples
monaco-editor

Insert line in Monaco editor preserving selection


I'd like to insert a line of text before the existing text at a given line number. I'm currently using this:

const insertionRange = new monaco.Range(
    lineNo, this.getModel().getLineMinColumn(lineNo),
    lineNo, this.getModel().getLineMinColumn(lineNo),
);
this.executeEdits("", [{ range: insertionRange, text: insertMe + "\n" }]);

However I think I also need to push the insertion cursor(s) and any selections that follow the text that I inserted. So if before I had:

1  So we beat on,
2  borne back ceaselessly into the past.|

after inserting a line before line 2, I want the insertion point to be at the end of line 3:

1  So we beat on,
2  boats against the current,
3  borne back ceaselessly into the past.|

ICodeEditor.executeEdits does take an optional third ICursorStateComputer option which can be used to modify the cursor after an edit takes place, but I'm not sure how to use it.

There is also an InsertLineBeforeAction which I might be able to use instead of doing this manually.


Solution

  • One possible option is to compute new selections, maybe something like this:

    const newSelections = this.getSelections().map((s) => {
        if (s.endLineNumber >= lineNo) s.endLineNumber ++;
        if (s.positionLineNumber >= lineNo) s.positionLineNumber ++;
        if (s.selectionStartLineNumber >= lineNo) s.selectionStartLineNumber ++;
        if (s.startLineNumber >= inputLineNum) s.startLineNumber ++;
        return s;
    });
    

    then pass newSelections as the third argument to executeEdits.