Inserting a new text at given cursor position

How about replaceSelection (http://codemirror.net/doc/manual.html#replaceSelection)?

doc.replaceSelection(replacement: string, ?select: string) Replace the selection(s) with the given string. By default, the new selection ends up after the inserted text. The optional select argument can be used to change this—passing "around" will cause the new text to be selected, passing "start" will collapse the selection to the start of the inserted text.


Here's how I did it:

function insertTextAtCursor(editor, text) {
    var doc = editor.getDoc();
    var cursor = doc.getCursor();
    doc.replaceRange(text, cursor);
}

To add the new line at the end -

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
}

Call function

updateCodeMirror("This is new line");

Tags:

Codemirror