在给定的光标位置插入新文本

Che*_*tan 13 codemirror

我正在为我的新语言模式定制代码镜像.作为这种新模式实现的一部分,我正在编写一个新工具栏,用户可以在其中选择一些文本并说出插入.此命令应在单击工具栏之前插入用户正在键入的文本.

我找不到任何API级别的支持.如果还有其他任何方式可以帮助我吗?

基本上获取当前光标位置编号和当前光标所在的位置.可能是一个Position对象

用于插入文本的API,例如 insertText("Text", PositionObject)

Sue*_*zio 12

我是这样做的:

function insertTextAtCursor(editor, text) {
    var doc = editor.getDoc();
    var cursor = doc.getCursor();
    doc.replaceRange(text, cursor);
}
Run Code Online (Sandbox Code Playgroud)


Dad*_*ane 10

要在最后添加新行 -

function updateCodeMirror(data){
    var cm = $('.CodeMirror')[0].CodeMirror;
    var doc = cm.getDoc();
    var cursor = doc.getCursor(); // gets the line number in the cursor position
    var line = doc.getLine(cursor.line); // get the line contents
    var pos = { // create a new object to avoid mutation of the original selection
        line: cursor.line,
        ch: line.length - 1 // set the character position to the end of the line
    }
    doc.replaceRange('\n'+data+'\n', pos); // adds a new line
}
Run Code Online (Sandbox Code Playgroud)

通话功能

updateCodeMirror("This is new line");
Run Code Online (Sandbox Code Playgroud)


小智 7

改进的功能,如果选择存在,则替换文本,如果没有,则插入当前光标位置

function insertString(editor,str){

        var selection = editor.getSelection();

        if(selection.length>0){
            editor.replaceSelection(str);
        }
        else{

            var doc = editor.getDoc();
            var cursor = doc.getCursor();

            var pos = {
               line: cursor.line,
               ch: cursor.ch
            }

            doc.replaceRange(str, pos);

        }

    }
Run Code Online (Sandbox Code Playgroud)