CodeMirror是一款在線的支持語法高亮的代碼編輯器,現在已有封裝的react版本(react-codemirror)可以直接使用。Codemirror資源文件中,lib下是放的是核心庫和核心css,mode下放的是各種支持語言的語法定義,theme目錄下是支持的主題樣式。
使用codemirror實現在線代碼編輯器主要包括的功能是:
1、實現自動提示
2、 關鍵詞高亮與自定義theme
下面是codemirror的使用介紹(以react-codemirror的使用爲例):
導入核心庫和核心css:
import CodeMirror from 'react-codemirror';
import 'codemirror/lib/codemirror.css';
導入使用的語言語法定義文件:
import 'codemirror/mode/sql/sql';
導入自動提示核心文件及樣式:
import 'codemirror/addon/hint/show-hint.css';
import 'codemirror/addon/hint/show-hint.js';
導入指定語言的提示文件:
import 'codemirror/addon/hint/sql-hint.js';
導入選中的theme文件:
import 'codemirror/theme/blackboard.css';
定義基本options:
const options={
lineNumbers: true, //顯示行號
mode: {name: "text/x-mysql"}, //定義mode
extraKeys: {"Ctrl": "autocomplete"}, //自動提示配置
theme: "blackboard" //選中的theme
};
render:
return (
<div>
<CodeMirror ref="editor" value={this.state.sqlValue} onChange={code => this.setState({sqlText: sqlValue})} options={options} />
</div>
);
當需要獲取CodeMirror對象並進行一些操作時:
const editor = this.refs.editor.getCodeMirror();
console.log(editor.getSelection()); //獲取選中內容
editor.setValue(sql); //設置新的value值
以上就基於react-codemirror實現了自動提示和關鍵詞高亮的功能。Options詳細配置項及api見http://codemirror.net/。
theme文件夾下提供了近50個theme可供選擇,FarhadG實現了很多額外的theme,見https://github.com/FarhadG/code-mirror-themes,各theme的實現效果見http://farhadg.github.io/code-mirror-themes/。
我們還可以根據自己的需求自定義theme,介紹兩種方法:
1、 FarhadG提供了工具codeMirror-aceEditor-theme-generator,我們可以在http://tmtheme-editor.herokuapp.com進行theme的設計,並下載爲xml文件,使用codeMirror-aceEditor-theme-generator將其轉換爲自定義的theme文件;
theme其實就是樣式文件,實現高亮的原理是根據不同語言的語法定義設置不同的類名,theme就是定義各種類的樣式,可以自己實現theme樣式文件,import至項目中,就可以在options中使用對應theme。舉例如下(sqlThem.css):
/*選中區域*/
.cm-s-sqlTheme .CodeMirror-activeline-background { background: #D7D4F0; }
.cm-s-sqlTheme .CodeMirror-selected {background: #D7D4F0;}
.cm-s-sqlTheme .CodeMirror-linenumber { color: #AEAEAE; } /*行號數字*/
.cm-s-sqlTheme .cm-quote {color: #090;} /*引號*/
.cm-s-sqlTheme .cm-keyword {color: #3300CC;} /*關鍵字,例如:SELECT*/
.cm-s-sqlTheme .cm-number {color: #333333;} /*數字*/
.cm-s-sqlTheme .cm-variable-2 {color: #333333;} /*變量2,例如:a.id中的.id*/
.cm-s-sqlTheme .cm-comment {color: #009933;} /*註釋*/
.cm-s-sqlTheme .cm-string {color: #009933;} /*字符串*/
.cm-s-sqlTheme .cm-string-2 {color: #009933;} /*字符串*/
需要注意的是:
1、codemirror.css文件中定義了組件的樣式(比如行號,背景、前景顏色,光標等樣式),若需更改可在自定義的樣式文件中覆蓋; codemirror.css文件還實現了default的theme(見cm-s-default),供參考。
2、cm-s-themeName中的themeName必須與css文件名和theme名一致。
3、選擇不同的語言(如Java、js、sql)對應的theme文件中使用的類存在不同,在實際使用中根據選擇的語言進行配置就可以,不將完整的類名列表全部定義樣式。