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");
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With