简体   繁体   English

如何将文本插入摩纳哥编辑器?

[英]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");

A more robust solution would be to use the Selection API instead of Position更强大的解决方案是使用Selection API 而不是 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.如果编辑器中已经有预先选择的文本,插入将替换它,在我看来,这是正确的行为。

Using the executeEdits API使用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]);

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`});

A more natural solution (as mentioned above) can be the to use the executeEdits method that comes with monaco and use a specific range with line numbers and column numbers, because in the examples they are always using the first line:更自然的解决方案(如上所述)可以是使用 monaco 附带的executeEdits方法,并使用带有行号和列号的特定范围,因为在示例中它们始终使用第一行:

const startLineNumber = 15 // Line number in which the content will start being typed
const startColumn = 5 // Column number in which the content will start being typed
const endLineNumber = 18 // Line number in which the text will finish
const endColumn = 25 
const text = "This is the new text" // The content going to be added


const range = new monaco.edito.Range(startLineNumber, startColumn, endLineNumber, endColumn); // It will go to the specific position of the editor

const id = { major: 1, minor: 1 }; // Required generic id

const editOperation = {identifier: id, range: range, text: text, forceMoveMarkers: true}; // The operation going to be performed

monaco.editor.executeEdits("custom-code", [ editOperation ]); // Runs the instruction

The good part of the code above is that it can add, delete, update and replace existing code, so it will be very efficient and the end user will see it like if he/she was typing.上面代码的好处是它可以添加、删除、更新和替换现有代码,因此它会非常高效,最终用户会看到它就像他/她正在打字一样。

I've had issues implementing this with react and typescript so hopefully this could help someone.我在使用 react 和 typescript 实现这一点时遇到了问题,所以希望这可以帮助某人。

import Editor, { Monaco, OnMount } from '@monaco-editor/react';
import { editor, languages } from 'monaco-editor';

...

const CustomEditor: React.FC = () => {

    const [monacoInstance, setMonacoInstance] = React.useState<editor.IStandaloneCodeEditor | null>(null);

    const insertText = (text: string) => {
        if (monacoInstance) {
            const selection = monacoInstance.getSelection();
            const id = { major: 1, minor: 1 };
            const op = {
                identifier: id,
                range: {
                    startLineNumber: selection?.selectionStartLineNumber || 1,
                    startColumn: selection?.selectionStartColumn || 1,
                    endLineNumber: selection?.endLineNumber || 1,
                    endColumn: selection?.endColumn || 1,
                },
                text,
                forceMoveMarkers: true,
            };
            monacoInstance.executeEdits('my-source', [op]);
        }
    };

    const editorMount: OnMount = (editorL: editor.IStandaloneCodeEditor) => {
        setMonacoInstance(editorL);
    };

...

        <Editor
            onMount={editorMount}

...

        <StyledButton // styled comp
            onClick={() => {insertText('inserted text');}}
        >
            insert text
        </StyledButton>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在摩纳哥编辑器中插入片段? - How to insert snippet in Monaco Editor? 如何使用 API 在 Monaco Editor 中格式化 JSON 代码? - How do I format JSON code in Monaco Editor with API? 如何将 javascript 自动完成添加到摩纳哥编辑器的 markdown 模式? - How do I add javascript autocomplete to markdown mode of monaco editor? 如何使用 Playwright 在摩纳哥编辑器中插入代码? - How to insert code in monaco editor using Playwright? 如何使用量角器在monaco编辑器中插入代码? - How to insert code in monaco editor using the protractor? 如何使用javascript将焦点处的文本插入markitup编辑器? - How do I insert text at the focus into a markitup editor with javascript? 我如何在我的反应构建中为摩纳哥编辑器的 loader.js 及其对本地主机的依赖项提供服务 - How do I serve Monaco editor's loader.js and its dependencies on localhost in my react build 如何在 React 中获取嵌入式 Monaco 编辑器的行数? (包括包装) - How do I get the line count of an embedded Monaco editor in React? (including wrapping) 如何使用 testcafe 在 monaco 编辑器上删除或替换文本? - How to delete or replace text on monaco editor using testcafe? 您如何在 Monaco 编辑器中处理来自 IViewZone 的输入事件? - How do you process input events from an IViewZone in the Monaco Editor?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM