Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add new line programmatically in CodeMirror?

Tags:

codemirror

I need to insert a new line next to my current line number in CodeMirror.

I viewed the documentation but didn't find anything about appending any content at the end of the line.

Please help. :(

like image 482
Melvin Avatar asked Dec 05 '22 07:12

Melvin


2 Answers

Get the current line from the cursor position, and act on it. This should do it (not tested):

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('my new line of code\n', pos); // adds a new line
like image 77
Eliran Malka Avatar answered Feb 03 '23 13:02

Eliran Malka


This should work:

function appendTo(editor, line, text) {
    editor.replaceRange(text, CodeMirror.Pos(line));
}
like image 39
Marijn Avatar answered Feb 03 '23 12:02

Marijn