The premise

I wrote this because I used CodeMirror in my previous project, and I thought it would be a good online code editor. I’ve also seen some websites that use online code editors, but I don’t know what they use, so I’m going to take that part out of my company’s project and write a separate blog. And submit the extracted code to GitHub (address), in case it may be used again in the future (maybe in the graduation project).

A simple introduction

CodeMirror is an online code editor that supports syntax highlighting. Liverpoolfc.tv: codemirror.net/

At first glance, those online editors may look a little ugly on the official website. Anyway, that’s the way it looks to me at first glance, but after my own fine-tuning, I can also create a beautiful online code editor.

You can download it from the official website.

After downloading, unzip the folder, lib is the core library and core CSS, mode is the syntax definition of each supported language, theme directory is the supported theme style. In general, adding a reference to lib and a reference to mode is sufficient during development.


How to use

The following two are mandatory to use Code Mirror:

< link rel = "stylesheet" href = "codemirror 5.31.0 / lib/codemirror. CSS" / > < script SRC = "codemirror 5.31.0 / lib/codemirror. Js" > < / script >Copy the code

The js file corresponding to the language to be edited in the mode editor is referenced next. Here we use Groovy as an example:

<! - groovy code highlighting -- > < script SRC = "codemirror - 5.31.0 / mode/groovy/groovy. Js" > < / script >Copy the code

If you want Java code to support code highlighting as well, you’ll need to import clike.js that I downloaded from the web (I’ve put it on my GitHub).

<! <script SRC =" codemiror-5.31.0 /clike.js"></script>Copy the code

The referenced files are used to support syntax highlighting for the corresponding language.

The first time I went to Code Mirror’s official website, I found the editors ugly. That may be because the theme is ugly. Here I recommend a good theme.

<! <link rel="stylesheet" href="codemirror-5.31.0/theme/dracula. CSS "/>Copy the code

If you also want your editor to support line folding, do as follows:

<! - support code folding - > < link rel = "stylesheet" href = "codemirror - 5.31.0 / addon/fold/foldgutter CSS" / > < script SRC = "codemirror - 5.31.0 / addon/fold/foldcode js" > < / script > < script SRC = "codemirror - 5.31.0 / addon/fold/foldgutter js" > < / script > < script SRC = "codemirror 5.31.0 / addon/fold/brace - a fold. Js" > < / script > < script SRC = "codemirror 5.31.0 / addon/fold/comment - a fold. Js" > < / script >Copy the code

Is that how you introduce it? Of course not

Creating an editor

In a real-world project, the entire body content would not be directly used as a container for the editor. The most common is to use a textarea. I’m using a textarea here,

<! -- begin code --> <textarea class="form-control" id="code" name="code"></textarea> <! -- end code-->Copy the code

The next step is to create the editor.

Var Editor = codemiror.fromTextarea (document.getelementById ("code"), {});Copy the code

Isn’t it a little monotonous?

Yes, I can also set some properties in it :(take advantage of the files I introduced in the beginning)

Mode: "text/groovy", // Implement groovy code highlight mode: "text/x-java", // implement Java code highlight lineNumbers: true, // display line number theme: "Dracula ", // set theme lineWrapping: true, // code fold foldGutter: true, gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], matchBrackets: true, // brackets matching //readOnly: true, //readOnlyCopy the code

If you need to see more attributes, you can go to the official website to find them, so far I only use these attributes!

Here are a few:

IndentUnit: integer Indentation unit. The value is the number of Spaces. The default value is 2.

SmartIndent: Boolean Auto indent. Sets whether to auto indent based on context (by the same amount as the previous line). The default is true.

TabSize: integer Width of the TAB character. The default value is 4.

IndentWithTabs: Boolean Specifies whether n* TAB width Spaces should be replaced with N TAB characters in indentation. The default value is false.

ElectricChars: Boolean Specifies whether to re-indent input when it may change the current indentation. Default is true (only valid if mode supports indentation).

