CodeMirror基本使用及实现关键词高亮、自定义主题

版权声明:本文为博主原创文章,欢迎转载,转载请注明出处。 https://blog.csdn.net/smk108/article/details/79110010

CodeMirror是一款在线的支持语法高亮的代码编辑器,现在已有封装的react版本(react-codemirror)可以直接使用。Codemirror资源文件中,lib下是放的是核心库和核心cssmode下放的是各种支持语言的语法定义,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详细配置项及apihttp://codemirror.net/

theme文件夹下提供了近50theme可供选择,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文件中使用的类存在不同,在实际使用中根据选择的语言进行配置就可以,不将完整的类名列表全部定义样式。
 




 

猜你喜欢

转载自blog.csdn.net/smk108/article/details/79110010
今日推荐