editor = CodeMirror.fromTextArea(document.getElementById("textarea"), {
extraKeys: { // 配置按鍵
"Ctrl": "autocomplete", // 需要下面的synonyms配置
},
lineNumbers: true, // 顯示行號
lineWrapping: true, // 自動換行
styleActiveLine: true, // 選中行高亮
mode: "text/javascript",
theme: "idea", // 主題配置
matchBrackets: true, // 匹配括號
hintOptions: {hint: synonyms}, // 自動提示配置
gutters: ["CodeMirror-lint-markers"],
lint: true, // 代碼出錯提醒
indentUnit: 4, // 縮進配置(默認為2)
});
// 自動提示需要支持Pormise, 當當前數據的字符串滿足comp中的某一個word時,會提示該word所在數組的詞匯
if (typeof Promise !== "undefined") {
comp = [
["here", "hither"],
["asynchronous", "nonsynchronous"],
["completion", "achievement", "conclusion", "culmination", "expirations"],
["hinting", "advive", "broach", "imply"],
["function","action"],
["provide", "add", "bring", "give"],
["synonyms", "equivalents"],
["words", "token"],
["each", "every"],
];
}
// 提示功能的代碼, 可以適當修改來滿足自己的需求
function synonyms(cm, option) {
return new Promise(function(accept) {
setTimeout(function() {
var cursor = cm.getCursor(), line = cm.getLine(cursor.line)
var start = cursor.ch, end = cursor.ch
while (start && /\w/.test(line.charAt(start - 1))) --start
while (end < line.length && /\w/.test(line.charAt(end))) ++end
var word = line.slice(start, end)
for (var i = 0; i < comp.length; i++) if (comp[i].indexOf(word) != -1)
return accept({list: comp[i],
from: CodeMirror.Pos(cursor.line, start),
to: CodeMirror.Pos(cursor.line, end)})
return accept(null)
}, 10)
})
}
// 額外配置快捷鍵
editor.addKeyMap({
'Ctrl-S': function () {
saveFunction();
},
'Ctrl-s': function () {
saveFunction();
},
'Ctrl-f': autoFormatSelection,
});
// 自動格式化編輯器
function autoFormatSelection() {
CodeMirror.commands["selectAll"](editor);
var range = getSelectedRange();
editor.autoFormatRange(range.from, range.to);
editor.commentRange(false, range.from, range.to);
}
// 獲取編輯器中選中范圍的的行號
function getSelectedRange() {
return {
from: editor.getCursor(true),
to: editor.getCursor(false)
}
}
editor.replaceSelection("內容"); // 替換選中的字符串、在光標處插入字符
editor.setSize('100%', '100%'); //設置代碼框的長寬
CodeMirror.commands["selectAll"](editor); // 執行內置的命令
CodeMirror.commands["goDocEnd"](editor) //移動到文件尾部
editor.refresh(); // 插件不顯示文本內容,直到點擊才出現