14

I have a monaco code editor embedded in my app.

How do I programmatically insert text on a particular line?

var editor = monaco.editor.create(document.getElementById("container"), {
    value: "// First line\nfunction hello() {\n\talert('Hello world!');\n}\n// Last line",
    language: "javascript",

    lineNumbers: false,
    roundedSelection: false,
    scrollBeyondLastLine: false,
    readOnly: false,
    theme: "vs-dark",
});
// how do I do this?
editor.insertText("FOO");
Doug
  • 10,752
  • 11
  • 57
  • 97

3 Answers3

19

A more robust solution would be to use the Selection API instead of Position

var selection = editor.getSelection();
var id = { major: 1, minor: 1 };             
var text = "XXX";
var op = {identifier: id, range: selection, text: text, forceMoveMarkers: true};
editor.executeEdits("my-source", [op]);

If there is already a pre-selected text in the editor, the insert will replace it, which is in my opinion, the correct behavior.

Jakub Zawiślak
  • 3,892
  • 2
  • 14
  • 17
kosinix
  • 1,481
  • 16
  • 19
13

Using the executeEdits API

var line = editor.getPosition();
var range = new monaco.Range(line.lineNumber, 1, line.lineNumber, 1);
var id = { major: 1, minor: 1 };             
var text = "FOO";
var op = {identifier: id, range: range, text: text, forceMoveMarkers: true};
editor.executeEdits("my-source", [op]);
Doug
  • 10,752
  • 11
  • 57
  • 97
  • 2
    Just like to say that there's also a method off the model called `pushEditOperations`, which is similar to `editor.executeEdits`. Quite helpful if you have multiple models and want to update one that isn't the editor's current model. – Benny Hinrichs Jul 03 '19 at 17:29
0

To insert text at the cursor, there is this very simple way. I use it a lot to make Snippet toolbars:

editor.trigger('keyboard', 'type', {text: "test"});

It will replace the text if text is selected.

And you can also add multiple line text this way:

editor.trigger('keyboard', 'type', {text: `text on
multiple
line`});
Dharman
  • 21,838
  • 18
  • 57
  • 107
Miky Dal
  • 49
  • 4