Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I insert text into a Monaco Editor?

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");
like image 718
Doug Avatar asked Jan 13 '17 20:01

Doug


People also ask

How do I use editor in react in Monaco?

The easiest way to use the react-monaco-editor with create-react-app is to use the react-app-rewired project. For setting it up, the following steps are required: Install react-app-rewired : npm install -D react-app-rewired. Replace react-scripts by react-app-rewired in the scripts section of your packages.

What is the use of Monaco editor?

Monaco editor is the editor that powers Visual Studio Code. It is licensed under the MIT License and supports IE 11, Edge, Chrome, Firefox, Safari, and Opera. This editor is very convenient to write markdown, json, and many other languages. It provides colorization, auto-complete, and lots of other features.


1 Answers

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.

like image 198
kosinix Avatar answered Sep 29 '22 18:09

kosinix