function insertText(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 = { line: cursor.line }; if (line.length === 0) { // check if the line is empty // add the data doc.replaceRange(data, pos); } else { // add a new line and the data doc.replaceRange("\n" + data, pos); } }