在線代碼編輯器CodeMirror簡介

1.什麼是Code Mirror

最近作一個項目須要在網頁上實現一個代碼編輯器,支持語法高亮、自動縮進、智能提示等功能。發現Code Mirror恰好知足全部需求。Code Mirror是由js寫的一款插件,其功能很是強大,用來實現網頁端代碼編輯器很是方便。若是想看效果圖,可移步到這裏----CodeOnline,這是我作的一個小項目,其中代碼編輯器的就是用Code Mirror實現的。javascript

2.使用Code Mirror

下面我將演示如何使用Code Mirror搭建一個簡易的代碼編輯器,並對其經常使用配置簡要介紹。css

首先要到Code Mirror官網下載此插件,而後在網頁中引入便可。以下代碼即實現了一個能夠高亮顯示Java代碼的編輯器:html

 1 <!--
 2 最簡單的CodeMirror編輯器
 3 -->
 4 
 5 <!DOCTYPE
 6 html>
 7 
 8 <html>
 9 
10 <!--下面兩個是使用Code Mirror必須引入的-->
11 <link rel="stylesheet" href="codemirror-5.12/lib/codemirror.css">
12 <script src="codemirror-5.12/lib/codemirror.js"></script>
13 
14 <!--Java代碼高亮必須引入-->
15 <script src="codemirror-5.12/clike.js"></script>
16 
17 <head>
18 <title>CodeMirrorTest</title>
19 </head>
20 <body>
21 <textarea id="code"></textarea>
22 </body>
23 <script type="text/javascript">
24 //根據DOM元素的id構造出一個編輯器
25     var editor=CodeMirror.fromTextArea(document.getElementById("code"),{
26                 mode:"text/x-java" //實現Java代碼高亮
27         });
28 </script>
29 </html>

如要顯示行號,只需在構造editor時加上java

lineNumbers:true

正則表達式

var editor=CodeMirror.fromTextArea(document.getElementById("code"),{
                mode:"text/x-java", //實現Java代碼高亮
                lineNumbers:true
        });

 

固然,如此簡單的編輯器還能不知足咱們的需求,接下來咱們要爲這個編輯器加上以下功能:json

  • 更改主題
  • 綁定Vim
  • 摺疊代碼
  • 全屏模式
  • 括號匹配
  • 智能提示

更改主題:vim

Code Mirror提供了不少種主題,在codemirror-5.12/theme/seti.css能夠看到全部主題,咱們準備使用seti這個主題,首先需將其引入:數組

<link rel="stylesheet" href="codemirror-5.12/theme/seti.css">

然後在構造editor時加入參數瀏覽器

theme:"seti"

完整代碼以下:app

 1 <!DOCTYPE html>
 2 <html>
 3 <link rel="stylesheet" href="codemirror-5.12/lib/codemirror.css">
 4 <script src="codemirror-5.12/lib/codemirror.js"></script>
 5 <script src="codemirror-5.12/clike.js"></script>
 6 
 7 <!--引入css文件,用以支持主題-->
 8 <link rel="stylesheet" href="codemirror-5.12/theme/seti.css">
 9 <head>
10 <title>CodeMirror Test</title>
11 </head>
12 <body>
13 <textarea id="code"></textarea>
14 </body>
15 <script type="text/javascript">
16     var editor=CodeMirror.fromTextArea(document.getElementById("code"),{
17         mode:"text/x-java",
18         lineNumbers:true,
19         theme:"seti"
20     });
21 </script>
22 </html>

最後各類其餘功能的實現方法與之相似,稍微注意的是須要引入的文件不一樣,我將實現各個功能所需的文件均寫在了以下代碼中:

 1 <!DOCTYPE html>
 2 <html>
 3 <link rel="stylesheet" href="codemirror-5.12/lib/codemirror.css">
 4 <script src="codemirror-5.12/lib/codemirror.js"></script>
 5 <script src="codemirror-5.12/clike.js"></script>
 6 
 7 <!--引入css文件,用以支持主題-->
 8 <link rel="stylesheet" href="codemirror-5.12/theme/eclipse.css">
 9 <link rel="stylesheet" href="codemirror-5.12/theme/seti.css">
