如何在CodeMirror中以编程方式添加新行?

时间:2014-03-24 12:48:27

标签: codemirror

我需要在CodeMirror中的当前行号旁边插入一个新行。

我查看了文档,但没有找到任何关于在行末添加任何内容的内容。

请帮忙。 :(

3 个答案:

答案 0 :(得分:7)

从光标位置获取当前行,并对其进行操作。这应该做(未经测试):

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

答案 1 :(得分:3)

这应该有效:

function appendTo(editor, line, text) {
    editor.replaceRange(text, CodeMirror.Pos(line));
}

答案 2 :(得分:0)

在最后添加新行 -

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
    console.log(doc);
    var pos = { // create a new object to avoid mutation of the original selection
        line: (doc.size+5),
        ch: line.length - 1 // set the character position to the end of the line
    }
    doc.replaceRange('\n'+data+'\n', pos); // adds a new line
}

通话功能

updateCodeMirror("This is new line");
相关问题