How to insert text into the Monaco editor?

I have a monaco code editor built into my application.

How to programmatically insert text into a specific 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"); 
+5
source share
2 answers

Using 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]); 
+6
source

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

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

If the editor already has the selected text, the insert will replace it, which, in my opinion, is the correct behavior.

+1
source

Source: https://habr.com/ru/post/1262771/


All Articles