在線代碼編輯器CodeMirror簡介


1.什么是Code Mirror

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

2.使用Code Mirror

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

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

 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時加上

lineNumbers:true

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

 

當然,如此簡單的編輯器還能不滿足我們的需求,接下來我們要為這個編輯器加上如下功能:

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

更改主題:

Code Mirror提供了很多種主題,在codemirror-5.12/theme/seti.css可以看到所有主題,我們准備使用seti這個主題,首先需將其引入:

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

而后在構造editor時加入參數

theme:"seti"

完整代碼如下:

 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始終渲染整個文檔。注意:這樣設置在處理大文檔時會影響性能。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM