解决CodeMirror编辑器Tab转空格问题

CodeMirror默认

最近用CodeMirror做了个编辑器,遇到一个问题: 就像这样:

See the Pen codemirror-1 by 麻凯倩 (@makaiqian) on CodePen.

默认的Tab是不会转为空格的,需要处理。

codemirror-no


不是想要的结果

网上和官网提供找的方法是:

editor.setOption("extraKeys", {  
  Tab: function(cm) {
    var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
    cm.replaceSelection(spaces);
  }
});

实践了一下,还是会有一个问题:
选中多行代码缩进的时候,选中的代码也会被转为空格,就被删了!!而不是理想中的选中几行都缩进。


解决方案

经过了几天的积累,终于找到了解决方案:

editor.setOption("extraKeys", {  
    Tab: newTab
});

function newTab(cm) {  
    if (cm.somethingSelected()) {
        cm.indentSelection('add');
    } else {
        cm.replaceSelection(cm.getOption) ? "\t" : Array(cm.getOption("indentUnit") + 1).join(" "), "end", "+input");
    }
}

DEMO:

效果:

麻凯倩

微信:makaiqian,请备注来源“博客”并介绍自己。

总访问量: 总访客数: 备案号:浙ICP备15036547号-1