codemirror2 在antd的form中会出现无法录入或者录入报错的问题,解决方法请查阅:
codemirrorwrapper - CodeSandbox
1. 安装依赖
yarn add codemirror
yarn add react-codemirror2
2. 引入
// js
import Cm from "./extendCodeMirror.js"; // 代码在文章底部, 用于初始化编辑器的格式化代码的功能
import {UnControlled as CodeMirror} from 'react-codemirror2';
import 'codemirror/addon/fold/foldcode.js'; // 代码折叠
import 'codemirror/addon/fold/foldgutter.js'; // 代码折叠
import 'codemirror/addon/fold/brace-fold.js'; // 代码折叠
import 'codemirror/addon/fold/comment-fold.js'; // 代码折叠
import 'codemirror/addon/hint/javascript-hint.js'; // 自动提示
import 'codemirror/addon/hint/show-hint.js'; // 自动提示
import 'codemirror/addon/lint/lint.js'; // 错误校验
import 'codemirror/addon/lint/javascript-lint.js'; // js错误校验
import 'codemirror/addon/selection/active-line.js'; // 当前行高亮
import 'codemirror/lib/codemirror.js'
import 'codemirror/mode/javascript/javascript.js'
// css
import 'codemirror/addon/fold/foldgutter.css'; // 代码折叠
import 'codemirror/addon/hint/show-hint.css'; // 自动提示
import 'codemirror/addon/lint/lint.css' // 代码错误提示
import 'codemirror/lib/codemirror.css' // 编辑器样式
import 'codemirror/theme/idea.css' // 主题: idea
import 'codemirror/theme/solarized.css'
//声明JSHINT
const jshint = require('../../../libs/codeMirror/jshint'); // jshit.js 在文章底部
window.JSHINT = jshint.JSHINT;
3.使用
<CodeMirror
editorDidMount={this.onEditorDidMount}
value={''}
options={{
extraKeys: { //配置按键
"Alt": "autocomplete", // 按下`alt`时出现代码提示
},
lineNumbers: true, // 显示行号
lineWrapping: false, // 自动换行
styleActiveLine: true, // 选中行高亮
mode: "javascript",
theme: "idea", // 主题配置
matchBrackets: true, // 匹配括号
hintOptions: {hint: this.synonyms}, // 自动提示配置
gutters: ["CodeMirror-lint-markers"],
lint: true, // 代码出错提醒
indentUnit: 4, // 缩进配置(默认为2)
}}
/>
// js
onEditorDidMount = editor => {
this.editor = editor;
editor.setSize("width", 'height'); // 设置编辑器宽高
// 绑定其他快捷键, 这里以按下ctrl-1 格式化编辑器代码做示例
editor.addKeyMap({
'Ctrl-1': this.autoFormatSelection,
})
}
synonyms = (cm, option) => {
let comp = [
"要提示的代码1",
"要提示的代码2",
"..."
]
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 && /[a-zA-Z0-9_.]/.test(line.charAt(start - 1))) --start;
while (end < line.length && /[a-zA-Z0-9_.]/.test(line.charAt(end))) ++end;
var word = line.slice(start, end);
var result_comp = [];
for (let i = 0; i < comp.length; i++) {
if (comp[i].indexOf(word) !== -1) {
result_comp.push(comp[i]);
}
}
if (result_comp.length) {
return accept({
list: result_comp,
from: Cm.Pos(cursor.line, start),
to: Cm.Pos(cursor.line, end)
});
} else {
return accept(null)
}
}, 50)
})
}
autoFormatSelection = () => {
const script_length = this.editor.getValue().length;
const startPos = {line: 0, ch: 0, sticky: null};
const endPos = this.editor.doc.posFromIndex(script_length);
this.editor.setSelection(startPos, endPos);
this.editor.autoFormatRange(startPos, endPos);
this.editor.commentRange(false, startPos, endPos);
};
4.补充代码
// extendCodeMirror.js
/* eslint-disable */
import * as CodeMirror from 'codemirror';
CodeMirror.extendMode("css", {
commentStart: "/*",
commentEnd: "*/",
newlineAfterToken: function(type, content) {
return /^[;{}]$/.test(content);
}
});
CodeMirror.extendMode("javascript", {
commentStart: "/*",
commentEnd: "*/",
// FIXME semicolons inside of for
newlineAfterToken: function(type, content, textAfter, state) {
if (this.jsonMode) {
return /^[\[,{]$/.test(content) || /^}/.test(textAfter);
} else {
if (content == ";" && state.lexical && state.lexical.type == ")") return false;
return /^[;{}]$/.test(content) && !/^;/.test(textAfter);
}
}
});
CodeMirror.extendMode("xml", {
commentStart: "<!--",
commentEnd: "-->",
newlineAfterToken: function(type, content, textAfter) {
return type == "tag" && />$/.test(content) || /^</.test(textAfter);
}
});
// Comment/uncomment the specified range
CodeMirror.defineExtension("commentRange", function (isComment, from, to) {
var cm = this, curMode = CodeMirror.innerMode(cm.getMode(), cm.getTokenAt(from).state).mode;
cm.operation(function() {
if (isComment) { // Comment range
cm.replaceRange(curMode.commentEnd, to);
cm.replaceRange(curMode.commentStart, from);
if (from.line == to.line && from.ch == to.ch) // An empty comment inserted - put cursor inside
cm.setCursor(from.line, from.ch + curMode.commentStart.length);
} else { // Uncomment range
var selText = cm.getRange(from, to);
var startIndex = selText.indexOf(curMode.commentStart);
var endIndex = selText.lastIndexOf(curMode.commentEnd);
if (startIndex > -1 && endIndex > -1 && endIndex > startIndex) {
// Take string till comment start
selText = selText.substr(0, startIndex)
// From comment start till comment end
+ selText.substring(startIndex + curMode.commentStart.length, endIndex)
// From comment end till string end
+ selText.substr(endIndex + curMode.commentEnd.length);
}
cm.replaceRange(selText, from, to);
}
});
});
// Applies automatic mode-aware indentation to the specified range
CodeMirror.defineExtension("autoIndentRange", function (from, to) {
var cmInstance = this;
this.operation(function () {
for (var i = from.line; i <= to.line; i++) {
cmInstance.indentLine(i, "smart");
}
});
});
// Applies automatic formatting to the specified range
CodeMirror.defineExtension("autoFormatRange", function (from, to) {
var cm = this;
var outer = cm.getMode(), text = cm.getRange(from, to).split("\n");
var state = CodeMirror.copyState(outer, cm.getTokenAt(from).state);
var tabSize = cm.getOption("tabSize");
var out = "", lines = 0, atSol = from.ch == 0;
function newline() {
out += "\n";
atSol = true;
++lines;
}
for (var i = 0; i < text.length; ++i) {
var stream = new CodeMirror.StringStream(text[i], tabSize);
while (!stream.eol()) {
var inner = CodeMirror.innerMode(outer, state);
var style = outer.token(stream, state), cur = stream.current();
stream.start = stream.pos;
if (!atSol || /\S/.test(cur)) {
out += cur;
atSol = false;
}
if (!atSol && inner.mode.newlineAfterToken &&
inner.mode.newlineAfterToken(style, cur, stream.string.slice(stream.pos) || text[i+1] || "", inner.state))
newline();
}
if (!stream.pos && outer.blankLine) outer.blankLine(state);
if (!atSol) newline();
}
cm.operation(function () {
cm.replaceRange(out, from, to);
for (var cur = from.line + 1, end = from.line + lines; cur <= end; ++cur)
cm.indentLine(cur, "smart");
cm.setSelection(from, cm.getCursor(false));
});
});
// console.log("初始化CodeMirror完成");
export default CodeMirror;
// jshint.js
//链接: https://pan.baidu.com/s/1mdTArljNyDybKOqKIL2XQQ 提取码: d2b2 复制这段内容后打开百度网盘手机App,操作更方便哦