8

I'm adding some text to the Monaco editor using a button outside it (i.e. "hello world") and then I'm trying to set the cursor position to the next line.

I tried using the "setPosition({column:x, lineNumber:y})" function from the editor, but it doesn't work.

This is how I'm implementing it:

insertInPosition(textToInsert:string, cursorPosition:any){
    this.editorInstance.setPosition(cursorPosition);
    var allInstructions = this.instructionSet.split("\n")
    allInstructions.splice(cursorPosition.lineNumber - 1, 0, textToInsert);
    allInstructions.splice(cursorPosition.lineNumber, 1);
    allInstructions = allInstructions.join("\n");
    this.editorInstance.setPosition(cursorPosition);
}

I expect to see the cursor in the line and column defined by cursorPosition, but I actually see that the cursor points to line 1 and column 1 (At the top of the editor).

I also tried to use the same api editor.setPosition() inside the onDidChangeModelContent() method, but it doesn't works. And when I print in console the editor.getPosition() I receive the correct positions.

Any idea on what could be wrong?

2 Answers 2

7
this.editor?.trigger('keyboard', 'type', {text: 'value'});
this.editor?.focus();
const position: any  = this.editor?.getPosition();
this.editor?.setPosition(position);
Sign up to request clarification or add additional context in comments.

1 Comment

Please provide some explanation to your code.
1

Some monaco editor events (including onDidChangeModelContent()), change cursor position after executing. I took this information from here.

To prevent it from happening, you can do something like this:

var overridenPosition = null;

editor.onDidChangeModelContent(e => {
    if (/* your condition here */) {
        // your logic here
        overridenPosition = { lineNumber: 4, column: 2 }; // put your value here
    }
});

editor.onDidChangeCursorPosition(e => {
    if (overridenPosition != null) {
        editor.setPosition(overridenPosition);
        overridenPosition = null;
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.