分类目录归档:CodeMirror使用示例

CodeMirror中的{line, ch}对象

在CodeMirror,经常会遇到这样结构的对象:

{
    line: integer,
    ch: integer
}

有时候是作为参数传给函数,也有的时候是某个函数的返回值。需要注意的是,对象中的linech分别表示编辑器内容的行号和列号,它们都是从0开始计数的。例如,要取从第6行第3个字符第13行第22个字符的内容,那么就要这样写:

var contentRange = editor.getRange({line: 5, ch: 2}, {line: 12, ch:21});

CodeMirror 代码二叉树结构可视化



代码二叉树结构可视化


var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  lineWrapping: true
});
var updateTimeout;
editor.on("change", function(cm) {
  clearTimeout(updateTimeout);
  updateTimeout = setTimeout(updateVisual, 200);
});
updateVisual();

function updateVisual() {
  var out = document.getElementById("output");
  out.innerHTML = "";

  function drawTree(out, node) {
    if (node.lines) {
      out.appendChild(document.createElement("div")).innerHTML =
        "<b>leaf</b>: " + node.lines.length + " lines, " + Math.round(node.height) + " px";
      var lines = out.appendChild(document.createElement("div"));
      lines.style.lineHeight = "6px"; lines.style.marginLeft = "10px";
      for (var i = 0; i < node.lines.length; ++i) {
        var line = node.lines[i], lineElt = lines.appendChild(document.createElement("div"));
        lineElt.className = "lineblock";
        var gray = Math.min(line.text.length * 3, 230), col = gray.toString(16);
        if (col.length == 1) col = "0" + col;
        lineElt.style.background = "#" + col + col + col;
        lineElt.style.width = Math.max(Math.round(line.height / 3), 1) + "px";
      }
    } else {
      out.appendChild(document.createElement("div")).innerHTML =
        "<b>node</b>: " + node.size + " lines, " + Math.round(node.height) + " px";
      var sub = out.appendChild(document.createElement("div"));
      sub.style.paddingLeft = "20px";
      for (var i = 0; i < node.children.length; ++i)
        drawTree(sub, node.children[i]);
    }
  }
  drawTree(out, editor.getDoc());
}

CodeMirror 单词自动完成




单词自动完成

alt-space(注:官方这里用的是ctrl-space,因为在我们日常输入中这个组合通常用于切换输入法,所以我改了一下)激活自动完成功能。自动完成使用了模块anyword-hint.js

      CodeMirror.commands.autocomplete = function(cm) {
        cm.showHint({hint: CodeMirror.hint.anyword});
      }
      var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
        lineNumbers: true,
        extraKeys: {"Alt-Space": "autocomplete"}
      });

CodeMirror 高亮光标所在行



行高亮

高亮光标所在行

var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  mode: "application/xml",
  styleActiveLine: true,
  lineNumbers: true,
  lineWrapping: true
});

CodeMirror代码自动换行以及代码框自适应高度

设置自动换行

editor.setOption('lineWrapping', true);

设置自动高度

editor.setSize('auto', 'auto');

示例请看 http://sojs.hyjiacan.com/view/3