最近工作中需要优化下之前的网页端代码编辑器。我作为后端开发,虽然做这个不专业,但也只能硬着头皮上啊,大量查阅资料,还是优化了一些内容的,在这里分享一下。如果有写的不对的地方,也请大家体谅下,毕竟纯手打很累的哈哈。
参考手册:
vue-codemirror github 地址:https://github.com/surmon-china/vue-codemirror
codemirror 中文文档:https://olindk.gitbooks.io/codemirror/content/configuration.html
codemirror 英文文档:https://codemirror.net/doc/manual.html#config
如何引入 vue-codemirror 就不详细写了,网上资料很多。在 vue-codemirror gitbub 中也有简单教程,此文章只列举一些我认为挺有用的功能。
options配置
codemirror 中最重要的就是配置,这里先贴出来我用的配置。
cmOptions: {
theme: 'monokai',
mode: '',
readOnly: false,
tabSize: 4, // 制表符
indentUnit: 2, // 缩进位数
lineNumbers: true,
ineWiseCopyCut: true,
viewportMargin: 1000,
autofocus: true,
autocorrect: true,
spellcheck: true,
specialChars: /[--?-??-?????-?]/g,
specialCharPlaceholder: function (ch) {
let token = document.createElement("span");
let content = ".";
token.className = "cm-invalidchar";
if (typeof content == "string") {
token.appendChild(document.createTextNode(content));
}
token.title = "\u" + ch.charCodeAt(0).toString(16);
token.setAttribute("aria-label", token.title);
return token
},
extraKeys: {
Tab: (cm) => {
if (cm.somethingSelected()) { // 存在文本选择
cm.indentSelection('add'); // 正向缩进文本
} else { // 无文本选择
cm.replaceSelection(Array(cm.getOption("indentUnit") + 1).join(" "), "end", "+input"); // 光标处插入 indentUnit 个空格
}
},
},
lint: false,
// 代码折叠
gutters: [
"CodeMirror-lint-markers",
"CodeMirror-linenumbers",
"Co