SpecialChars: Regular expressions for special characters that RegExp needs to be replaced by placeholders. The most commonly used are non-print characters. The default is /[\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/.

SpecialCharPlaceholder: function(char) → Element This is a function that takes as an argument the character specified by specialChars, which generates a DOM node to display the specified character. By default, a red dot (•) is displayed with a prompt box with the preceding special character encoding.

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 Configures shortcut keys. The default is default, which is codemorrir.js internally defined. Others are in the key Map directory.

The extraKeys: Object binds the editor with shortcuts that are different from the previous keyMap configuration.

LineWrapping: Boolean Whether text on long lines is wrap or scroll, default is scroll.

LineNumbers: Boolean whether to display lineNumbers to the left of the editor.

FirstLineNumber: integer Specifies the number from which to start counting the line number. The default value is 1.

LineNumberFormatter: function(line: integer) → string Sets the line number using a function.

Gutters: array used to add extra gutter (before or instead of gutter). Values should be an array of CSS names, each of which defines the width to draw the gutter background (and optionally the background). In order to place the gutter number explicitly (default to the right of all other gutter), you can also include the codemiror-linenumbers class. The class name is the key name passed to setGutterMarker.

FixedGutter: Boolean Sets gutter to follow the editor’s content horizontally (false) or fixed to the left (true or default).

ScrollbarStyle: string Sets the scrollbar. Default is “native”, display the native scroll bar. The core library also provides a “NULL” style, which completely hides the scroll bar. Addons allows you to set more scrollbar modes.

coverGutterNextToScrollbar: Boolean When fixedGutter is enabled and a horizontal scroll bar exists, the gutter will default to the left of the scroll bar. When this is set to true, the gutter will be blocked by elements with the Codemiror-gutter-filler class. InputStyle: string Specifies how CodeMirror handles input and focus. The core library defines textarea and Contenteditable input patterns. The default is contenteditable on mobile browsers and Textarea on desktop browsers. IME and screen reader support is better in Contenteditable mode.

ReadOnly: Boolean | string editor is read-only. If set to the default value “nocursor”, in addition to being read-only, the edit area does not gain focus.

ShowCursorWhenSelecting: Boolean Indicates whether the cursor is displayed when selected. The default is false.

LineWiseCopyCut: Boolean When enabled, if text is not selected when copying or cutting, the entire line where the cursor is located is automatically manipulated.

UndoDepth: INTEGER The maximum number of undoDepth undoDepth: integer The maximum number of undoDepth undoDepth: integer The maximum number of undoDepth undoDepth: integer

HistoryEventDelay: INTEGER Specifies the number of milliseconds before a history event is raised during input or deletion.

Tabindex: The tabindex of the INTEGER editor.

Autofocus: Boolean Whether focus is automatically acquired during initialization. This is off by default. However, it is automatically set to true when textarea is used and no explicit value is specified.

DragDrop: Boolean Whether drag and drop is allowed. Default is true.

AllowDropFileTypes: Array Defaults to NULL. When set, only file types contained in this array are accepted to be dragged into the editor. The file type is MIME name.

CursorBlinkRate: number Indicates the interval (in milliseconds) at which the cursor flashes. The default is 530. When set to 0, the cursor flashing is disabled. Negative numbers hide the cursor.

CursorScrollMargin: number The distance above and below the cursor when the cursor is near the edge of the viewable area. The default is 0.

CursorHeight: number indicates the cursorHeight. The default is 1, which is the full row height. For some fonts, setting 0.85 will look better.

ResetSelectionOnContextMenu: Boolean set outside on click to open the context menu select text, whether to move the cursor to click. The default is true.

WorkTime, workDelay: number uses a dummy background thread to highlight the workTime duration and then uses timeout to rest the workDelay duration. The default values are 200 and 300. (Have no idea what this feature means)

PollInterval: number Specifies the speed at which CodeMirror scrolls (writes data) to the corresponding Textarea (when focus is gained). Most input is captured by events, but some input methods (such as IME) do not generate events on some browsers, so data scrolling is used. The default is 100 milliseconds.

By default, CodeMirror merges two spans that use the same class into one. Disable this feature by setting this item to false.

AddModeClass: Boolean When enabled (disabled by default), additional CM-M CSS style classes are added to each tag that represent the mode in which the tag was generated. For example, the cm-M-XML class is added to tags generated by XML Mode.

MaxHighlightLength: Number When very long lines need to be highlighted, the editor sets other lines to plain text when certain locations are reached in order to maintain response performance. The default is 10000 and can be set to Infinity to disable this feature.

ViewportMargin: INTEGER Specifies the number of lines to render above and below the content currently scrolling into the view. This affects the number of rows to update when scrolling. The default value of 10 should normally be used. You can set the value to Infinity to always render the entire document. Note: This setting affects performance when working with large documents.


What if you want to set the size of your code box?

editor.setSize('800px', '950px'); // Set the length and width of the code boxCopy the code

Also, what if you want to assign a value to a code box?

editor.setValue(""); // Assign editor.getValue() to the code box; // Get the value of the code boxCopy the code

If you want to set a new property somewhere else, you can write it like this:

editor.setOption("readOnly", true); // Something like thisCopy the code

conclusion

How to use the Code Mirror


I feel I can still ha!

All the code involved can be downloaded on GitHub: github.com/zhisheng17/…

Author: Zhisheng Tian


Address:
Build your own online code editor using CodeMirror