我的应用程序中嵌入了摩纳哥代码编辑器.
如何以编程方式在特定行上插入文本?
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.. 12
使用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]);
kosinix.. 9
一个更可靠的解决方案是使用Selection API代替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]);
如果编辑器中已经有预先选择的文本,则插入将替换它,我认为这是正确的行为。
使用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]);
一个更可靠的解决方案是使用Selection API代替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]);
如果编辑器中已经有预先选择的文本,则插入将替换它,我认为这是正确的行为。