10 <link rel="stylesheet" href="codemirror-5.12/theme/dracula.css">
11 
12 <!--引入js,綁定Vim-->
13 <link rel="stylesheet" href="codemirror-5.12/addon/dialog/dialog.css">
14 <script src="codemirror-5.12/keymap/vim.js"></script>
15 <script src="codemirror-5.12/addon/search/searchcursor.js"></script>
16 <!--改善vim輸入命令時的樣式-->
17 <script src="codemirror-5.12/addon/dialog/dialog.js"></script>
18 
19 <!--支持代碼摺疊-->
20 <link rel="stylesheet" href="codemirror-5.12/addon/fold/foldgutter.css"/>
21 <script src="codemirror-5.12/addon/fold/foldcode.js"></script>
22 <script src="codemirror-5.12/addon/fold/foldgutter.js"></script>
23 <script src="codemirror-5.12/addon/fold/brace-fold.js"></script>
24 <script src="codemirror-5.12/addon/fold/comment-fold.js"></script>
25 
26 <!--全屏模式-->
27 <link rel="stylesheet" href="codemirror-5.12/addon/display/fullscreen.css">
28 <script src="codemirror-5.12/addon/display/fullscreen.js"></script>
29 
30 <!--括號匹配-->
31 <script src="codemirror-5.12/addon/edit/matchbrackets.js"></script>
32 
33 <!--自動補全-->
34 <link rel="stylesheet" href="codemirror-5.12/addon/hint/show-hint.css">
35 <script src="codemirror-5.12/addon/hint/show-hint.js"></script>
36 <script src="codemirror-5.12/addon/hint/anyword-hint.js"></script>
37 
38 <head>
39 <title>CodeMirror Test</title>
40 </head>
41 
42 <body>
43 <textarea id="code"></textarea>
44 </body>
45 <script type="text/javascript">
46     var editor=CodeMirror.fromTextArea(document.getElementById("code"),{
47          //Java高亮顯示
48          mode:"text/x-java",
49 
50          //顯示行號
51          lineNumbers:true,
52 
53          //設置主題
54          theme:"seti",
55 
56          //綁定Vim
57          keyMap:"vim",
58 
59          //代碼摺疊
60          lineWrapping:true,
61          foldGutter: true,
62          gutters:["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
63 
64          //全屏模式
65          fullScreen:true,
66 
67           //括號匹配
68           matchBrackets:true,
69 
70           智能提示 
71           extraKeys:{"Ctrl-Space":"autocomplete"}//ctrl-space喚起智能提示
72 });
73 </script>
74 </html>

其餘說明:

  1. 在構造editor時相關的屬性大多數均可以動態的指定。如設置顯示行號能夠不在構造editor時指出,只需構造出editor以後,調用
    editor.setOption("lineNumbers",true)
    便可,更改主題也相似的用
    editor.setOption("theme","seti")
    便可,很是方便。
  2. 能夠用
    editor.getOption("屬性名")
    來獲取editor某屬性的值,在本例中
    editor.getOption("theme")
    將返回"seti"
  3. 沒法用js的DOM操做獲取編輯器中的值,但能夠用
    editor.getValeu()
    得到其中的值,
    editor.setValue("value")
    來設置其中的值
  4. 能夠自定義編輯器的大小,只需設置以下樣式便可:
    <style type="text/css">
         .CodeMirror{border:1px solid black;font-   size:15px;width:100px;height:100px}
    </style>
  5. 在extra中可綁定函數到按鍵上,例如:
    var editor=CodeMirror.fromTextArea(document.getElementById("code"),{
        mode:"text/x-java",
        extraKeys:{
            "Ctrl-Space":"autocomplete",
            "Ctrl-F7":function () {
                        alert("綁定了Ctrl-F7");
                      },
            "Shift-Alt-Enter": function (cm) {
                       cm.setOption("fullScreen", !cm.getOption("fullScreen"));
                      }
        }
    });

須要注意的是,若是將esc鍵綁定了某函數,那麼Vim可能沒法正常工做。

3.結語

Code Mirror很是強大,上面的例子說明了其基本的使用方法,足夠應付大多數使用場景,固然還有不少功能未能一一說明,個人大部分文章首發在知乎專欄:關於計算機的一些事,歡迎你們關注。如要深刻學習,請閱讀其官方文檔。最後放一篇文章,該文章羅列了更多的配置項,傳送門:codeMirror配置。爲了方便閱讀,摘抄以下:

options 可使用的參數

CodeMirror函數和它的fromTextArea方法均可以使用一個配置對象做爲第二個參數。

value: string | CodeMirror.Doc

編輯器的初始值(文本),能夠是字符串或者CodeMirror文檔對象(不一樣於HTML文檔對象)。

mode: string | object


通用的或者在CodeMirror中使用的與mode相關聯的mime,當不設置這個值的時候,會默認使用第一個載入的mode定義文件。通常地,會使用關聯的mime類型來設置這個值;除此以外,也可使用一個帶有name屬性的對象來做爲值(如:{name: 「javascript」, json: true})。能夠經過訪問CodeMir

ror.modes和CodeMirror.mimeModes獲取定義的mode和MIME。


lineSeparator: string|null

明確指定編輯器使用的行分割符(換行符)。默認(值爲null)狀況下,文檔會被 CRLF(以及單獨的CR, LF)分割,單獨的LF會在全部的輸出中用做換行符(如:getValue)。當指定了換行字符串,行就只會被指定的串分割。

theme: string

配置編輯器的主題樣式。要使用主題,必須保證名稱爲 .cm-s-[name] (name是設置的theme的值)的樣式是加載上了的。固然,你也能夠一次加載多個主題樣式,使用方法和html和使用類同樣,如: theme: foo bar,那麼此時須要cm-s-foo cm-s-bar這兩個樣式都已經被加載上了。

indentUnit: integer

縮進單位,值爲空格數,默認爲2 。

smartIndent: boolean

自動縮進,設置是否根據上下文自動縮進(和上一行相同的縮進量)。默認爲true。

tabSize: integer

tab字符的寬度,默認爲4 。

indentWithTabs: boolean

在縮進時,是否須要把 n*tab寬度個空格替換成n個tab字符,默認爲false 。

electricChars: boolean

在輸入可能改變當前的縮進時,是否從新縮進,默認爲true (僅在mode支持縮進時有效)。

specialChars: RegExp

須要被佔位符(placeholder)替換的特殊字符的正則表達式。最經常使用的是非打印字符。默認爲:/[\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/。

specialCharPlaceholder: function(char) → Element

這是一個接收由specialChars選項指定的字符做爲參數的函數,此函數會產生一個用來顯示指定字符的DOM節點。默認狀況下,顯示一個紅點(•),這個紅點有一個帶有前面特殊字符編碼的提示框。

rtlMoveVisually: boolean

Determines whether horizontal cursor movement through right-to-left (Arabic, Hebrew) text is visual (pressing the left arrow moves the cursor left) or logical (pressing the left arrow moves to the next lower index in the string, which is visually right in right-to-left text). The default is false on Windows, and true on other platforms.(這段徹底不曉得搞啥子鬼)

keyMap: string

配置快捷鍵。默認值爲default,即 codemorrir.js 內部定義。其它在key map目錄下。

extraKeys: object

給編輯器綁定與前面keyMap配置不一樣的快捷鍵。

lineWrapping: boolean

在長行時文字是換行(wrap)仍是滾動(scroll),默認爲滾動(scroll)。

lineNumbers: boolean

是否在編輯器左側顯示行號。

firstLineNumber: integer

行號從哪一個數開始計數,默認爲1 。

lineNumberFormatter: function(line: integer) → string

使用一個函數設置行號。

gutters: array<string>

用來添加額外的gutter(在行號gutter前或代替行號gutter)。值應該是CSS名稱數組,每一項定義了用於繪製gutter背景的寬度(還有可選的背景)。爲了能明確設置行號gutter的位置(默認在全部其它gutter的右邊),也能夠包含CodeMirror-linenumbers類。類名是用於傳給setGutterMarker的鍵名(keys)。

fixedGutter: boolean

設置gutter跟隨編輯器內容水平滾動(false)仍是固定在左側(true或默認)。

scrollbarStyle: string

設置滾動條。默認爲」native」,顯示原生的滾動條。核心庫還提供了」null」樣式,此樣式會徹底隱藏滾動條。Addons能夠設置更多的滾動條模式。

coverGutterNextToScrollbar: boolean

當fixedGutter啓用,而且存在水平滾動條時,在滾動條最左側默認會顯示gutter,當此項設置爲true時,gutter會被帶有CodeMirror-gutter-filler類的元素遮擋。

inputStyle: string

選擇CodeMirror處理輸入和焦點的方式。核心庫定義了textarea和contenteditable輸入模式。在移動瀏覽器上,默認是contenteditable,在桌面瀏覽器上,默認是textarea。在contenteditable模式下對IME和屏幕閱讀器支持更好。

readOnly: boolean|string

編輯器是否只讀。若是設置爲預設的值 「nocursor」,那麼除了設置只讀外,編輯區域還不能得到焦點。

showCursorWhenSelecting: boolean

在選擇時是否顯示光標,默認爲false。

lineWiseCopyCut: boolean

啓用時,若是在複製或剪切時沒有選擇文本,那麼就會自動操做光標所在的整行。

undoDepth: integer

最大撤消次數,默認爲200(包括選中內容改變事件) 。

historyEventDelay: integer

在輸入或刪除時引起歷史事件前的毫秒數。

tabindex: integer

編輯器的tabindex。

autofocus: boolean

是否在初始化時自動獲取焦點。默認狀況是關閉的。可是,在使用textarea而且沒有明確指定值的時候會被自動設置爲true。

低級選項

下面的選項僅用於一些特殊狀況。

dragDrop: boolean

是否容許拖放,默認爲true。

allowDropFileTypes: array<string>

默認爲null。當設置此項時,只接收包含在此數組內的文件類型拖入編輯器。文件類型爲MIME名稱。

cursorBlinkRate: number

光標閃動的間隔,單位爲毫秒。默認爲530。當設置爲0時,會禁用光標閃動。負數會隱藏光標。

cursorScrollMargin: number

當光標靠近可視區域邊界時,光標距離上方和下方的距離。默認爲0 。

cursorHeight: number

光標高度。默認爲1,也就是撐滿行高。對一些字體,設置0.85看起來會更好。

resetSelectionOnContextMenu: boolean

設置在選擇文本外點擊打開上下文菜單時,是否將光標移動到點擊處。默認爲true。

workTime, workDelay: number

經過一個假的後臺線程高亮 workTime 時長,而後使用 timeout 休息 workDelay 時長。默認爲200和300 。(徹底不懂這個功能是在說啥)

pollInterval: number

指明CodeMirror向對應的textarea滾動(寫數據)的速度(得到焦點時)。大多數的輸入都是經過事件捕獲,可是有的輸入法(如IME)在某些瀏覽器上並不會生成事件,因此使用數據滾動。默認爲100毫秒。

flattenSpans: boolean

默認狀況下,CodeMirror會將使用相同class的兩個span合併成一個。經過設置此項爲false禁用此功能。

addModeClass: boolean

當啓用時(默認禁用),會給每一個標記添加額外的表示生成標記的mode的以cm-m開頭的CSS樣式類。例如,XML mode產生的標記,會添加cm-m-xml類。

maxHighlightLength: number

當須要高亮很長的行時,爲了保持響應性能,當到達某些位置時,編輯器會直接將其餘行設置爲純文本(plain text)。默認爲10000,能夠設置爲Infinity來關閉此功能。

viewportMargin: integer

指定當前滾動到視圖中內容上方和下方要渲染的行數。這會影響到滾動時要更新的行數。一般狀況下應該使用默認值10。能夠設置值爲Infinity始終渲染整個文檔。注意:這樣設置在處理大文檔時會影響性能。

相關文章
相關標籤/搜索