User manual and reference guide用户手册和参考教程 version 5.42.3

CodeMirror is a code-editor component that can be embedded in Web pages. CodeMirror是一套可以嵌入到网页中的代码编辑器组件。The core library provides only the editor component, no accompanying buttons, auto-completion, or other IDE functionality. 它的核心库只提供了编辑器组件,没有附带按钮、自动补全,或者其它IDE功能。It does provide a rich API on top of which such functionality can be straightforwardly implemented. 它确实提供了一套丰富的API,可以直接在核心库的基础上实现那些功能。See the addons included in the distribution, and the list of externally hosted addons, for reusable implementations of extra features.请参阅包含在分发包中的附件,以及外部托管附件的列表,以了解额外功能的可重用的实现器。

CodeMirror works with language-specific modes. CodeMirror要与专用语言模式配合使用。Modes are JavaScript programs that help color (and optionally indent) text written in a given language. 模式是给定语言中用于帮助编写着色的JavaScript程序(可能还有帮助正确缩进)。The distribution comes with a number of modes (see the mode/ directory), and it isn't hard to write new ones for other languages.分发包自带了一些模式(请参阅mode/目录),为其它语言编写一种新模式也不难。

Basic Usage基本用法

The easiest way to use CodeMirror is to simply load the script and style sheet found under lib/ in the distribution, plus a mode script from one of the mode/ directories. 使用CodeMirror最简单的方法是直接载入分发包中lib/下面的脚本和样式,加上来自mode/目录的一种模式脚本。For example:例如:

<script src="lib/codemirror.js"></script>
<link rel="stylesheet" href="lib/codemirror.css">
<script src="mode/javascript/javascript.js"></script>

(Alternatively, use a module loader. (作为替代,请使用模块化载入器。More about that later.模块化载入器详情)

Having done this, an editor instance can be created like this:搞定了这些之后,就创建了如下的编辑器实例:

var myCodeMirror = CodeMirror(document.body);

The editor will be appended to the document body, will start empty, and will use the mode that we loaded. 编辑器将附加到文档主体中,开始是空白,然后使用我们载入的模式。To have more control over the new editor, a configuration object can be passed to CodeMirror as a second argument:若要对新的编辑器做更多的控制,可以向CodeMirror传入一个配置对象,作为第二个参数。

var myCodeMirror = CodeMirror(document.body, {
value: "function myScript(){return 100;}\n", mode:  "javascript"
});

This will initialize the editor with a piece of code already in it, and explicitly tell it to use the JavaScript mode (which is useful when multiple modes are loaded). 这将利用一小段内部已有的代码,来初始化编辑器,并明确告诉它使用JavaScript模式(当载入多种模式时,它很有用)。See below for a full discussion of the configuration options that CodeMirror accepts.请看下面以获得对CodeMirror接受的配置选项的完整讨论。

In cases where you don't want to append the editor to an element, and need more control over the way it is inserted, the first argument to the CodeMirror function can also be a function that, when given a DOM element, inserts it into the document somewhere. 如果你不想把编辑器附加到某个元素,而且需要对插入编辑器的方式有更多的控制,也可以把CodeMirror函数的第一个参数写成一个函数,只要给这个函数一个DOM元素作为参数,就把编辑器插入到文档的某个位置。This could be used to, for example, replace a textarea with a real editor:例如,它可以是:用一个真正的编辑器代替一个textarea文本域:

var myCodeMirror = CodeMirror(function(elt) {
  myTextArea.parentNode.replaceChild(elt, myTextArea);
}, {value: myTextArea.value});

However, for this use case, which is a common way to use CodeMirror, the library provides a much more powerful shortcut:然而,对于这种常见的CodeMirror用法,库还提供了一个更强大的简写方式:

var myCodeMirror = CodeMirror.fromTextArea(myTextArea);

This will, among other things, ensure that the textarea's value is updated with the editor's contents when the form (if it is part of a form) is submitted. 和其它做法相比,这将确保当表单提交时(如果它是表单的一部分),则textarea文本域的值会随着编辑器的内容一起更新。See the API reference for a full description of this method.请参阅API参考以得到此方法的完整描述。

Module loaders模块载入器

The files in the CodeMirror distribution contain shims for loading them (and their dependencies) in AMD or CommonJS environments. CodeMirror分发包中的文件包含了在AMD或CommonJS环环境中所用的用于载入它们(和它们的依赖性)垫片。If the variables exports and module exist and have type object, CommonJS-style require will be used. 如果变量exportsmodule已存在,并具有类型对象,则将使用CommonJS风格的require。If not, but there is a function define with an amd property present, AMD-style (RequireJS) will be used.如果不是,但是存在函数define,以及某个属性amd属性,则将使用AMD风格(RequireJS)。

It is possible to use Browserify or similar tools to statically build modules using CodeMirror. 可以使用Browserify或类似的工具来利用CodeMirror静态建立模块。Alternatively, use RequireJS to dynamically load dependencies at runtime. 或者,使用RequireJS在运行时动态载入依赖性。Both of these approaches have the advantage that they don't use the global namespace and can, thus, do things like load multiple versions of CodeMirror alongside each other.这两种实现方法都具有优点,即它不使用全局命名空间,因此,像载入多个CodeMirror版可以并行不悖。

ere's a simple example of using RequireJS to load CodeMirror:此处有利用RequireJS载入CodeMirror的简单示例:

require([
"cm/lib/codemirror", "cm/mode/htmlmixed/htmlmixed"
], function(CodeMirror) {
CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true, mode: "htmlmixed"
});
});

It will automatically load the modes that the mixed HTML mode depends on (XML, JavaScript, and CSS). 它将自动载入依赖于XML、JavaScript和CSS的混合HTML模式。Do not use RequireJS' paths option to configure the path to CodeMirror, since it will break loading submodules through relative paths. 请不要使用RequireJS的paths配置项来配置CodeMirror的路径,因为它将通过相对路径破坏载入子模块。Use the packages configuration option instead, as in:请改用packages配置选项,如下:

require.config({
packages: [{
name: "codemirror",
location: "../path/to/codemirror",
main: "lib/codemirror"
}]
});

Configuration配置

Both the CodeMirror function and its fromTextArea method take as second (optional) argument an object containing configuration options. CodeMirror函数和它的fromTextArea方法都用一个包含配置选项的对象作为它的第二个(可选)参数。Any option not supplied like this will be taken from CodeMirror.defaults, an object containing the default options. 任何不提供的配置项,将取用来自CodeMirror.defaults的值,CodeMirror.defaults是一个包含默认配置项的对象。You can update this object to change the defaults on your page.你可以更新此对象以改变网页上的默认值。

Options are not checked in any way, so setting bogus option values is bound to lead to odd errors.不会用任何方式去检查配置项,所以设置虚假的配置项值必然会导致奇怪的错误。

These are the supported options:有一些受支持的配置项:

value: string|CodeMirror.Doc
The starting value of the editor. 编辑器的起始值。Can be a string, or a document object.可以是一个字符串,或者是一个文档对象
mode: string|object
The mode to use. 所使用的模式。When not given, this will default to the first mode that was loaded. 如果不指定它,它将默认为被载入的第一种模式。It may be a string, which either simply names the mode or is a MIME type associated with the mode. 它可能是一个简单命名了模式的字符串,也可能是一个与模式相关联的MIME类型。Alternatively, it may be an object containing configuration options for the mode, with a name property that names the mode (for example {name: "javascript", json: true}). 它也有可能是一个对象,包含了针对模式的配置选项,带有一个命名了模式的name属性(例如{name: "javascript", json: true})。The demo pages for each mode contain information about what configuration parameters the mode supports. 针对每种模式的演示文档包含了关于模式支持哪些配置参数的信息。You can ask CodeMirror which modes and MIME types have been defined by inspecting the CodeMirror.modes and CodeMirror.mimeModes objects. 你可以通过检查CodeMirror.modes对象和CodeMirror.mimeModes对象,来了解CodeMirror,哪种模式和MIME类型已经定义了The first maps mode names to their constructors, and the second maps MIME types to mode specs.第一个对象把模式名称映射到它们的构造器,第二个对象把MIME类型映射到模式规范文档。
lineSeparator: string|null
Explicitly set the line separator for the editor. 显式设置编辑器的行分隔符。By default (value null), the document will be split on CRLFs as well as lone CRs and LFs, and a single LF will be used as line separator in all output (such as getValue). 默认情况下,文档在在CRLF以及孤CR和孤LF处分行,单个LF将用作所有输出中的行分隔符(譬如getValue)。When a specific string is given, lines will only be split on that string, and output will, by default, use that same separator.如果给定了一个特定的字符串,行将在字符串上被切分,默认情况下,输出将使用相同的分隔符。
theme: string
The theme to style the editor with. 样式化编辑器的主题。You must make sure the CSS file defining the corresponding .cm-s-[name] styles is loaded (see the theme directory in the distribution). 你必须确保载入定义了对应的.cm-s-[name]样式的CSS文件(请参阅分发包中的theme目录)。The default is "default", for which colors are included in codemirror.css. 默认值是"default",其颜色包含在codemirror.css中。It is possible to use multiple theming classes at once—for example "foo bar" will assign both the cm-s-foo and the cm-s-bar classes to the editor.可以同时使用多个主题类——例如,"foo bar"将给编辑器分配cm-s-foo类和cm-s-bar类。
indentUnit: integer
How many spaces a block (whatever that means in the edited language) should be indented. 一个块应该缩进多少个空格(无论这在被编辑语言中意味着什么)The default is 2.默认值是2。
smartIndent: boolean
Whether to use the context-sensitive indentation that the mode provides (or just indent the same as the line before). 是否使用由模式提供的上下文敏感缩进(或者只是与行前相同的缩进)。Defaults to true.默认值是true。
tabSize: integer
The width of a tab character. 制表符的宽度。Defaults to 4.默认值是4。
indentWithTabs: boolean
Whether, when indenting, the first N*tabSize spaces should be replaced by N tabs. 在缩进时,前N个tabSize空白是否必须替换成N个制表符。Default is false.默认值是false。
electricChars: boolean
Configures whether the editor should re-indent the current line when a character is typed that might change its proper indentation (only works if the mode supports indentation). 配置当字符键入时,可以改变它的适当缩进,编辑器是否需要重新缩进当前行(只在支持缩进的模式中起作用)。Default is true.默认值为true。
specialChars: RegExp
A regular expression used to determine which characters should be replaced by a special placeholder. 一个正则表达式,用来确定哪些字符应该用特定的占位符来替换。Mostly useful for non-printing special characters. 对于非打印的特殊字符非常有用。The default is /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/.默认值是/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/
specialCharPlaceholder: function(char) → Element
A function that, given a special character identified by the specialChars option, produces a DOM node that is used to represent the character. 一个函数,给它一个由specialChars配置项标识的特殊字符,产生一个DOM节点,用来代表字符。By default, a red dot () is shown, with a title tooltip to indicate the character code.默认情况下,显示了一个红点(),还有一个title提示,指示字符代码。
direction: "ltr" | "rtl"
Flips overall layout and selects base paragraph direction to be left-to-right or right-to-left. 翻转整个布局,并选择基本段落方向为从左往右或从右往左。Default is "ltr". 默认值是“lrt”。CodeMirror applies the Unicode Bidirectional Algorithm to each line, but does not autodetect base direction — it's set to the editor direction for all lines. CodeMirror对每一行应用Unicode双向算法,但是并不自动侦测基本方向——所有行都被设置为编辑器方向。The resulting order is sometimes wrong when base direction doesn't match user intent (for example, leading and trailing punctuation jumps to the wrong side of the line). 输出结果是有时候当基本方向不匹配用户缩进时,会发生错误(例如前导和尾随的标点符号跳到行的错误侧)。Therefore, it's helpful for multilingual input to let users toggle this option. 因此,让用户切换此配置项有助于多语言输入。
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.在Windows中,默认值是false,在其它平台中,默认值是true
keyMap: string
Configures the key map to use. 配置要使用的键映射。The default is "default", which is the only key map defined in codemirror.js itself. 默认值是"default",它是定义在codemirror.js本身中唯一的键映射。Extra key maps are found in the key map directory. key map目录中能够找到其它键映射。See the section on key maps for more information.请参阅关于键映射的章节以获得更多信息。
extraKeys: object
Can be used to specify extra key bindings for the editor, alongside the ones defined by keyMap. 可以用来指定针对编辑器的额外的键绑定,与keyMap中定义的那一套并行不悖。Should be either null, or a valid key map value.它要么是null,要么是一个有效的键映射值。
configureMouse: fn(cm: CodeMirror, repeat: "single" | "double" | "triple", event: Event) → Object
Allows you to configure the behavior of mouse selection and dragging. 允许你配置鼠标选区和拖曳的行为。The function is called when the left mouse button is pressed. 当鼠标左键按下时,调用此函数。The returned object may have the following properties:返回的对象将有下面的属性:
unit: "char" | "word" | "line" | "rectangle" | fn(CodeMirror, Pos) → {from: Pos, to: Pos}
The unit by which to select. 要选择的单位。May be one of the built-in units or a function that takes a position and returns a range around that, for a custom unit. 它既可以是内建单位之一,也可以是一个函数,取用一个位置作为参数,返回一个周围的范围,得到一个自定义单位。The default is to return "word" for double clicks, "line" for triple clicks, "rectangle" for alt-clicks (or, on Chrome OS, meta-shift-clicks), and "single" otherwise.默认值是,对于双击,返回"word",对于三击,返回"line",对于按住alt键单击(或者,在Chrome OS中,是按住meta键和Shift键单击),返回"rectangle",否则,返回"single"
extend: bool
Whether to extend the existing selection range or start a new one. 是扩展已有的选区范围,还是开始一个新选区。By default, this is enabled when shift clicking.默认情况下,当按住Shift键单击时,启用这。
addNew: bool
When enabled, this adds a new range to the existing selection, rather than replacing it. 当启用时,这给已有的选区增加了一个新的范围,而不是代替它。The default behavior is to enable this for command-click on Mac OS, and control-click on other platforms.默认行为是在Mac OS上针对Command-单击启用者,在其它平台上,针对Ctrl-单击启用这。
moveOnDrag: bool
When the mouse even drags content around inside the editor, this controls whether it is copied (false) or moved (true). 当鼠标拖过编辑器里面的内容时,它控制了是复制(false)还是移动(true)。By default, this is enabled by alt-clicking on Mac OS, and ctrl-clicking elsewhere.默认情况下,在MacOS中,通过Alt-单击启用它,在其它平台上,通过Ctrl-单击启用它。
lineWrapping: boolean
Whether CodeMirror should scroll or wrap for long lines. 对于长行,CodeMirror应该滚动它,还是折行它。Defaults to false (scroll).默认值为false(滚动)。
lineNumbers: boolean
Whether to show line numbers to the left of the editor.是否在编辑器的左侧显示行数。
firstLineNumber: integer
At which number to start counting lines. 计行数从哪个数字开始。Default is 1.默认值是1
lineNumberFormatter: function(line: integer) → string
A function used to format line numbers. 用来格式化行数的数字。The function is passed the line number, and should return a string that will be shown in the gutter.此函数用行数字作为参数,然后返回一个字符串,它将显示在沟槽中。
gutters: array<string>
Can be used to add extra gutters (beyond or instead of the line number gutter). 可以用来添加额外的沟槽(另加沟槽或代替行数沟槽)。Should be an array of CSS class names, each of which defines a width (and optionally a background), and which will be used to draw the background of the gutters. 应该是一个CSS类名称的数组,每个项定义了一个width(视情况加一个背景色),它将用来绘制沟槽的背景。May include the CodeMirror-linenumbers class, in order to explicitly set the position of the line number gutter (it will default to be to the right of all other gutters). 可能包含CodeMirror-linenumbers类,为了显式设置行数字沟槽的位置(它将默认在所有其它沟槽的右边)。These class names are the keys passed to setGutterMarker.这些类名是传给setGutterMarker的键。
fixedGutter: boolean
Determines whether the gutter scrolls along with the content horizontally (false) or whether it stays fixed during horizontal scrolling (true, the default).确定沟槽是随着内容水平滚动(false)还是在水平滚动过程中保持不动(true,默认值)。
scrollbarStyle: string
Chooses a scrollbar implementation. 选择一个滚动条实现器。The default is "native", showing native scrollbars. 默认值为"native",显示原生滚动条。The core library also provides the "null" style, which completely hides the scrollbars. 核心库还提供了一个"null"样式,它完全隐藏了滚动条。Addons can implement additional scrollbar models.附件可以实现一个附加的滚动条模型。
coverGutterNextToScrollbar: boolean
When fixedGutter is on, and there is a horizontal scrollbar, by default the gutter will be visible to the left of this scrollbar. 当打开fixedGutter时,而且存在一个水平滚动条,默认情况下,沟槽将可见于滚动条的左侧。If this option is set to true, it will be covered by an element with class CodeMirror-gutter-filler.如果此配置项设置为true,沟槽将被一个带有CodeMirror-gutter-filler类的元素所覆盖。
inputStyle: string
Selects the way CodeMirror handles input and focus. 选择CodeMirror处理输入和焦点的方法。The core library defines the "textarea" and "contenteditable" input models. 核心库定义了"textarea""contenteditable"两种输入模式。On mobile browsers, the default is "contenteditable". 在手机浏览器中,默认值是"contenteditable"On desktop browsers, the default is "textarea". 在桌面浏览器中,默认值是"textarea"Support for IME and screen readers is better in the "contenteditable" model. "contenteditable"模式中,对IME和屏幕阅读器的支持比较好。The intention is to make it the default on modern desktop browsers in the future.考虑使它在未来的现代桌面浏览器上成为默认值。
readOnly: boolean|string
This disables editing of the editor content by the user. 它禁用了由用户编辑编辑器的内容。If the special value "nocursor" is given (instead of simply true), focusing of the editor is also disallowed.如果给定了特殊值"nocursor"(而不只是true)则编辑器的焦点也被禁用掉了。
showCursorWhenSelecting: boolean
Whether the cursor should be drawn when a selection is active. 当激活选区时,是否应该绘制光标。Defaults to false.默认值是false
lineWiseCopyCut: boolean
When enabled, which is the default, doing copy or cut when there is no selection will copy or cut the whole lines that have cursors on them.默认是启用它,当启用它时,在做复制或剪切时,如果没有选区,则将复制或剪切光标所在的位置的整一行。
pasteLinesPerSelection: boolean
When pasting something from an external source (not from the editor itself), if the number of lines matches the number of selection, CodeMirror will by default insert one line per selection. 当从外部源粘贴一些东西时(不是来自编辑器本身),如果行数匹配选区的数目,则CodeMirror将在每个选区插入一行。You can set this to false to disable that behavior.你可以把它设置为false来禁用此行为。
selectionsMayTouch: boolean
Determines whether multiple selections are joined as soon as they touch (the default) or only when they overlap (true).确定当多行选区相触时,是否立即合并到一起(默认值)或者只有当它们重叠时才合并到一起(true)。
undoDepth: integer
The maximum number of undo levels that the editor stores. 编辑器所存储的最多撤销次数。Note that this includes selection change events. 请注意,这包括选区改变事件。Defaults to 200.默认值为200。
historyEventDelay: integer
The period of inactivity (in milliseconds) that will cause a new history event to be started when typing or deleting. 在键入或删除时,不活动多长时间(以毫秒计)将导致开始一个新的历史事件。Defaults to 1250.默认值是1250
tabindex: integer
The tab index to assign to the editor. 赋给编辑器的tab索引If not given, no tab index will be assigned.如果没有指定它,就不会给它赋tab索引值。
autofocus: boolean
Can be used to make CodeMirror focus itself on initialization. 可以用来使CodeMirror在初始化时自动得到焦点。Defaults to off. 默认值为关闭。When fromTextArea is used, and no explicit value is given for this option, it will be set to true when either the source textarea is focused, or it has an autofocus attribute and no other element is focused.如果用了fromTextArea,而且此配置项没有指定明确的值,当源textarea文本域得到焦点时,或者源textarea文本域具有autofocus特性,而且没有其它元素得到焦点时,此配置项将自动设置为true
phrases: ?object
Some addons run user-visible strings (such as labels in the interface) through the phrase method to allow for translation. 有些附件运行用户可见的字符串(譬如接口中的标签),通过phrase方法来允许翻译。This option determines the return value of that method. 此配置项确定了那个方法的返回值。When it is null or an object that doesn't have a property named by the input string, that string is returned. 当它是null或者是不具有由输入字符串命名的属性的对象时,就返回字符串。Otherwise, the value of the property corresponding to that string is returned.否则,就返回对应于字符串的属性的值。

Below this a few more specialized, low-level options are listed. 下面列出了一些更特殊的、底层的配置项。These are only useful in very specific situations, you might want to skip them the first time you read this manual.这些只在特殊场景中有用,在你第一次阅读本手册时,你可能想要跳过它们。

dragDrop: boolean
Controls whether drag-and-drop is enabled. 控制是否启用拖放。On by default.默认启用。
allowDropFileTypes: array<string>
When set (default is null) only files whose type is in the array can be dropped into the editor. 如果设置了它(默认是null),只有数组中的文件类型的文件可以投放到编辑器中。The strings should be MIME types, and will be checked against the type of the File object as reported by the browser.字符串应该是MIME类型,将针对由浏览器报告的File对象的type来检查它。
cursorBlinkRate: number
Half-period in milliseconds used for cursor blinking. 光标闪动的以毫秒计的半周期。The default blink rate is 530ms. 默认闪烁率为530ms。By setting this to zero, blinking can be disabled. 把它设置为0,就会禁用闪烁。A negative value hides the cursor entirely.负值就整个隐藏了光标。
cursorScrollMargin: number
How much extra space to always keep above and below the cursor when approaching the top or bottom of the visible view in a scrollable document. 当到达可滚动文档的视口的顶部或底部时,光标上面和下面需要保持多少额外的空间。Default is 0.默认值是0。
cursorHeight: number
Determines the height of the cursor. 确定光标的高度。Default is 1, meaning it spans the whole height of the line. 默认值为1,意味着它将跨整个行高。For some fonts (and by some tastes) a smaller height (for example 0.85), which causes the cursor to not reach all the way to the bottom of the line, looks better对于某些字体(以及一些品味),一个较小的高度(例如0.85)将导致光标根本无法触及行的底部,看起来更好。
resetSelectionOnContextMenu: boolean
Controls whether, when the context menu is opened with a click outside of the current selection, the cursor is moved to the point of the click. 控制当当前选区外面的一次点击打开上下文菜单时,光标是否移到点击的点。Defaults to true.默认值是true
workTime, workDelay: number
Highlighting is done by a pseudo background-thread that will work for workTime milliseconds, and then use timeout to sleep for workDelay milliseconds. 通过伪后台线程完成高亮,将在workTime毫秒后起作用,然后使用停时来沉睡workDelay毫秒。The defaults are 200 and 300, you can change these options to make the highlighting more or less aggressive.默认值是200和300,你可以修改此配置项,以使高亮更多或更少具有侵犯性。
pollInterval: number
Indicates how quickly CodeMirror should poll its input textarea for changes (when focused). 指示CodeMirror在得到焦点时,需要多快地轮询它的输入textarea域,以感知更改。Most input is captured by events, but some things, like IME input on some browsers, don't generate events that allow CodeMirror to properly detect it. 大多数输入是被事件捕获的,但是有些事情,像有些浏览器中的IME输入,并不生成事件,让浏览器来正确地侦测到它。Thus, it polls. 因此,需要轮询。Default is 100 milliseconds.默认值为100毫秒。
flattenSpans: boolean
By default, CodeMirror will combine adjacent tokens into a single span if they have the same class. 默认情况下,相领的span如果有相同的类,CodeMirror将把相邻的口令合并成一个span。This will result in a simpler DOM tree, and thus perform better. 这将导致更简单的DOM树,因此性能更好。With some kinds of styling (such as rounded corners), this will change the way the document looks. 因为某些样式(譬如圆角),这将改变文档的外观。You can set this option to false to disable this behavior.你可以把此配置项设置为false来禁用这种行为。
addModeClass: boolean
When enabled (off by default), an extra CSS class will be added to each token, indicating the (inner) mode that produced it, prefixed with "cm-m-". 当启用时(默认为关闭的),将对每个口令添加额外的CSS类,指示产生它的模式(inner),带有前缀"cm-m-"For example, tokens from the XML mode will get the cm-m-xml class.例如,来自XML模式的口令将得到cm-m-xml类。
maxHighlightLength: number
When highlighting long lines, in order to stay responsive, the editor will give up and simply style the rest of the line as plain text when it reaches a certain position. 在高亮长行时,为了保持响应,当达到一定的位置时,将放弃编辑器,并将行的剩余部分简单样式为纯文本。The default is 10 000. 默认值为10000。You can set this to Infinity to turn off this behavior.你可以把这设置为Infinity来关闭此行为。
viewportMargin: integer
Specifies the amount of lines that are rendered above and below the part of the document that's currently scrolled into view. 指定当前滚动到视图中的文档部分的上方和下方呈现的行数。This affects the amount of updates needed when scrolling, and the amount of work that such an update does. 这会影响滚动时所需的更新量,以及此类更新所做的工作量。You should usually leave it at its default, 10. 通常不需要修改它,使用它的默认值0Can be set to Infinity to make sure the whole document is always rendered, and thus the browser's text search works on it. 可以把它设置为Infinity,以确保始终呈现整个文档,因此浏览器的文本搜索能对它起作用。This will have bad effects on performance of big documents.这将对大文档的性能产生不良影响。

Events事件

Various CodeMirror-related objects emit events, which allow client code to react to various situations. 各种与CodeMirror相关的对象发出事件,这些事件允许客户端代码对各种情况作出反应。Handlers for such events can be registered with the on and off methods on the objects that the event fires on. 可利用on方法和off方法在引发事件的对象上注册这些事件的处理器。To fire your own events, use CodeMirror.signal(target, name, args...), where target is a non-DOM-node object.若要引发你自己的事件,请使用CodeMirror.signal(target, name, args...),其中target是一个非DOM节点对象。

An editor instance fires the following events. 某个编辑器引发下面的事件。The instance argument always refers to the editor itself.instance参数始终引用编辑器本身。

"change" (instance: CodeMirror, changeObj: object)
Fires every time the content of the editor is changed. 每当编辑器的内容被改变时引发此事件。The changeObj is a {from, to, text, removed, origin} object containing information about the changes that occurred as second argument. changeObj是一个{from, to, text, removed, origin}对象,包含了关于发生的改变的信息,作为第二个参数。from and to are the positions (in the pre-change coordinate system) where the change started and ended (for example, it might be {ch:0, line:18} if the position is at the beginning of line #19). fromto是更改开始和结束的位置(用更改前的坐标系统)(例如,如果位置开始于第19行,它可能是{ch:0, line:18})。text is an array of strings representing the text that replaced the changed range (split by line). text是字符串的数组,代表改变的范围内被替换的文本(用行隔开)。removed is the text that used to be between from and to, which is overwritten by this change. removed是原来在fromto之间的文本,它会在更改中被覆盖。This event is fired before the end of an operation, before the DOM updates happen.此事件会在一次操作结束之前、在DOM更新发生之前引发。
"changes" (instance: CodeMirror, changes: array<object>)
Like the "change" event, but batched per operation, passing an array containing all the changes that happened in the operation. "change"差不多,但是对各次操作批处理,传入一个数组,包含操作中发生的所有的改变。This event is fired after the operation finished, and display changes it makes will trigger a new operation.此事事件是在操作结束时引发此事件,显示它所做的改变,将触发一个新的操作。
"beforeChange" (instance: CodeMirror, changeObj: object)
This event is fired before a change is applied, and its handler may choose to modify or cancel the change. 在应用更改之前引发此事件,它的处理器将选择修改或撤销更改。The changeObj object has from, to, and text properties, as with the "change" event. changeObj对象具有fromtotext属性,和"change"事件中的changeObj对象相似。It also has a cancel() method, which can be called to cancel the change, and, if the change isn't coming from an undo or redo event, an update(from, to, text) method, which may be used to modify the change. 它还具有一个可以调用它来撤销或重做事件的cancel()方法、一个可以用来修改更改的update(from, to, text)方法,Undo or redo changes can't be modified, because they hold some metainformation for restoring old marked ranges that is only valid for that specific change. 撤销或重做更改不能被修改,因为它们容纳了一些元信息,用来恢复旧的标记范围,只对特定的改变有效。All three arguments to update are optional, and can be left off to leave the existing value for that field intact. update的三个参数全都是可选的,可以留空,以保持该字段的现有值不变。
Note: you may not do anything from a "beforeChange" handler that would cause changes to the document or its visualization. 注意:你不能通过"beforeChange"处理函数来做任何可能导致文档或它的可视化改变的事情。Doing so will, since this handler is called directly from the bowels of the CodeMirror implementation, probably cause the editor to become corrupted.因为此处理函数直接从CodeMirror实现器的内部调用的,所以,这样做可能导致损坏编辑器。
"cursorActivity" (instance: CodeMirror)
Will be fired when the cursor or selection moves, or any change is made to the editor content.将在光标或选区移动时引发此事件,或者在对编辑器内容做任何更改时引发。
"keyHandled" (instance: CodeMirror, name: string, event: Event)
Fired after a key is handled through a key map. 在通过键映射处理键之后引发此事件。name is the name of the handled key (for example "Ctrl-X" or "'q'"), and event is the DOM keydown or keypress event.name是处理键的名称(例如"Ctrl-X""'q'"),并且eventkeydownkeypress事件。
"inputRead" (instance: CodeMirror, changeObj: object)
Fired whenever new input is read from the hidden textarea (typed or pasted by the user).每当从隐藏的textarea文本域中读取输入(由用户键入或粘贴)的时候引发。
"electricInput" (instance: CodeMirror, line: integer)
Fired if text input matched the mode's electric patterns, and this caused the line's indentation to change.如果文本输入匹配模式的electric,则引发此事件,这将导致改变行的缩进。
"beforeSelectionChange" (instance: CodeMirror, obj: {ranges, origin, update})
This event is fired before the selection is moved. 在选区移动之前引发此事件。Its handler may inspect the set of selection ranges, present as an array of {anchor, head} objects in the ranges property of the obj argument, and optionally change them by calling the update method on this object, passing an array of ranges in the same format. 它的处理函数可能影响选区范围的集合,选区范围集合呈现为一个{anchor, head}对象的数组,存放在obj参数的ranges属性里,视需要可以通过调用此对象上的update方法来改变它们,传入同样格式的范围数组。The object also contains an origin property holding the origin string passed to the selection-changing method, if any. 此对象还包含了一个origin属性,容纳了传给选区改变方法的原始字符串,如果有这个字符串的话。Handlers for this event have the same restriction as "beforeChange" handlers — they should not do anything to directly update the state of the editor.对于此事件的处理函数具有和"beforeChange"处理函数相同的约束——它们不能做任何直接更新编辑器状态的事情。
"viewportChange" (instance: CodeMirror, from: number, to: number)
Fires whenever the view port of the editor changes (due to scrolling, editing, or any other factor). 每当编辑器的视口改变时(由于滚动、编辑或其它因素)时引发此事件。The from and to arguments give the new start and end of the viewport.参数fromto给了视图的新开始点和结束点。
"swapDoc" (instance: CodeMirror, oldDoc: Doc)
This is signalled when the editor's document is replaced using the swapDoc method.当编辑器的文档利用swapDoc方法替换的时候,发出此信号。
"gutterClick" (instance: CodeMirror, line: integer, gutter: string, clickEvent: Event)
Fires when the editor gutter (the line-number area) is clicked. 当编辑器沟槽(行数字区域)被点击时引发此事件。Will pass the editor instance as first argument, the (zero-based) number of the line that was clicked as second argument, the CSS class of the gutter that was clicked as third argument, and the raw mousedown event object as fourth argument.将传入编辑器实例,作为第一个参数,被点击的(基于零的)行数字将作为第二个参数,被点击的沟槽的CSS类作为第三个参数,原始的mousedown事件对象作为第四个参数。
"gutterContextMenu" (instance: CodeMirror, line: integer, gutter: string, contextMenu: Event: Event)
Fires when the editor gutter (the line-number area) receives a contextmenu event. 当编辑器沟槽(行数字区域)接收到一次contextmenu事件时引发此事件。Will pass the editor instance as first argument, the (zero-based) number of the line that was clicked as second argument, the CSS class of the gutter that was clicked as third argument, and the raw contextmenu mouse event object as fourth argument. 将传入编辑器实例作为第一个参数,被点击的(基于零的)行数字作为第二个参数,被点击的沟槽的CSS类作为第三个参数,原始的contextmenu鼠标事件作为第四个参数。You can preventDefault the event, to signal that CodeMirror should do no further handling.你可以preventDefault此事件,从而向CodeMirror发出信号,不需要再做进一步处理了。
"focus" (instance: CodeMirror, event: Event)
Fires whenever the editor is focused.每当编辑器得到焦点时引发此事件。
"blur" (instance: CodeMirror, event: Event)
Fires whenever the editor is unfocused.每当编辑器失去焦点时引发此事件。
"scroll" (instance: CodeMirror)
Fires when the editor is scrolled.每当编辑器滚动时引发此事件。
"refresh" (instance: CodeMirror)
Fires when the editor is refreshed or resized. 每当刷新编辑器改变编辑器的尺寸时引发此事件。Mostly useful to invalidate cached values that depend on the editor or character size.主要用于使依赖于编辑器尺寸或字符大小的缓存值无效。
"optionChange" (instance: CodeMirror, option: string)
Dispatched every time an option is changed with setOption.每次利用setOption改变选项时派遣此事件。
"scrollCursorIntoView" (instance: CodeMirror, event: Event)
Fires when the editor tries to scroll its cursor into view. 当编辑器试图滚动以将光标滚进可视区域时引发此事件。Can be hooked into to take care of additional scrollable containers around the editor. 可以钩住它以照顾附加的围绕着编辑器的可滚动的容器。When the event object has its preventDefault method called, CodeMirror will not itself try to scroll the window.当事件对象调用它的preventDefault方法时,CodeMirror将不会试图滚动容器。
"update" (instance: CodeMirror)
Will be fired whenever CodeMirror updates its DOM display.每当CodeMirror更新它的DOM显示时引发此事件。
"renderLine" (instance: CodeMirror, line: LineHandle, element: Element)
Fired whenever a line is (re-)rendered to the DOM. 每当一个行重新呈现到DOM中时引发此事件。Fired right after the DOM element is built, before it is added to the document. 在创建DOM元素之后立即引发此事件,但是此事件发生在把DOM元素加入到文档之前。The handler may mess with the style of the resulting element, or add event handlers, but should not try to change the state of the editor.此处理函数可能会搞乱输出元素的样式,或者添加事件处理函数,但是不能试图改变编辑器的状态。
"mousedown", "dblclick", "touchstart", "contextmenu", "keydown", "keypress", "keyup", "cut", "copy", "paste", "dragstart", "dragenter", "dragover", "dragleave", "drop" (instance: CodeMirror, event: Event)
Fired when CodeMirror is handling a DOM event of this type. 在CodeMirror处理此类型的DOM事件时引发此事件。You can preventDefault the event, or give it a truthy codemirrorIgnore property, to signal that CodeMirror should do no further handling.你可以preventDefault此事件,或给它一个真实的codemirrorIgnore属性,以向CodeMirror发出信号,不要进一步处理。

Document objects (instances of CodeMirror.Doc) emit the following events:文档对象(CodeMirror.Doc的实例)会发出下面的事件:

"change" (doc: CodeMirror.Doc, changeObj: object)
Fired whenever a change occurs to the document. 每当文档发生改变时引发此事件。changeObj has a similar type as the object passed to the editor's "change" event.changeObj对象具有传给编辑器的"change"事件的changeObj对象相同的类型。
"beforeChange" (doc: CodeMirror.Doc, change: object)
See the description of the same event on editor instances.请参阅编辑器实例上的相同事件的描述
"cursorActivity" (doc: CodeMirror.Doc)
Fired whenever the cursor or selection in this document changes.每当文档中的光标或选区改变时引发此事件。
"beforeSelectionChange" (doc: CodeMirror.Doc, selection: {head, anchor})
Equivalent to the event by the same name as fired on editor instances.等同于编辑器实例上引发的同名事件

Line handles (as returned by, for example, getLineHandle) support these events:行处理函数(例如,getLineHandle方法返回的对象)支持这些事件:

"delete" ()
Will be fired when the line object is deleted. 在行对象被删除时将引发此事件。A line object is associated with the start of the line. 行对象与行的开头相关联。Mostly useful when you need to find out when your gutter markers on a given line are removed.当你需要找出给定行上的沟槽标记何时被删除时,它很有用。
"change" (line: LineHandle, changeObj: object)
Fires when the line's text content is changed in any way (but the line is not deleted outright). 当行的文本内容以任何方式改变(但是没有完全删除此行)时,引发此事件。The change object is similar to the one passed to change event on the editor object.changeObj对象类似于编辑器对象上传递给"change"事件的changeObj对象。

Marked range handles (CodeMirror.TextMarker), as returned by markText and setBookmark, emit the following events:被标记的范围(CodeMirror.TextMarker)的处理函数,被标记的范围是由markText方法和setBookmark方法返回的对象,它会发出下面的事件:

"beforeCursorEnter" ()
Fired when the cursor enters the marked range. 当光标进入一个被标记的范围时引发此事件。From this event handler, the editor state may be inspected but not modified, with the exception that the range on which the event fires may be cleared.利用此事件处理函数,可以影响编辑器的状态,但是不能修改编辑器,例外是引发事件的被标记范围可能被清空了。
"clear" (from: {line, ch}, to: {line, ch})
Fired when the range is cleared, either through cursor movement in combination with clearOnEnter or through a call to its clear() method. 当被标记的范围被清空时引发此事件,既可以是由于光标运动配合clearOnEnter,也可以是由于调用了它的clear()方法。Will only be fired once per handle. 只对每次处理引发一次。Note that deleting the range through text editing does not fire this event, because an undo action might bring the range back into existence. 请注意,通过文本编辑删除范围并不引发此事件,因为一个撤销动作可能恢复此范围。from and to give the part of the document that the range spanned when it was cleared.在此范围被清空时,fromto给出了文档中,它跨过的部分。
"hide" ()
Fired when the last part of the marker is removed from the document by editing operations.因为编辑处理而从文档中删除标记的最后一部分时,引发此事件。
"unhide" ()
Fired when, after the marker was removed by editing, a undo operation brought the marker back.因为编辑而删除标记时引发此事件,撤销操作可能恢复此标记。

Line widgets (CodeMirror.LineWidget), returned by addLineWidget, fire these events:行部件(CodeMirror.LineWidget),由addLineWidget方法返回,引发这些事件:

"redraw" ()
Fired whenever the editor re-adds the widget to the DOM. 每当编辑器再次把部件添加到DOM中时引发此事件。This will happen once right after the widget is added (if it is scrolled into view), and then again whenever it is scrolled out of view and back in again, or when changes to the editor options or the line the widget is on require the widget to be redrawn.在添加部件之后立即引发此事件(如果它是滚动进入可视区域的),每当小部件滚出可视区域的时候,每当小部件再次滚进可视区域的时候,或者当编辑器的选项发生改变时,或者小部件所在行要求重新绘制小部件时,都会再次引发此事件。

Key Maps键映射

Key maps are ways to associate keys and mouse buttons with functionality. 键映射是将键盘键和鼠标按钮与功能相关联的方式。A key map is an object mapping strings that identify the buttons to functions that implement their functionality.键映射是一个对象,把标识按钮的字符串映射到实现它们的功能的函数。

The CodeMirror distributions comes with Emacs, Vim, and Sublime Text-style keymaps.CodeMirror分发包自带了EmacsVimSublime Text风格的键映射。

Keys are identified either by name or by character. 可以按键名称或键字符来映射映。The CodeMirror.keyNames object defines names for common keys and associates them with their key codes. CodeMirror.keyNames对象定义了针对常见键的名称,并把它们关联到键代码。Examples of names defined here are Enter, F5, and Q. 例如此处定义的键名称有EnterF5QThese can be prefixed with Shift-, Cmd-, Ctrl-, and Alt- to specify a modifier. 它们可以加前缀Shift-Cmd-Ctrl-Alt-来指定修饰符。So for example, Shift-Ctrl-Space would be a valid key identifier.所以例如Shift-Ctrl-Space算是一个有效的键标识符。

Common example: map the Tab key to insert spaces instead of a tab character.常见示例:映射Tab键以插入空格,而不是插入制表符:

editor.setOption("extraKeys", {
Tab: function(cm) {
var spaces = Array(cm.getOption("indentUnit") + 1).join(" ");
cm.replaceSelection(spaces);
}
});

Alternatively, a character can be specified directly by surrounding it in single quotes, for example '$' or 'q'. 或者,可以直接用单引号包围字符来指定一个字符,例如:'$''q'Due to limitations in the way browsers fire key events, these may not be prefixed with modifiers.由于浏览器引发键事件的限制,这些可能不能加前缀修饰符。

To bind mouse buttons, use the names `LeftClick`, `MiddleClick`, and `RightClick`. 若要绑定鼠标按钮,请使用名称`LeftClick``MiddleClick`以及`RightClick`These can also be prefixed with modifiers, and in addition, the word `Double` or `Triple` can be put before `Click` (as in `LeftDoubleClick`) to bind a double- or triple-click. 它们可以加前缀修饰符,此外,单词`Double``Triple`可以放在`Click`前面(譬如写成`LeftDoubleClick`)以绑定双击或三击。The function for such a binding is passed the position that was clicked as second argument.这样绑定的函数,传入了被点击的位置,作为第二个参数。

Multi-stroke key bindings can be specified by separating the key names by spaces in the property name, for example Ctrl-X Ctrl-V. 可以通过在属性名中用空格分隔键名来指定多次击键键绑定,例如Ctrl-X Ctrl-VWhen a map contains multi-stoke bindings or keys with modifiers that are not specified in the default order (Shift-Cmd-Ctrl-Alt), you must call CodeMirror.normalizeKeyMap on it before it can be used. 当映射包含多次击键绑定或带有包饰符的键,如果没有用默认顺序指定它们(Shift-Cmd-Ctrl-Alt),你可以在使用它之前,它上面调用CodeMirror.normalizeKeyMapThis function takes a keymap and modifies it to normalize modifier order and properly recognize multi-stroke bindings. 此函数取用了一个键映射,并把它修改为正规的修饰符顺序,并正确地识别多次击键绑定。It will return the keymap itself.它将返回键映射本身。

The CodeMirror.keyMap object associates key maps with names. CodeMirror.keyMap将键映射与键名称相关联。User code and key map definitions can assign extra properties to this object. 用户代码和键映射定义可以将额外的属性赋给此对象。Anywhere where a key map is expected, a string can be given, which will be looked up in this object. 需要键映射的地方,都可以给一个字符串,将会在此对象中查找它。It also contains the "default" key map holding the default bindings.它还包含了"default"键映射,容纳了默认的绑定。

The values of properties in key maps can be either functions of a single argument (the CodeMirror instance), strings, or false. 键映射中的属性的值既可以是单参数的函数(参数是CodeMirror实例),也可以是字符串或者falseStrings refer to commands, which are described below. 字符串指的是命令,下面描述了它。If the property is set to false, CodeMirror leaves handling of the key up to the browser. 如果属性被设置为false,CodeMirror将把键的处理留给浏览 。A key handler function may return CodeMirror.Pass to indicate that it has decided not to handle the key, and other handlers (or the default behavior) should be given a turn.某个键处理函数可能返回CodeMirror.Pass,以指示它已经决定不处理此键,其它处理函数(或者默认行为)应该拐弯。

Keys mapped to command names that start with the characters "go" or to functions that have a truthy motion property (which should be used for cursor-movement actions) will be fired even when an extra Shift modifier is present (i.e. "Up": "goLineUp" matches both up and shift-up). 键映射到命令名称,如果名称开始于字符"go",或者映射到函数,函数带有真正的motion属性(它应该用于光标移动动作),哪怕存在额外的Shift修饰符,也将引发它(亦即,"Up": "goLineUp"既匹配up,又匹配shift-up)。This is used to easily implement shift-selection.这用来轻松实现按住Shift键做选区。

Key maps can defer to each other by defining a fallthrough property. 通过定义fallthrough属性,键映射可以互相延迟。This indicates that when a key is not found in the map itself, one or more other maps should be searched. 这表示,当在映射本身中找不到键时,将搜索一个或多个其它映射。It can hold either a single key map or an array of key maps.它既可以容纳单个键映射,也可以容纳键映射的数组。

When a key map needs to set something up when it becomes active, or tear something down when deactivated, it can contain attach and/or detach properties, which should hold functions that take the editor instance and the next or previous keymap. 当键映射在激活它时需要设置一些东西时,或者它失活时需要拆掉一些东西时,它可以包含attach属性和/或detach属性,它应该容纳函数,取用编辑器实例和下一个或上一个键映射作为参数。Note that this only works for the top-level keymap, not for fallthrough maps or maps added with extraKeys or addKeyMap.请注意它只对顶级键映射起作用,不对降落的映射或者利用extraKeys方法和addKeyMap方法添加的映射起作用。

Commands命令

Commands are parameter-less actions that can be performed on an editor. 命令是在编辑器上执行的几乎没有参数的动作。Their main use is for key bindings. 它们主要用于键绑定。Commands are defined by adding properties to the CodeMirror.commands object. 可以通过给CodeMirror.commands对象添加属性来定义命令。A number of common commands are defined by the library itself, most of them used by the default key bindings. 库自身已经定义了一些常见的命令,大多数用于默认的键绑定。The value of a command property must be a function of one argument (an editor instance).命令的属性值必须是一个单参数的函数(参数就是编辑器实例)。

Some of the commands below are referenced in the default key map, but not defined by the core library. 下面的一些命令在默认的键映射中被引用,但不是由核心库定义的。These are intended to be defined by user code or addons.这些都是打算由用户代码或插件定义的。

Commands can also be run with the execCommand method.还可以配合execCommand方法运行命令。

selectAllCtrl-A (PC), Cmd-A (Mac)
Select the whole content of the editor.选择编辑器的整个内容。
singleSelectionEsc
When multiple selections are present, this deselects all but the primary selection.当存在多个选区时,这将取消选中除了主选区之外的所有选区。
killLineCtrl-K (Mac)
Emacs-style line killing. Emacs风格的行删除。Deletes the part of the line after the cursor. 删除了行内光标后面的部分。If that consists only of whitespace, the newline at the end of the line is also deleted.如果它只是由空格构成的,行末尾的新行符号也会被删除。
deleteLineCtrl-D (PC), Cmd-D (Mac)
Deletes the whole line under the cursor, including newline at the end.删除光标下面的一整行,包括末尾的新行符号。
delLineLeft
Delete the part of the line before the cursor.删除了行内光标前面的部分。
delWrappedLineLeftCmd-Backspace (Mac)
Delete the part of the line from the left side of the visual line the cursor is on to the cursor.删除光标所在行从可视行左侧到光标的部分。
delWrappedLineRightCmd-Delete (Mac)
Delete the part of the line from the cursor to the right side of the visual line the cursor is on.删除光标所在行从光标到可视行右侧的部分。
undoCtrl-Z (PC), Cmd-Z (Mac)
Undo the last change. 撤销最后的更改。Note that, because browsers still don't make it possible for scripts to react to or customize the context menu, selecting undo (or redo) from the context menu in a CodeMirror instance does not work.请注意,因为浏览器依然无法让脚本对上下文菜单做出反应,或者自定义上下文菜单,所以在CodeMirror实例中从上下文菜单中选择撤销(或重做)是不起作用的。
redoCtrl-Y (PC), Shift-Cmd-Z (Mac), Cmd-Y (Mac)
Redo the last undone change.重做上一次撤销的更改。
undoSelectionCtrl-U (PC), Cmd-U (Mac)
Undo the last change to the selection, or if there are no selection-only changes at the top of the history, undo the last change.撤销对选区的最后的更改,或者如果在历史栈的前面不存在唯选区的更改,就撤销上一次更改。
redoSelectionAlt-U (PC), Shift-Cmd-U (Mac)
Redo the last change to the selection, or the last text change if no selection changes remain.重做对选区的最后更改,或者如果没有选区更改,就重做上一次文本更改。
goDocStartCtrl-Home (PC), Cmd-Up (Mac), Cmd-Home (Mac)
Move the cursor to the start of the document.把光标移动到文档的开头。
goDocEndCtrl-End (PC), Cmd-End (Mac), Cmd-Down (Mac)
Move the cursor to the end of the document.把光标移动到文档的末尾。
goLineStartAlt-Left (PC), Ctrl-A (Mac)
Move the cursor to the start of the line.把光标移动到行的开头。
goLineStartSmartHome
Move to the start of the text on the line, or if we are already there, to the actual start of the line (including whitespace).把光标移动到行的文本开头,或者如果已经在那里的话,就移到行的实际开头(包括空白)。
goLineEndAlt-Right (PC), Ctrl-E (Mac)
Move the cursor to the end of the line.把光标移动到行的末尾。
goLineRightCmd-Right (Mac)
Move the cursor to the right side of the visual line it is on.把光标移动到它所在的可视行的右侧。
goLineLeftCmd-Left (Mac)
Move the cursor to the left side of the visual line it is on. 把光标移动到它所在的可视行的左侧。If this line is wrapped, that may not be the start of the line.如果此行折行了,它不能在行的开头。
goLineLeftSmart
Move the cursor to the left side of the visual line it is on. 把光标移到它所在的可视行的左侧。If that takes it to the start of the line, behave like goLineStartSmart.如果这把它带到行的开头,行为就像goLineStartSmart
goLineUpUp, Ctrl-P (Mac)
Move the cursor up one line.把光标上移一行。
goLineDownDown, Ctrl-N (Mac)
Move down one line.把光标下移一行。
goPageUpPageUp, Shift-Ctrl-V (Mac)
Move the cursor up one screen, and scroll up by the same distance.把光标上移一屏,并向上滚动相同的距离。
goPageDownPageDown, Ctrl-V (Mac)
Move the cursor down one screen, and scroll down by the same distance.把光标下移一屏,并向下滚动相同的距离。
goCharLeftLeft, Ctrl-B (Mac)
Move the cursor one character left, going to the previous line when hitting the start of line.把光标往左移一个字符,如果它碰到一行开头,就去上一行的末尾。
goCharRightRight, Ctrl-F (Mac)
Move the cursor one character right, going to the next line when hitting the end of line.把光标往右移一个字符,如果它碰到一行末尾,就去下一行的开头。
goColumnLeft
Move the cursor one character left, but don't cross line boundaries.把光标往左移一个字符,但是不会跨过行边界。
goColumnRight
Move the cursor one character right, don't cross line boundaries.把光标往右移一个字符,但是不会跨过行边界。
goWordLeftAlt-B (Mac)
Move the cursor to the start of the previous word.把光标移到前一个单词的开头。
goWordRightAlt-F (Mac)
Move the cursor to the end of the next word.把光标移到下一个单词的末尾。
goGroupLeftCtrl-Left (PC), Alt-Left (Mac)
Move to the left of the group before the cursor. 把光标移到它前面的组的左侧。A group is a stretch of word characters, a stretch of punctuation characters, a newline, or a stretch of more than one whitespace character.组是单词字符的伸展、标点符号字符的伸展、新行或者多个空白字符的伸展。
goGroupRightCtrl-Right (PC), Alt-Right (Mac)
Move to the right of the group after the cursor (see above).把光标移到它后面的组的右侧(请参阅上面对组的解释。)
delCharBeforeShift-Backspace, Ctrl-H (Mac)
Delete the character before the cursor.删除光标前面的字符。
delCharAfterDelete, Ctrl-D (Mac)
Delete the character after the cursor.删除光标后面的字符。
delWordBeforeAlt-Backspace (Mac)
Delete up to the start of the word before the cursor.删除光标前面的单词部分。
delWordAfterAlt-D (Mac)
Delete up to the end of the word after the cursor.删除光标后面的单词部分。
delGroupBeforeCtrl-Backspace (PC), Alt-Backspace (Mac)
Delete to the left of the group before the cursor.删除到光标前面的的左侧。
delGroupAfterCtrl-Delete (PC), Ctrl-Alt-Backspace (Mac), Alt-Delete (Mac)
Delete to the start of the group after the cursor.删除到光标后面的的开头。
indentAutoShift-Tab
Auto-indent the current line or selection.自动缩进当前行或者当前选区。
indentMoreCtrl-] (PC), Cmd-] (Mac)
Indent the current line or selection by one indent unit.将当前行或当前选区缩进一个缩进单位
indentLessCtrl-[ (PC), Cmd-[ (Mac)
Dedent the current line or selection by one indent unit.将当前行或当前选区反缩进一个缩进单位
insertTab
Insert a tab character at the cursor.在光标位置插入一个制表符。
insertSoftTab
Insert the amount of spaces that match the width a tab at the cursor position would have.插入一些空格,匹配光标位置应该具有的制表符的宽度。
defaultTabTab
If something is selected, indent it by one indent unit. 如果选中了一些东西,就把它缩进一个缩进单位If nothing is selected, insert a tab character.如果没选中什么东西,就插入一个制表符。
transposeCharsCtrl-T (Mac)
Swap the characters before and after the cursor.交换光标前后的字符。
newlineAndIndentEnter
Insert a newline and auto-indent the new line.插入一个新行,并且自动缩进新行。
toggleOverwriteInsert
Flip the overwrite flag.翻转overwrite标记。
saveCtrl-S (PC), Cmd-S (Mac)
Not defined by the core library, only referred to in key maps. 不是由核心库定义的,只在键映射中起作用。Intended to provide an easy way for user code to define a save command.旨在提供一个简单的方法,用来定义一个保存用户代码的命令。
findCtrl-F (PC), Cmd-F (Mac)
findNextCtrl-G (PC), Cmd-G (Mac)
findPrevShift-Ctrl-G (PC), Shift-Cmd-G (Mac)
replaceShift-Ctrl-F (PC), Cmd-Alt-F (Mac)
replaceAllShift-Ctrl-R (PC), Shift-Cmd-Alt-F (Mac)
Not defined by the core library, but defined in the search addon (or custom client addons).不是由核心库定义的,但是定义在搜索附件(或自定义的附件)中。

Customized Styling自定义的样式

Up to a certain extent, CodeMirror's look can be changed by modifying style sheet files. 从某种程度上来说,可以通过修改样式表文件来改变CodeMirror的外观。The style sheets supplied by modes simply provide the colors for that mode, and can be adapted in a very straightforward way. 由模式提供的样式表文件仅提供了针对模式的着色,可以用非常直观的方法调整它。To style the editor itself, it is possible to alter or override the styles defined in codemirror.css.若要样式化编辑器本身,可以修改或重写定义在codemirror.css中的样式。

Some care must be taken there, since a lot of the rules in this file are necessary to have CodeMirror function properly. 此处必须稍作注意,因为要使codemirror正常工作,此文件中的许多规则都是必需的。Adjusting colors should be safe, of course, and with some care a lot of other things can be changed as well. 当然,调整颜色应该是安全的,而且在一定程度上,其他很多事情也可以修改。The CSS classes defined in this file serve the following roles:定义在此文件中的CSS类提供了下面的角色:

CodeMirror
The outer element of the editor. 编辑器的外层元素。This should be used for the editor width, height, borders and positioning. 这应该用于编辑器的宽度、高度和定位。Can also be used to set styles that should hold for everything inside the editor (such as font and font size), or to set a background. 还可以用来设置编辑器内部一切东西的样式,譬如字体和字号。Setting this class' height style to auto will make the editor resize to fit its content (it is recommended to also set the viewportMargin option to Infinity when doing this.将此类的height样式设置为auto,将使编辑器改变尺寸以适应它的内容(建议在这样做时,同时把viewportMargin配置项设置为Infinity。)
CodeMirror-focused
Whenever the editor is focused, the top element gets this class. 当编辑器得到焦点时,顶层元素得到此类。This is used to hide the cursor and give the selection a different color when the editor is not focused.这用来隐藏光标,并给选区一个不同于编辑器没有得到焦点时的颜色。
CodeMirror-gutters
This is the backdrop for all gutters. 这是所有沟槽的背景。Use it to set the default gutter background color, and optionally add a border on the right of the gutters.使用它来设置默认沟槽背景色,视情况在沟槽的右侧添加边框线。
CodeMirror-linenumbers
Use this for giving a background or width to the line number gutter.使用它来给行数字沟槽指定背景或宽度。
CodeMirror-linenumber
Used to style the actual individual line numbers. 用来样式化单个行数字。These won't be children of the CodeMirror-linenumbers (plural) element, but rather will be absolutely positioned to overlay it. 它们不是CodeMirror-linenumbers(复数)的子元素,而是被绝对定位到CodeMirror-linenumbers上面与它重叠。Use this to set alignment and text properties for the line numbers.使用类名来设置针对行数字的对齐和文本属性。
CodeMirror-lines
The visible lines. 可视的行。This is where you specify vertical padding for the editor content.这是你为编辑器内容指定垂直补白的地方。
CodeMirror-cursor
The cursor is a block element that is absolutely positioned. 光标是绝对定位的块元素。You can make it look whichever way you want.你可以把它变成你想要的外观。
CodeMirror-selected
The selection is represented by span elements with this class.选区是用带有此类的span元素代表的。
CodeMirror-matchingbracket, CodeMirror-nonmatchingbracket
These are used to style matched (or unmatched) brackets.这些用来样式化匹配(或不匹配)的括号。

If your page's style sheets do funky things to all div or pre elements (you probably shouldn't do that), you'll have to define rules to cancel these effects out again for elements under the CodeMirror class.如果你的网页样式表对所有的div元素或pre元素做了些奇怪的事情(或许你不该那样做),你就不得不针对CodeMirror类下的元素定义规则,来抵消这些效果。

Themes are also simply CSS files, which define colors for various syntactic elements. 主题也是CSS文件,它们定义了针对各种语法元素的颜色。See the files in the theme directory.请参阅theme目录中的文件。

Programming API编程API

A lot of CodeMirror features are only available through its API. 很多CodeMirror只有通过它的API才可用。Thus, you need to write code (or use addons) if you want to expose them to your users.因此,如果你想把接口曝露给用户,你就需要编写代码(或者使用附件)。

Whenever points in the document are represented, the API uses objects with line and ch properties. 每当代表文档中的点时,API都使用带有属性linech的对象。Both are zero-based. 这两个属性都是基于0的。CodeMirror makes sure to 'clip' any positions passed by client code so that they fit inside the document, so you shouldn't worry too much about sanitizing your coordinates. CodeMirror确保“夹住”客户端代码传入的任何位置,从而它们适应在文档内部,从而你不需要操作如何无害化坐标。If you give ch a value of null, or don't specify it, it will be replaced with the length of the specified line. 如果给ch指定了值null,或者没有指定它,它将被替换为指定行的长度。Such positions may also have a sticky property holding "before" or "after", whether the position is associated with the character before or after it. 这种位置可能还有一个sticky属性,容纳了"before""after",来确定位置是与它前面的字符相关联,还是与它后面的字符相关联。This influences, for example, where the cursor is drawn on a line-break or bidi-direction boundary.例如,这会影响光标在断行或双向边界上的绘制位置。

Methods prefixed with doc. can, unless otherwise specified, be called both on CodeMirror (editor) instances and CodeMirror.Doc instances. 带有前缀doc.的方法,除非另有指定,它既可以在CodeMirror(编辑器)实例上调用,也可以在CodeMirror.Doc实例上调用。Methods prefixed with cm. are only available on CodeMirror instances.带有cm.前缀的方法,只在CodeMirror实例上可用。

Constructor构造器

Constructing an editor instance is done with the CodeMirror(place: Element|fn(Element), ?option: object) constructor. 构造一个编辑器实例,是利用CodeMirror(place: Element|fn(Element), ?option: object)构造器来完成的。If the place argument is a DOM element, the editor will be appended to it. 如果place参数是一个DOM元素,则编辑器追加到它里面。If it is a function, it will be called, and is expected to place the editor into the document. 如果place是一个函数,将调用它,期待是编辑器要插入到文档的位置。options may be an element mapping option names to values. options可以是一个元素,把配置项名称映射到值。The options that it doesn't explicitly specify (or all options, if it is not passed) will be taken from CodeMirror.defaults.并不明确指定的配置项(或者如果没有传入此对象,就是所有配置项)将取用自来自CodeMirror.defaults的值。

Note that the options object passed to the constructor will be mutated when the instance's options are changed, so you shouldn't share such objects between instances.请注意,当实例的配置项被被修改时,传递给构造器的options对象也将被修改,因此你不应该在实例之间共享此对象。

See CodeMirror.fromTextArea for another way to construct an editor instance.请参阅CodeMirror.fromTextArea以了解构造一个编辑器实例的另一种方法。

Content manipulation methods内容操纵方法

doc.getValue(?separator: string) → string
Get the current editor content. 取得当前编辑器内容。You can pass it an optional argument to specify the string to be used to separate lines (defaults to "\n").你可以传给它一个可选的参数,以指定用来分隔行的字符串(默认值是"\n")。
doc.setValue(content: string)
Set the editor content.设置编辑器内容。
doc.getRange(from: {line, ch}, to: {line, ch}, ?separator: string) → string
Get the text between the given points in the editor, which should be {line, ch} objects. 取得编辑器中给定点之间的文本,给定点应该是{line, ch}对象。An optional third argument can be given to indicate the line separator string to use (defaults to "\n").可选的第三个参数可以给出指示要用的行分隔符字符串(默认值"\n")。
doc.replaceRange(replacement: string, from: {line, ch}, to: {line, ch}, ?origin: string)
Replace the part of the document between from and to with the given string. 用给定字符串替换文档中在fromto之间的那部分内容。from and to must be {line, ch} objects. fromto必须是{line, ch}对象。to can be left off to simply insert the string at position from. to可以留空,从而仅仅是在from位置插入字符串。When origin is given, it will be passed on to "change" events, and its first letter will be used to determine whether this change can be merged with previous history events, in the way described for selection origins.如果给定origin,它就将传递给"change"事件,它的第一个字母将用来确定此将改变是否与前一次历史事件合并。
doc.getLine(n: integer) → string
Get the content of line n.取得第n的内容。
doc.lineCount() → integer
Get the number of lines in the editor.取得编辑器中的行数目。
doc.firstLine() → integer
Get the number of first line in the editor. 取得编辑器中首行的数字。This will usually be zero but for linked sub-views, or documents instantiated with a non-zero first line, it might return other values.它通常是零,但是对于linked sub-views或者用非零首行实例化的documents,它可能返回其它值。
doc.lastLine() → integer
Get the number of last line in the editor. 取得编辑器中末行的数字。This will usually be doc.lineCount() - 1, but for linked sub-views, it might return other values.它通常是doc.lineCount() - 1,但是对于linked sub-views,它可能返回其它值。
doc.getLineHandle(num: integer) → LineHandle
Fetches the line handle for the given line number.抓取针对给定行数字的行处理器。
doc.getLineNumber(handle: LineHandle) → integer
Given a line handle, returns the current position of that line (or null when it is no longer in the document).给定一个行处理器,返回行的当前位置(如果处理器中在当前文档中,就返回null)。
doc.eachLine(f: (line: LineHandle))
doc.eachLine(start: integer, end: integer, f: (line: LineHandle))
Iterate over the whole document, or if start and end line numbers are given, the range from start up to (not including) end, and call f for each line, passing the line handle. 迭代遍整个文档,或者如果给定了startend,则范围是从startend(但不包括end),并对每一行调用f,传入行处理器。This is a faster way to visit a range of line handlers than calling getLineHandle for each of them. 这是访问一个行处理器范围更快的方法,快过针对每一项调用getLineHandleNote that line handles have a text property containing the line's content (as a string).请注意行处理器具有text属性,包含了行的内容(作为字符串)。
doc.markClean()
Set the editor content as 'clean', a flag that it will retain until it is edited, and which will be set again when such an edit is undone again. 将编辑器内容设置为‘clean’,这是它在被编辑前包含的标记,如果这样的编辑没有完成,内容将再次设置为‘clean’。Useful to track whether the content needs to be saved. 对跟踪是否需要保存内容很有用。This function is deprecated in favor of changeGeneration, which allows multiple subsystems to track different notions of cleanness without interfering.此函数已被建议弃用,由于changeGeneration允许多个子系统跟踪不同的清除记号法而互不干扰。
doc.changeGeneration(?closeEvent: boolean) → integer
Returns a number that can later be passed to isClean to test whether any edits were made (and not undone) in the meantime. 返回一个数字,它后来传给isClean以测试是否做了任何编辑(或者没做编辑)。If closeEvent is true, the current history event will be ‘closed’, meaning it can't be combined with further changes (rapid typing or deleting events are typically combined).如果closeEventtrue,则当前历史事件将是‘closed’,意味着它不会与未来的改变结合(快速键入或删除事件通常是结合在一起的)。
doc.isClean(?generation: integer) → boolean
Returns whether the document is currently clean — not modified since initialization or the last call to markClean if no argument is passed, or since the matching call to changeGeneration if a generation value is given.返回文档是否已被清理——从初始化以来没有被修改过,或者从上次调用不传参数的markClean以来没有被修改过,从匹配调用给了一个生成值的changeGeneration以来没被修改过。

Cursor and selection methods光标和选区方法

doc.getSelection(?lineSep: string) → string
Get the currently selected code. 取得当前选中的代码。Optionally pass a line separator to put between the lines in the output. 视情况传入一个行分隔符以放在输出中的行之间。When multiple selections are present, they are concatenated with instances of lineSep in between.如果存在多个选区,则它会用lineSep的实例作补间串联起来。
doc.getSelections(?lineSep: string) → array<string>
Returns an array containing a string for each selection, representing the content of the selections.返回一个数组,包含了针对每个选区的数组,代表选区的内容。
doc.replaceSelection(replacement: string, ?select: string)
Replace the selection(s) with the given string. 利用给定的字符串替换选区。By default, the new selection ends up after the inserted text. 默认情况下,新选区出现在被插入的文本之后。The optional select argument can be used to change this—passing "around" will cause the new text to be selected, passing "start" will collapse the selection to the start of the inserted text.可选的select参数可以用来改变这——传入"around"将导致新文本被选中,传入"start"将把选区折叠到被插入的文本的开头。
doc.replaceSelections(replacements: array<string>, ?select: string)
The length of the given array should be the same as the number of active selections. 给定数组的长度应该与激活选区的数目相同。Replaces the content of the selections with the strings in the array. 利用数组中的字符串替换选区中的内容。The select argument works the same as in replaceSelection.select参数产生与replaceSelection中的select参数相同的作用。
doc.getCursor(?start: string) → {line, ch}
Retrieve one end of the primary selection. 检索首要选区的一端。start is an optional string indicating which end of the selection to return. start是可选的字符串,指示返回选区的哪一端。It may be "from", "to", "head" (the side of the selection that moves when you press shift+arrow), or "anchor" (the fixed side of the selection). 它可以是"from""to""head"(当你按下shift+箭头键时,选区的一侧)或者"anchor"(选区的固定侧)。Omitting the argument is the same as passing "head". 省略此参数,相同于传入了参数"head"A {line, ch} object will be returned.将返回一个{line, ch}
doc.listSelections() → array<{anchor, head}>
Retrieves a list of all current selections. 检索当前选区的列表。These will always be sorted, and never overlap (overlapping selections are merged). 这将始终被排序,永远不会重叠(重叠的选区会被合并)。Each object in the array contains anchor and head properties referring to {line, ch} objects.数组中的每个对象包含anchor属性和head属性,引用到{line, ch}对象。
doc.somethingSelected() → boolean
Return true if any text is selected.如果文本被选中,就返回true
doc.setCursor(pos: {line, ch}|number, ?ch: number, ?options: object)
Set the cursor position. 设置光标的位置。You can either pass a single {line, ch} object, or the line and the character as two separate parameters. 你可以要么传入单个{line, ch}对象,或者将行数和字符数作为两个分开的参数传入。Will replace all selections with a single, empty selection at the given position. 将用一个给定位置的空选区来替换所有选区。The supported options are the same as for setSelection.受支持的optionssetSelection中的options所起的作用相同。
doc.setSelection(anchor: {line, ch}, ?head: {line, ch}, ?options: object)
Set a single selection range. 设置一个选区范围。anchor and head should be {line, ch} objects. anchorhead应该是{line, ch}对象。head defaults to anchor when not given. 如果不给定head值,它默认是anchorThese options are supported:这些选项是受支持的:
scroll: boolean
Determines whether the selection head should be scrolled into view. 确定选区头是否应该滚进视图。Defaults to true.默认为true
origin: string
Determines whether the selection history event may be merged with the previous one. 确定了选区历史记录事件是否可以与前一个合并。When an origin starts with the character +, and the last recorded selection had the same origin and was similar (close in time, both collapsed or both non-collapsed), the new one will replace the old one. 如果来源以字符+开头,而且最后记录的选区具有相同的来源,并且相似(被包进time,两者都是折叠或者两者都是展开的),则新来源将替换旧来源。When it starts with *, it will always replace the previous event (if that had the same origin). 如果它以*开头,则将替换先前的事件(如果那具有相同的来源)。Built-in motion uses the "+move" origin. 内建的运动使用"+move"来源。User input uses the "+input" origin.用户输入使用"+input"来源。
bias: number
Determine the direction into which the selection endpoints should be adjusted when they fall inside an atomic range. Can be either -1 (backward) or 1 (forward). When not given, the bias will be based on the relative position of the old selection—the editor will try to move further away from that, to prevent getting stuck.
doc.setSelections(ranges: array<{anchor, head}>, ?primary: integer, ?options: object)
Sets a new set of selections. 设置一个新选区。There must be at least one selection in the given array. 给定数组中至少存在一个选区。When primary is a number, it determines which selection is the primary one. 如果primary是一个数组,它确定了哪个选区是首要选区。When it is not given, the primary index is taken from the previous selection, or set to the last range if the previous selection had less ranges than the new one. 如果没有给定primary,首要索引取自前一个选区,或者如果前一个选区的范围小于新范围,就设置为最后的范围。Supports the same options as setSelection.运行与setSelection相同的options
doc.addSelection(anchor: {line, ch}, ?head: {line, ch})
Adds a new selection to the existing set of selections, and makes it the primary selection.把一个新选区添加到已有的选区集合,并使它成为首要选区。
doc.extendSelection(from: {line, ch}, ?to: {line, ch}, ?options: object)
Similar to setSelection, but will, if shift is held or the extending flag is set, move the head of the selection while leaving the anchor at its current place. to is optional, and can be passed to ensure a region (for example a word or paragraph) will end up selected (in addition to whatever lies between that region and the current anchor). When multiple selections are present, all but the primary selection will be dropped by this method. Supports the same options as setSelection.
doc.extendSelections(heads: array<{line, ch}>, ?options: object)
An equivalent of extendSelection that acts on all selections at once.
doc.extendSelectionsBy(f: function(range: {anchor, head}) → {line, ch}), ?options: object)
Applies the given function to all existing selections, and calls extendSelections on the result.
doc.setExtending(value: boolean)
Sets or clears the 'extending' flag, which acts similar to the shift key, in that it will cause cursor movement and calls to extendSelection to leave the selection anchor in place.
doc.getExtending() → boolean
Get the value of the 'extending' flag.取得‘extending’标记的值。
cm.hasFocus() → boolean
Tells you whether the editor currently has focus.告诉你编辑器当前是否具有焦点。
cm.findPosH(start: {line, ch}, amount: integer, unit: string, visually: boolean) → {line, ch, ?hitSide: boolean}
Used to find the target position for horizontal cursor motion. start is a {line, ch} object, amount an integer (may be negative), and unit one of the string "char", "column", or "word". Will return a position that is produced by moving amount times the distance specified by unit. When visually is true, motion in right-to-left text will be visual rather than logical. When the motion was clipped by hitting the end or start of the document, the returned value will have a hitSide property set to true.
cm.findPosV(start: {line, ch}, amount: integer, unit: string) → {line, ch, ?hitSide: boolean}
Similar to findPosH, but used for vertical motion. unit may be "line" or "page". The other arguments and the returned value have the same interpretation as they have in findPosH.
cm.findWordAt(pos: {line, ch}) → {anchor: {line, ch}, head: {line, ch}}
Returns the start and end of the 'word' (the stretch of letters, whitespace, or punctuation) at the given position.

Configuration methods配置方法

cm.setOption(option: string, value: any)
Change the configuration of the editor. 改变编辑器的配置项。option should the name of an option, and value should be a valid value for that option.option必须是一个配置项的名称,value必须是针对此配置项的有效值。
cm.getOption(option: string) → any
Retrieves the current value of the given option for this editor instance.针对此编辑器实例,检索给定配置项的当前值。
cm.addKeyMap(map: object, bottom: boolean)
Attach an additional key map to the editor. This is mostly useful for addons that need to register some key handlers without trampling on the extraKeys option. Maps added in this way have a higher precedence than the extraKeys and keyMap options, and between them, the maps added earlier have a lower precedence than those added later, unless the bottom argument was passed, in which case they end up below other key maps added with this method.
cm.removeKeyMap(map: object)
Disable a keymap added with addKeyMap. Either pass in the key map object itself, or a string, which will be compared against the name property of the active key maps.
cm.addOverlay(mode: string|object, ?options: object)
Enable a highlighting overlay. This is a stateless mini-mode that can be used to add extra highlighting. For example, the search addon uses it to highlight the term that's currently being searched. mode can be a mode spec or a mode object (an object with a token method). The options parameter is optional. If given, it should be an object, optionally containing the following options:
opaque: bool
Defaults to off, but can be given to allow the overlay styling, when not null, to override the styling of the base mode entirely, instead of the two being applied together.
priority: number
Determines the ordering in which the overlays are applied. Those with high priority are applied after those with lower priority, and able to override the opaqueness of the ones that come before. Defaults to 0.
cm.removeOverlay(mode: string|object)
Pass this the exact value passed for the mode parameter to addOverlay, or a string that corresponds to the name property of that value, to remove an overlay again.
cm.on(type: string, func: (...args))
Register an event handler for the given event type (a string) on the editor instance. There is also a CodeMirror.on(object, type, func) version that allows registering of events on any object.
cm.off(type: string, func: (...args))
Remove an event handler on the editor instance. An equivalent CodeMirror.off(object, type, func) also exists.

Document management methods文档管理方法

Each editor is associated with an instance of CodeMirror.Doc, its document. A document represents the editor content, plus a selection, an undo history, and a mode. A document can only be associated with a single editor at a time. You can create new documents by calling the CodeMirror.Doc(text: string, mode: Object, firstLineNumber: ?number, lineSeparator: ?string) constructor. The last three arguments are optional and can be used to set a mode for the document, make it start at a line number other than 0, and set a specific line separator respectively.

cm.getDoc() → Doc
Retrieve the currently active document from an editor.从编辑器中检索当前激活的文档。
doc.getEditor() → CodeMirror
Retrieve the editor associated with a document. 检索与文档相关联的编辑器。May return null.可能返回null
cm.swapDoc(doc: CodeMirror.Doc) → Doc
Attach a new document to the editor. Returns the old document, which is now no longer associated with an editor.
doc.copy(copyHistory: boolean) → Doc
Create an identical copy of the given doc. When copyHistory is true, the history will also be copied. Can not be called directly on an editor.
doc.linkedDoc(options: object) → Doc
Create a new document that's linked to the target document. Linked documents will stay in sync (changes to one are also applied to the other) until unlinked. These are the options that are supported:
sharedHist: boolean
When turned on, the linked copy will share an undo history with the original. Thus, something done in one of the two can be undone in the other, and vice versa.
from: integer
to: integer
Can be given to make the new document a subview of the original. Subviews only show a given range of lines. Note that line coordinates inside the subview will be consistent with those of the parent, so that for example a subview starting at line 10 will refer to its first line as line 10, not 0.
mode: string|object
By default, the new document inherits the mode of the parent. This option can be set to a mode spec to give it a different mode.
doc.unlinkDoc(doc: CodeMirror.Doc)
Break the link between two documents. After calling this, changes will no longer propagate between the documents, and, if they had a shared history, the history will become separate.
doc.iterLinkedDocs(function: (doc: CodeMirror.Doc, sharedHist: boolean))
Will call the given function for all documents linked to the target document. It will be passed two arguments, the linked document and a boolean indicating whether that document shares history with the target.

History-related methods历史记录相关的方法

doc.undo()
Undo one edit (if any undo events are stored).撤销一次编辑(如果已经存储了任何撤销事件)。
doc.redo()
Redo one undone edit.重做一次撤销编辑。
doc.undoSelection()
Undo one edit or selection change.撤销一次编辑或选区改变。
doc.redoSelection()
Redo one undone edit or selection change.重做一次撤销编辑或选区改变。
doc.historySize() → {undo: integer, redo: integer}
Returns an object with {undo, redo} properties, both of which hold integers, indicating the amount of stored undo and redo operations.
doc.clearHistory()
Clears the editor's undo history.清除编辑器的撤销历史记录。
doc.getHistory() → object
Get a (JSON-serializable) representation of the undo history.
doc.setHistory(history: object)
Replace the editor's undo history with the one provided, which must be a value as returned by getHistory. Note that this will have entirely undefined results if the editor content isn't also the same as it was when getHistory was called.

Text-marking methods文本标记方法

doc.markText(from: {line, ch}, to: {line, ch}, ?options: object) → TextMarker
Can be used to mark a range of text with a specific CSS class name. from and to should be {line, ch} objects. The options parameter is optional. When given, it should be an object that may contain the following configuration options:
className: string
Assigns a CSS class to the marked stretch of text.
inclusiveLeft: boolean
Determines whether text inserted on the left of the marker will end up inside or outside of it.
inclusiveRight: boolean
Like inclusiveLeft, but for the right side.
atomic: boolean
Atomic ranges act as a single unit when cursor movement is concerned—i.e. it is impossible to place the cursor inside of them. In atomic ranges, inclusiveLeft and inclusiveRight have a different meaning—they will prevent the cursor from being placed respectively directly before and directly after the range.
collapsed: boolean
Collapsed ranges do not show up in the display. Setting a range to be collapsed will automatically make it atomic.
clearOnEnter: boolean
When enabled, will cause the mark to clear itself whenever the cursor enters its range. This is mostly useful for text-replacement widgets that need to 'snap open' when the user tries to edit them. The "clear" event fired on the range handle can be used to be notified when this happens.
clearWhenEmpty: boolean
Determines whether the mark is automatically cleared when it becomes empty. Default is true.
replacedWith: Element
Use a given node to display this range. Implies both collapsed and atomic. The given DOM node must be an inline element (as opposed to a block element).
handleMouseEvents: boolean
When replacedWith is given, this determines whether the editor will capture mouse and drag events occurring in this widget. Default is false—the events will be left alone for the default browser handler, or specific handlers on the widget, to capture.
readOnly: boolean
A read-only span can, as long as it is not cleared, not be modified except by calling setValue to reset the whole document. Note: adding a read-only span currently clears the undo history of the editor, because existing undo events being partially nullified by read-only spans would corrupt the history (in the current implementation).
addToHistory: boolean
When set to true (default is false), adding this marker will create an event in the undo history that can be individually undone (clearing the marker).
startStyle: string
Can be used to specify an extra CSS class to be applied to the leftmost span that is part of the marker.
endStyle: string
Equivalent to startStyle, but for the rightmost span.
css: string
A string of CSS to be applied to the covered text. For example "color: #fe3".
attributes: object
When given, add the attributes in the given object to the elements created for the marked text. Adding class or style attributes this way is not supported.
shared: boolean
When the target document is linked to other documents, you can set shared to true to make the marker appear in all documents. By default, a marker appears only in its target document.
The method will return an object that represents the marker (with constructor CodeMirror.TextMarker), which exposes three methods: clear(), to remove the mark, find(), which returns a {from, to} object (both holding document positions), indicating the current position of the marked range, or undefined if the marker is no longer in the document, and finally changed(), which you can call if you've done something that might change the size of the marker (for example changing the content of a replacedWith node), and want to cheaply update the display.
doc.setBookmark(pos: {line, ch}, ?options: object) → TextMarker
Inserts a bookmark, a handle that follows the text around it as it is being edited, at the given position. A bookmark has two methods find() and clear(). The first returns the current position of the bookmark, if it is still in the document, and the second explicitly removes the bookmark. The options argument is optional. If given, the following properties are recognized:
widget: Element
Can be used to display a DOM node at the current location of the bookmark (analogous to the replacedWith option to markText).
insertLeft: boolean
By default, text typed when the cursor is on top of the bookmark will end up to the right of the bookmark. Set this option to true to make it go to the left instead.
shared: boolean
See the corresponding option to markText.
handleMouseEvents: boolean
As with markText, this determines whether mouse events on the widget inserted for this bookmark are handled by CodeMirror. The default is false.
doc.findMarks(from: {line, ch}, to: {line, ch}) → array<TextMarker>
Returns an array of all the bookmarks and marked ranges found between the given positions (non-inclusive).
doc.findMarksAt(pos: {line, ch}) → array<TextMarker>
Returns an array of all the bookmarks and marked ranges present at the given position.
doc.getAllMarks() → array<TextMarker>
Returns an array containing all marked ranges in the document.

Widget, gutter, and decoration methods

doc.setGutterMarker(line: integer|LineHandle, gutterID: string, value: Element) → LineHandle
Sets the gutter marker for the given gutter (identified by its CSS class, see the gutters option) to the given value. Value can be either null, to clear the marker, or a DOM element, to set it. The DOM element will be shown in the specified gutter next to the specified line.
doc.clearGutter(gutterID: string)
Remove all gutter markers in the gutter with the given ID.
doc.addLineClass(line: integer|LineHandle, where: string, class: string) → LineHandle
Set a CSS class name for the given line. line can be a number or a line handle. where determines to which element this class should be applied, can can be one of "text" (the text element, which lies in front of the selection), "background" (a background element that will be behind the selection), "gutter" (the line's gutter space), or "wrap" (the wrapper node that wraps all of the line's elements, including gutter elements). class should be the name of the class to apply.
doc.removeLineClass(line: integer|LineHandle, where: string, class: string) → LineHandle
Remove a CSS class from a line. line can be a line handle or number. where should be one of "text", "background", or "wrap" (see addLineClass). class can be left off to remove all classes for the specified node, or be a string to remove only a specific class.
doc.lineInfo(line: integer|LineHandle) → object
Returns the line number, text content, and marker status of the given line, which can be either a number or a line handle. The returned object has the structure {line, handle, text, gutterMarkers, textClass, bgClass, wrapClass, widgets}, where gutterMarkers is an object mapping gutter IDs to marker elements, and widgets is an array of line widgets attached to this line, and the various class properties refer to classes added with addLineClass.
cm.addWidget(pos: {line, ch}, node: Element, scrollIntoView: boolean)
Puts node, which should be an absolutely positioned DOM node, into the editor, positioned right below the given {line, ch} position. When scrollIntoView is true, the editor will ensure that the entire node is visible (if possible). To remove the widget again, simply use DOM methods (move it somewhere else, or call removeChild on its parent).
doc.addLineWidget(line: integer|LineHandle, node: Element, ?options: object) → LineWidget
Adds a line widget, an element shown below a line, spanning the whole of the editor's width, and moving the lines below it downwards. line should be either an integer or a line handle, and node should be a DOM node, which will be displayed below the given line. options, when given, should be an object that configures the behavior of the widget. The following options are supported (all default to false):
coverGutter: boolean
Whether the widget should cover the gutter.
noHScroll: boolean
Whether the widget should stay fixed in the face of horizontal scrolling.
above: boolean
Causes the widget to be placed above instead of below the text of the line.
handleMouseEvents: boolean
Determines whether the editor will capture mouse and drag events occurring in this widget. Default is false—the events will be left alone for the default browser handler, or specific handlers on the widget, to capture.
insertAt: integer
By default, the widget is added below other widgets for the line. This option can be used to place it at a different position (zero for the top, N to put it after the Nth other widget). Note that this only has effect once, when the widget is created.
Note that the widget node will become a descendant of nodes with CodeMirror-specific CSS classes, and those classes might in some cases affect it. This method returns an object that represents the widget placement. It'll have a line property pointing at the line handle that it is associated with, and the following methods:
clear()
Removes the widget.
changed()
Call this if you made some change to the widget's DOM node that might affect its height. It'll force CodeMirror to update the height of the line that contains the widget.

Sizing, scrolling and positioning methods改变尺寸方法、滚动方法和定位方法

cm.setSize(width: number|string, height: number|string)
Programmatically set the size of the editor (overriding the applicable CSS rules). width and height can be either numbers (interpreted as pixels) or CSS units ("100%", for example). You can pass null for either of them to indicate that that dimension should not be changed.
cm.scrollTo(x: number, y: number)
Scroll the editor to a given (pixel) position. Both arguments may be left as null or undefined to have no effect.
cm.getScrollInfo() → {left, top, width, height, clientWidth, clientHeight}
Get an {left, top, width, height, clientWidth, clientHeight} object that represents the current scroll position, the size of the scrollable area, and the size of the visible area (minus scrollbars).
cm.scrollIntoView(what: {line, ch}|{left, top, right, bottom}|{from, to}|null, ?margin: number)
Scrolls the given position into view. what may be null to scroll the cursor into view, a {line, ch} position to scroll a character into view, a {left, top, right, bottom} pixel range (in editor-local coordinates), or a range {from, to} containing either two character positions or two pixel squares. The margin parameter is optional. When given, it indicates the amount of vertical pixels around the given area that should be made visible as well.
cm.cursorCoords(where: boolean|{line, ch}, mode: string) → {left, top, bottom}
Returns an {left, top, bottom} object containing the coordinates of the cursor position. If mode is "local", they will be relative to the top-left corner of the editable document. If it is "page" or not given, they are relative to the top-left corner of the page. If mode is "window", the coordinates are relative to the top-left corner of the currently visible (scrolled) window. where can be a boolean indicating whether you want the start (true) or the end (false) of the selection, or, if a {line, ch} object is given, it specifies the precise position at which you want to measure.
cm.charCoords(pos: {line, ch}, ?mode: string) → {left, right, top, bottom}
Returns the position and dimensions of an arbitrary character. pos should be a {line, ch} object. This differs from cursorCoords in that it'll give the size of the whole character, rather than just the position that the cursor would have when it would sit at that position.
cm.coordsChar(object: {left, top}, ?mode: string) → {line, ch}
Given an {left, top} object (e.g. coordinates of a mouse event) returns the {line, ch} position that corresponds to it. The optional mode parameter determines relative to what the coordinates are interpreted. It may be "window", "page" (the default), or "local".
cm.lineAtHeight(height: number, ?mode: string) → number
Computes the line at the given pixel height. mode can be one of the same strings that coordsChar accepts.
cm.heightAtLine(line: integer|LineHandle, ?mode: string, ?includeWidgets: bool) → number
Computes the height of the top of a line, in the coordinate system specified by mode (see coordsChar), which defaults to "page". When a line below the bottom of the document is specified, the returned value is the bottom of the last line in the document. By default, the position of the actual text is returned. If `includeWidgets` is true and the line has line widgets, the position above the first line widget is returned.
cm.defaultTextHeight() → number
Returns the line height of the default font for the editor.
cm.defaultCharWidth() → number
Returns the pixel width of an 'x' in the default font for the editor. (Note that for non-monospace fonts, this is mostly useless, and even for monospace fonts, non-ascii characters might have a different width).
cm.getViewport() → {from: number, to: number}
Returns a {from, to} object indicating the start (inclusive) and end (exclusive) of the currently rendered part of the document. In big documents, when most content is scrolled out of view, CodeMirror will only render the visible part, and a margin around it. See also the viewportChange event.
cm.refresh()
If your code does something to change the size of the editor element (window resizes are already listened for), or unhides it, you should probably follow up by calling this method to ensure CodeMirror is still looking as intended. See also the autorefresh addon.

Mode, state, and token-related methods模式、状态、口令相关的方法

When writing language-aware functionality, it can often be useful to hook into the knowledge that the CodeMirror language mode has. See the section on modes for a more detailed description of how these work.

doc.getMode() → object
Gets the (outer) mode object for the editor. Note that this is distinct from getOption("mode"), which gives you the mode specification, rather than the resolved, instantiated mode object.
cm.getModeAt(pos: {line, ch}) → object
Gets the inner mode at a given position. This will return the same as getMode for simple modes, but will return an inner mode for nesting modes (such as htmlmixed).
cm.getTokenAt(pos: {line, ch}, ?precise: boolean) → object
Retrieves information about the token the current mode found before the given position (a {line, ch} object). The returned object has the following properties:
start
The character (on the given line) at which the token starts.
end
The character at which the token ends.
string
The token's string.
type
The token type the mode assigned to the token, such as "keyword" or "comment" (may also be null).
state
The mode's state at the end of this token.
If precise is true, the token will be guaranteed to be accurate based on recent edits. If false or not specified, the token will use cached state information, which will be faster but might not be accurate if edits were recently made and highlighting has not yet completed.
cm.getLineTokens(line: integer, ?precise: boolean) → array<{start, end, string, type, state}>
This is similar to getTokenAt, but collects all tokens for a given line into an array. It is much cheaper than repeatedly calling getTokenAt, which re-parses the part of the line before the token for every call.
cm.getTokenTypeAt(pos: {line, ch}) → string
This is a (much) cheaper version of getTokenAt useful for when you just need the type of the token at a given position, and no other information. Will return null for unstyled tokens, and a string, potentially containing multiple space-separated style names, otherwise.
cm.getHelpers(pos: {line, ch}, type: string) → array<helper>
Fetch the set of applicable helper values for the given position. Helpers provide a way to look up functionality appropriate for a mode. The type argument provides the helper namespace (see registerHelper), in which the values will be looked up. When the mode itself has a property that corresponds to the type, that directly determines the keys that are used to look up the helper values (it may be either a single string, or an array of strings). Failing that, the mode's helperType property and finally the mode's name are used.
For example, the JavaScript mode has a property fold containing "brace". When the brace-fold addon is loaded, that defines a helper named brace in the fold namespace. This is then used by the foldcode addon to figure out that it can use that folding function to fold JavaScript code.
When any 'global' helpers are defined for the given namespace, their predicates are called on the current mode and editor, and all those that declare they are applicable will also be added to the array that is returned.
cm.getHelper(pos: {line, ch}, type: string) → helper
Returns the first applicable helper value. See getHelpers.
cm.getStateAfter(?line: integer, ?precise: boolean) → object
Returns the mode's parser state, if any, at the end of the given line number. If no line number is given, the state at the end of the document is returned. This can be useful for storing parsing errors in the state, or getting other kinds of contextual information for a line. precise is defined as in getTokenAt().

Miscellaneous methods杂项方法

cm.operation(func: () → any) → any
CodeMirror internally buffers changes and only updates its DOM structure after it has finished performing some operation. If you need to perform a lot of operations on a CodeMirror instance, you can call this method with a function argument. It will call the function, buffering up all changes, and only doing the expensive update after the function returns. This can be a lot faster. The return value from this method will be the return value of your function.
cm.startOperation()
cm.endOperation()
In normal circumstances, use the above operation method. But if you want to buffer operations happening asynchronously, or that can't all be wrapped in a callback function, you can call startOperation to tell CodeMirror to start buffering changes, and endOperation to actually render all the updates. Be careful: if you use this API and forget to call endOperation, the editor will just never update.
cm.indentLine(line: integer, ?dir: string|integer)
Adjust the indentation of the given line. The second argument (which defaults to "smart") may be one of:
"prev"
Base indentation on the indentation of the previous line.
"smart"
Use the mode's smart indentation if available, behave like "prev" otherwise.
"add"
Increase the indentation of the line by one indent unit.
"subtract"
Reduce the indentation of the line.
<integer>
Add (positive number) or reduce (negative number) the indentation by the given amount of spaces.
cm.toggleOverwrite(?value: boolean)
Switches between overwrite and normal insert mode (when not given an argument), or sets the overwrite mode to a specific state (when given an argument).
cm.isReadOnly() → boolean
Tells you whether the editor's content can be edited by the user.
doc.lineSeparator()
Returns the preferred line separator string for this document, as per the option by the same name. When that option is null, the string "\n" is returned.
cm.execCommand(name: string)
Runs the command with the given name on the editor.
doc.posFromIndex(index: integer) → {line, ch}
Calculates and returns a {line, ch} object for a zero-based index who's value is relative to the start of the editor's text. If the index is out of range of the text then the returned object is clipped to start or end of the text respectively.
doc.indexFromPos(object: {line, ch}) → integer
The reverse of posFromIndex.
cm.focus()
Give the editor focus.
cm.phrase(text: string) → string
Allow the given string to be translated with the phrases option.
cm.getInputField() → Element
Returns the input field for the editor. Will be a textarea or an editable div, depending on the value of the inputStyle option.
cm.getWrapperElement() → Element
Returns the DOM node that represents the editor, and controls its size. Remove this from your tree to delete an editor instance.
cm.getScrollerElement() → Element
Returns the DOM node that is responsible for the scrolling of the editor.
cm.getGutterElement() → Element
Fetches the DOM node that contains the editor gutters.

Static properties静态属性

The CodeMirror object itself provides several useful properties.

CodeMirror.version: string
It contains a string that indicates the version of the library. This is a triple of integers "major.minor.patch", where patch is zero for releases, and something else (usually one) for dev snapshots.
CodeMirror.fromTextArea(textArea: TextAreaElement, ?config: object)
This method provides another way to initialize an editor. It takes a textarea DOM node as first argument and an optional configuration object as second. It will replace the textarea with a CodeMirror instance, and wire up the form of that textarea (if any) to make sure the editor contents are put into the textarea when the form is submitted. The text in the textarea will provide the content for the editor. A CodeMirror instance created this way has three additional methods:
cm.save()
Copy the content of the editor into the textarea.把编辑器的内容复制到textarea文本域
cm.toTextArea()
Remove the editor, and restore the original textarea (with the editor's current content). If you dynamically create and destroy editors made with `fromTextArea`, without destroying the form they are part of, you should make sure to call `toTextArea` to remove the editor, or its `"submit"` handler on the form will cause a memory leak.
cm.getTextArea() → TextAreaElement
Returns the textarea that the instance was based on.
CodeMirror.defaults: object
An object containing default values for all options. You can assign to its properties to modify defaults (though this won't affect editors that have already been created).
CodeMirror.defineExtension(name: string, value: any)
If you want to define extra methods in terms of the CodeMirror API, it is possible to use defineExtension. This will cause the given value (usually a method) to be added to all CodeMirror instances created from then on.
CodeMirror.defineDocExtension(name: string, value: any)
Like defineExtension, but the method will be added to the interface for Doc objects instead.
CodeMirror.defineOption(name: string, default: any, updateFunc: function)
Similarly, defineOption can be used to define new options for CodeMirror. The updateFunc will be called with the editor instance and the new value when an editor is initialized, and whenever the option is modified through setOption.
CodeMirror.defineInitHook(func: function)
If your extension just needs to run some code whenever a CodeMirror instance is initialized, use CodeMirror.defineInitHook. Give it a function as its only argument, and from then on, that function will be called (with the instance as argument) whenever a new CodeMirror instance is initialized.
CodeMirror.registerHelper(type: string, name: string, value: helper)
Registers a helper value with the given name in the given namespace (type). This is used to define functionality that may be looked up by mode. Will create (if it doesn't already exist) a property on the CodeMirror object for the given type, pointing to an object that maps names to values. I.e. after doing CodeMirror.registerHelper("hint", "foo", myFoo), the value CodeMirror.hint.foo will point to myFoo.
CodeMirror.registerGlobalHelper(type: string, name: string, predicate: fn(mode, CodeMirror), value: helper)
Acts like registerHelper, but also registers this helper as 'global', meaning that it will be included by getHelpers whenever the given predicate returns true when called with the local mode and editor.
CodeMirror.Pos(line: integer, ?ch: integer, ?sticky: string)
A constructor for the objects that are used to represent positions in editor documents. sticky defaults to null, but can be set to "before" or "after" to make the position explicitly associate with the character before or after it.
CodeMirror.changeEnd(change: object) → {line, ch}
Utility function that computes an end position from a change (an object with from, to, and text properties, as passed to various event handlers). The returned position will be the end of the changed range, after the change is applied.
CodeMirror.countColumn(line: string, index: number, tabSize: number) → number
Find the column position at a given string index using a given tabsize.

Addons

The addon directory in the distribution contains a number of reusable components that implement extra editor functionality (on top of extension functions like defineOption, defineExtension, and registerHelper). In brief, they are:

dialog/dialog.js
Provides a very simple way to query users for text input. Adds the openDialog(template, callback, options) → closeFunction method to CodeMirror instances, which can be called with an HTML fragment or a detached DOM node that provides the prompt (should include an input or button tag), and a callback function that is called when the user presses enter. It returns a function closeFunction which, if called, will close the dialog immediately. openDialog takes the following options:
closeOnEnter: bool
If true, the dialog will be closed when the user presses enter in the input. Defaults to true.
closeOnBlur: bool
Determines whether the dialog is closed when it loses focus. Defaults to true.
onKeyDown: fn(event: KeyboardEvent, value: string, close: fn()) → bool
An event handler that will be called whenever keydown fires in the dialog's input. If your callback returns true, the dialog will not do any further processing of the event.
onKeyUp: fn(event: KeyboardEvent, value: string, close: fn()) → bool
Same as onKeyDown but for the keyup event.
onInput: fn(event: InputEvent, value: string, close: fn()) → bool
Same as onKeyDown but for the input event.
onClose: fn(instance):
A callback that will be called after the dialog has been closed and removed from the DOM. No return value.

Also adds an openNotification(template, options) → closeFunction function that simply shows an HTML fragment as a notification at the top of the editor. It takes a single option: duration, the amount of time after which the notification will be automatically closed. If duration is zero, the dialog will not be closed automatically.

Depends on addon/dialog/dialog.css.

search/searchcursor.js
Adds the getSearchCursor(query, start, options) → cursor method to CodeMirror instances, which can be used to implement search/replace functionality. query can be a regular expression or a string. start provides the starting position of the search. It can be a {line, ch} object, or can be left off to default to the start of the document. options is an optional object, which can contain the property `caseFold: false` to disable case folding when matching a string, or the property `multiline: disable` to disable multi-line matching for regular expressions (which may help performance). A search cursor has the following methods:
findNext() → boolean
findPrevious() → boolean
Search forward or backward from the current position. The return value indicates whether a match was found. If matching a regular expression, the return value will be the array returned by the match method, in case you want to extract matched groups.
from() → {line, ch}
to() → {line, ch}
These are only valid when the last call to findNext or findPrevious did not return false. They will return {line, ch} objects pointing at the start and end of the match.
replace(text: string, ?origin: string)
Replaces the currently found match with the given text and adjusts the cursor position to reflect the replacement.
Implements the search commands. CodeMirror has keys bound to these by default, but will not do anything with them unless an implementation is provided. Depends on searchcursor.js, and will make use of openDialog when available to make prompting for search queries less ugly.
search/jump-to-line.js
Implements a jumpToLine command and binding Alt-G to it. Accepts linenumber, +/-linenumber, line:char, scroll% and :linenumber formats. This will make use of openDialog when available to make prompting for line number neater.
search/matchesonscrollbar.js
Adds a showMatchesOnScrollbar method to editor instances, which should be given a query (string or regular expression), optionally a case-fold flag (only applicable for strings), and optionally a class name (defaults to CodeMirror-search-match) as arguments. When called, matches of the given query will be displayed on the editor's vertical scrollbar. The method returns an object with a clear method that can be called to remove the matches. Depends on the annotatescrollbar addon, and the matchesonscrollbar.css file provides a default (transparent yellowish) definition of the CSS class applied to the matches. Note that the matches are only perfectly aligned if your scrollbar does not have buttons at the top and bottom. You can use the simplescrollbar addon to make sure of this. If this addon is loaded, the search addon will automatically use it.
edit/matchbrackets.js
Defines an option matchBrackets which, when set to true or an options object, causes matching brackets to be highlighted whenever the cursor is next to them. It also adds a method matchBrackets that forces this to happen once, and a method findMatchingBracket that can be used to run the bracket-finding algorithm that this uses internally. It takes a start position and an optional config object. By default, it will find the match to a matchable character either before or after the cursor (preferring the one before), but you can control its behavior with these options:
afterCursor
Only use the character after the start position, never the one before it.
strict
Causes only matches where both brackets are at the same side of the start position to be considered.
maxScanLines
Stop after scanning this amount of lines without a successful match. Defaults to 1000.
maxScanLineLength
Ignore lines longer than this. Defaults to 10000.
maxHighlightLineLength
Don't highlight a bracket in a line longer than this. Defaults to 1000.
edit/closebrackets.js
Defines an option autoCloseBrackets that will auto-close brackets and quotes when typed. By default, it'll auto-close ()[]{}''"", but you can pass it a string similar to that (containing pairs of matching characters), or an object with pairs and optionally explode properties to customize it. explode should be a similar string that gives the pairs of characters that, when enter is pressed between them, should have the second character also moved to its own line. By default, if the active mode has a closeBrackets property, that overrides the configuration given in the option. But you can add an override property with a truthy value to override mode-specific configuration. Demo here.
edit/matchtags.js
Defines an option matchTags that, when enabled, will cause the tags around the cursor to be highlighted (using the CodeMirror-matchingtag class). Also defines a command toMatchingTag, which you can bind a key to in order to jump to the tag matching the one under the cursor. Depends on the addon/fold/xml-fold.js addon. Demo here.
edit/trailingspace.js
Adds an option showTrailingSpace which, when enabled, adds the CSS class cm-trailingspace to stretches of whitespace at the end of lines. The demo has a nice squiggly underline style for this class.
edit/closetag.js
Defines an autoCloseTags option that will auto-close XML tags when '>' or '/' is typed, and a closeTag command that closes the nearest open tag. Depends on the fold/xml-fold.js addon. See the demo.
edit/continuelist.js
Markdown specific. Defines a "newlineAndIndentContinueMarkdownList" command that can be bound to enter to automatically insert the leading characters for continuing a list. See the Markdown mode demo.
comment/comment.js
Addon for commenting and uncommenting code. Adds four methods to CodeMirror instances:
toggleComment(?options: object)
Tries to uncomment the current selection, and if that fails, line-comments it.
lineComment(from: {line, ch}, to: {line, ch}, ?options: object)
Set the lines in the given range to be line comments. Will fall back to blockComment when no line comment style is defined for the mode.
blockComment(from: {line, ch}, to: {line, ch}, ?options: object)
Wrap the code in the given range in a block comment. Will fall back to lineComment when no block comment style is defined for the mode.
uncomment(from: {line, ch}, to: {line, ch}, ?options: object) → boolean
Try to uncomment the given range. Returns true if a comment range was found and removed, false otherwise.
The options object accepted by these methods may have the following properties:
blockCommentStart, blockCommentEnd, blockCommentLead, lineComment: string
Override the comment string properties of the mode with custom comment strings.
padding: string
A string that will be inserted after opening and leading markers, and before closing comment markers. Defaults to a single space.
commentBlankLines: boolean
Whether, when adding line comments, to also comment lines that contain only whitespace.
indent: boolean
When adding line comments and this is turned on, it will align the comment block to the current indentation of the first line of the block.
fullLines: boolean
When block commenting, this controls whether the whole lines are indented, or only the precise range that is given. Defaults to true.
The addon also defines a toggleComment command, which is a shorthand command for calling toggleComment with no options.
fold/foldcode.js
Helps with code folding. Adds a foldCode method to editor instances, which will try to do a code fold starting at the given line, or unfold the fold that is already present. The method takes as first argument the position that should be folded (may be a line number or a Pos), and as second optional argument either a range-finder function, or an options object, supporting the following properties:
rangeFinder: fn(CodeMirror, Pos)
The function that is used to find foldable ranges. If this is not directly passed, it will default to CodeMirror.fold.auto, which uses getHelpers with a "fold" type to find folding functions appropriate for the local mode. There are files in the addon/fold/ directory providing CodeMirror.fold.brace, which finds blocks in brace languages (JavaScript, C, Java, etc), CodeMirror.fold.indent, for languages where indentation determines block structure (Python, Haskell), and CodeMirror.fold.xml, for XML-style languages, and CodeMirror.fold.comment, for folding comment blocks.
widget: string|Element
The widget to show for folded ranges. Can be either a string, in which case it'll become a span with class CodeMirror-foldmarker, or a DOM node.
scanUp: boolean
When true (default is false), the addon will try to find foldable ranges on the lines above the current one if there isn't an eligible one on the given line.
minFoldSize: integer
The minimum amount of lines that a fold should span to be accepted. Defaults to 0, which also allows single-line folds.
See the demo for an example.
fold/foldgutter.js
Provides an option foldGutter, which can be used to create a gutter with markers indicating the blocks that can be folded. Create a gutter using the gutters option, giving it the class CodeMirror-foldgutter or something else if you configure the addon to use a different class, and this addon will show markers next to folded and foldable blocks, and handle clicks in this gutter. Note that CSS styles should be applied to make the gutter, and the fold markers within it, visible. A default set of CSS styles are available in: addon/fold/foldgutter.css . The option can be either set to true, or an object containing the following optional option fields:
gutter: string
The CSS class of the gutter. Defaults to "CodeMirror-foldgutter". You will have to style this yourself to give it a width (and possibly a background). See the default gutter style rules above.
indicatorOpen: string | Element
A CSS class or DOM element to be used as the marker for open, foldable blocks. Defaults to "CodeMirror-foldgutter-open".
indicatorFolded: string | Element
A CSS class or DOM element to be used as the marker for folded blocks. Defaults to "CodeMirror-foldgutter-folded".
rangeFinder: fn(CodeMirror, Pos)
The range-finder function to use when determining whether something can be folded. When not given, CodeMirror.fold.auto will be used as default.
The foldOptions editor option can be set to an object to provide an editor-wide default configuration. Demo here.
runmode/runmode.js
Can be used to run a CodeMirror mode over text without actually opening an editor instance. See the demo for an example. There are alternate versions of the file available for running stand-alone (without including all of CodeMirror) and for running under node.js (see bin/source-highlight for an example of using the latter).
runmode/colorize.js
Provides a convenient way to syntax-highlight code snippets in a webpage. Depends on the runmode addon (or its standalone variant). Provides a CodeMirror.colorize function that can be called with an array (or other array-ish collection) of DOM nodes that represent the code snippets. By default, it'll get all pre tags. Will read the data-lang attribute of these nodes to figure out their language, and syntax-color their content using the relevant CodeMirror mode (you'll have to load the scripts for the relevant modes yourself). A second argument may be provided to give a default mode, used when no language attribute is found for a node. Used in this manual to highlight example code.
mode/overlay.js
Mode combinator that can be used to extend a mode with an 'overlay' — a secondary mode is run over the stream, along with the base mode, and can color specific pieces of text without interfering with the base mode. Defines CodeMirror.overlayMode, which is used to create such a mode. See this demo for a detailed example.
mode/multiplex.js
Mode combinator that can be used to easily 'multiplex' between several modes. Defines CodeMirror.multiplexingMode which, when given as first argument a mode object, and as other arguments any number of {open, close, mode [, delimStyle, innerStyle, parseDelimiters]} objects, will return a mode object that starts parsing using the mode passed as first argument, but will switch to another mode as soon as it encounters a string that occurs in one of the open fields of the passed objects. When in a sub-mode, it will go back to the top mode again when the close string is encountered. Pass "\n" for open or close if you want to switch on a blank line.
  • When delimStyle is specified, it will be the token style returned for the delimiter tokens (as well as [delimStyle]-open on the opening token and [delimStyle]-close on the closing token).
  • When innerStyle is specified, it will be the token style added for each inner mode token.
  • When parseDelimiters is true, the content of the delimiters will also be passed to the inner mode. (And delimStyle is ignored.)
The outer mode will not see the content between the delimiters. See this demo for an example.
hint/show-hint.js
Provides a framework for showing autocompletion hints. Defines editor.showHint, which takes an optional options object, and pops up a widget that allows the user to select a completion. Finding hints is done with a hinting functions (the hint option), which is a function that take an editor instance and options object, and return a {list, from, to} object, where list is an array of strings or objects (the completions), and from and to give the start and end of the token that is being completed as {line, ch} objects. An optional selectedHint property (an integer) can be added to the completion object to control the initially selected hint.
If no hinting function is given, the addon will use CodeMirror.hint.auto, which calls getHelpers with the "hint" type to find applicable hinting functions, and tries them one by one. If that fails, it looks for a "hintWords" helper to fetch a list of completable words for the mode, and uses CodeMirror.hint.fromList to complete from those.
When completions aren't simple strings, they should be objects with the following properties:
text: string
The completion text. This is the only required property.
displayText: string
The text that should be displayed in the menu.
className: string
A CSS class name to apply to the completion's line in the menu.
render: fn(Element, self, data)
A method used to create the DOM structure for showing the completion by appending it to its first argument.
hint: fn(CodeMirror, self, data)
A method used to actually apply the completion, instead of the default behavior.
from: {line, ch}
Optional from position that will be used by pick() instead of the global one passed with the full list of completions.
to: {line, ch}
Optional to position that will be used by pick() instead of the global one passed with the full list of completions.
The plugin understands the following options, which may be either passed directly in the argument to showHint, or provided by setting an hintOptions editor option to an object (the former takes precedence). The options object will also be passed along to the hinting function, which may understand additional options.
hint: function
A hinting function, as specified above. It is possible to set the async property on a hinting function to true, in which case it will be called with arguments (cm, callback, ?options), and the completion interface will only be popped up when the hinting function calls the callback, passing it the object holding the completions. The hinting function can also return a promise, and the completion interface will only be popped when the promise resolves. By default, hinting only works when there is no selection. You can give a hinting function a supportsSelection property with a truthy value to indicate that it supports selections.
completeSingle: boolean
Determines whether, when only a single completion is available, it is completed without showing the dialog. Defaults to true.
alignWithWord: boolean
Whether the pop-up should be horizontally aligned with the start of the word (true, default), or with the cursor (false).
closeOnUnfocus: boolean
When enabled (which is the default), the pop-up will close when the editor is unfocused.
customKeys: keymap
Allows you to provide a custom key map of keys to be active when the pop-up is active. The handlers will be called with an extra argument, a handle to the completion menu, which has moveFocus(n), setFocus(n), pick(), and close() methods (see the source for details), that can be used to change the focused element, pick the current element or close the menu. Additionally menuSize() can give you access to the size of the current dropdown menu, length give you the number of available completions, and data give you full access to the completion returned by the hinting function.
extraKeys: keymap
Like customKeys above, but the bindings will be added to the set of default bindings, instead of replacing them.
The following events will be fired on the completions object during completion:
"shown" ()
Fired when the pop-up is shown.
"select" (completion, Element)
Fired when a completion is selected. Passed the completion value (string or object) and the DOM node that represents it in the menu.
"pick" (completion)
Fired when a completion is picked. Passed the completion value (string or object).
"close" ()
Fired when the completion is finished.
This addon depends on styles from addon/hint/show-hint.css. Check out the demo for an example.
hint/javascript-hint.js
Defines a simple hinting function for JavaScript (CodeMirror.hint.javascript) and CoffeeScript (CodeMirror.hint.coffeescript) code. This will simply use the JavaScript environment that the editor runs in as a source of information about objects and their properties.
hint/xml-hint.js
Defines CodeMirror.hint.xml, which produces hints for XML tagnames, attribute names, and attribute values, guided by a schemaInfo option (a property of the second argument passed to the hinting function, or the third argument passed to CodeMirror.showHint).
The schema info should be an object mapping tag names to information about these tags, with optionally a "!top" property containing a list of the names of valid top-level tags. The values of the properties should be objects with optional properties children (an array of valid child element names, omit to simply allow all tags to appear) and attrs (an object mapping attribute names to null for free-form attributes, and an array of valid values for restricted attributes). Demo here.
hint/html-hint.js
Provides schema info to the xml-hint addon for HTML documents. Defines a schema object CodeMirror.htmlSchema that you can pass to as a schemaInfo option, and a CodeMirror.hint.html hinting function that automatically calls CodeMirror.hint.xml with this schema data. See the demo.
hint/css-hint.js
A hinting function for CSS, SCSS, or LESS code. Defines CodeMirror.hint.css.
hint/anyword-hint.js
A very simple hinting function (CodeMirror.hint.anyword) that simply looks for words in the nearby code and completes to those. Takes two optional options, word, a regular expression that matches words (sequences of one or more character), and range, which defines how many lines the addon should scan when completing (defaults to 500).
hint/sql-hint.js
A simple SQL hinter. Defines CodeMirror.hint.sql. Takes two optional options, tables, a object with table names as keys and array of respective column names as values, and defaultTable, a string corresponding to a table name in tables for autocompletion.
search/match-highlighter.js
Adds a highlightSelectionMatches option that can be enabled to highlight all instances of a currently selected word. Can be set either to true or to an object containing the following options: minChars, for the minimum amount of selected characters that triggers a highlight (default 2), style, for the style to be used to highlight the matches (default "matchhighlight", which will correspond to CSS class cm-matchhighlight), trim, which controls whether whitespace is trimmed from the selection, and showToken which can be set to true or to a regexp matching the characters that make up a word. When enabled, it causes the current word to be highlighted when nothing is selected (defaults to off). Demo here.
lint/lint.js
Defines an interface component for showing linting warnings, with pluggable warning sources (see html-lint.js, json-lint.js, javascript-lint.js, coffeescript-lint.js, and css-lint.js in the same directory). Defines a lint option that can be set to an annotation source (for example CodeMirror.lint.javascript), to an options object (in which case the getAnnotations field is used as annotation source), or simply to true. When no annotation source is specified, getHelper with type "lint" is used to find an annotation function. An annotation source function should, when given a document string, an options object, and an editor instance, return an array of {message, severity, from, to} objects representing problems. When the function has an async property with a truthy value, it will be called with an additional second argument, which is a callback to pass the array to. The linting function can also return a promise, in that case the linter will only be executed when the promise resolves. By default, the linter will run (debounced) whenever the document is changed. You can pass a lintOnChange: false option to disable that. Depends on addon/lint/lint.css. A demo can be found here.
selection/mark-selection.js
Causes the selected text to be marked with the CSS class CodeMirror-selectedtext when the styleSelectedText option is enabled. Useful to change the colour of the selection (in addition to the background), like in this demo.
selection/active-line.js
Defines a styleActiveLine option that, when enabled, gives the wrapper of the line that contains the cursor the class CodeMirror-activeline, adds a background with the class CodeMirror-activeline-background, and adds the class CodeMirror-activeline-gutter to the line's gutter space is enabled. The option's value may be a boolean or an object specifying the following options:
nonEmpty: bool
Controls whether single-line selections, or just cursor selections, are styled. Defaults to false (only cursor selections).
See the demo.
selection/selection-pointer.js
Defines a selectionPointer option which you can use to control the mouse cursor appearance when hovering over the selection. It can be set to a string, like "pointer", or to true, in which case the "default" (arrow) cursor will be used. You can see a demo here.
mode/loadmode.js
Defines a CodeMirror.requireMode(modename, callback) function that will try to load a given mode and call the callback when it succeeded. You'll have to set CodeMirror.modeURL to a string that mode paths can be constructed from, for example "mode/%N/%N.js"—the %N's will be replaced with the mode name. Also defines CodeMirror.autoLoadMode(instance, mode), which will ensure the given mode is loaded and cause the given editor instance to refresh its mode when the loading succeeded. See the demo.
mode/meta.js
Provides meta-information about all the modes in the distribution in a single file. Defines CodeMirror.modeInfo, an array of objects with {name, mime, mode} properties, where name is the human-readable name, mime the MIME type, and mode the name of the mode file that defines this MIME. There are optional properties mimes, which holds an array of MIME types for modes with multiple MIMEs associated, and ext, which holds an array of file extensions associated with this mode. Four convenience functions, CodeMirror.findModeByMIME, CodeMirror.findModeByExtension, CodeMirror.findModeByFileName and CodeMirror.findModeByName are provided, which return such an object given a MIME, extension, file name or mode name string. Note that, for historical reasons, this file resides in the top-level mode directory, not under addon. Demo.
comment/continuecomment.js
Adds a continueComments option, which sets whether the editor will make the next line continue a comment when you press Enter inside a comment block. Can be set to a boolean to enable/disable this functionality. Set to a string, it will continue comments using a custom shortcut. Set to an object, it will use the key property for a custom shortcut and the boolean continueLineComment property to determine whether single-line comments should be continued (defaulting to true).
display/placeholder.js
Adds a placeholder option that can be used to make content appear in the editor when it is empty and not focused. It can hold either a string or a DOM node. Also gives the editor a CodeMirror-empty CSS class whenever it doesn't contain any text. See the demo.
display/fullscreen.js
Defines an option fullScreen that, when set to true, will make the editor full-screen (as in, taking up the whole browser window). Depends on fullscreen.css. Demo here.
display/autorefresh.js
This addon can be useful when initializing an editor in a hidden DOM node, in cases where it is difficult to call refresh when the editor becomes visible. It defines an option autoRefresh which you can set to true to ensure that, if the editor wasn't visible on initialization, it will be refreshed the first time it becomes visible. This is done by polling every 250 milliseconds (you can pass a value like {delay: 500} as the option value to configure this). Note that this addon will only refresh the editor once when it first becomes visible, and won't take care of further restyling and resizing.
scroll/simplescrollbars.js
Defines two additional scrollbar models, "simple" and "overlay" (see demo) that can be selected with the scrollbarStyle option. Depends on simplescrollbars.css, which can be further overridden to style your own scrollbars.
scroll/annotatescrollbar.js
Provides functionality for showing markers on the scrollbar to call out certain parts of the document. Adds a method annotateScrollbar to editor instances that can be called, with a CSS class name as argument, to create a set of annotations. The method returns an object whose update method can be called with a sorted array of {from: Pos, to: Pos} objects marking the ranges to be highlighted. To detach the annotations, call the object's clear method.
display/rulers.js
Adds a rulers option, which can be used to show one or more vertical rulers in the editor. The option, if defined, should be given an array of {column [, className, color, lineStyle, width]} objects or numbers (which indicate a column). The ruler will be displayed at the column indicated by the number or the column property. The className property can be used to assign a custom style to a ruler. Demo here.
display/panel.js
Defines an addPanel method for CodeMirror instances, which places a DOM node above or below an editor, and shrinks the editor to make room for the node. The method takes as first argument as DOM node, and as second an optional options object. The Panel object returned by this method has a clear method that is used to remove the panel, and a changed method that can be used to notify the addon when the size of the panel's DOM node has changed.
The method accepts the following options:
position: string
Controls the position of the newly added panel. The following values are recognized:
top (default)
Adds the panel at the very top.
after-top
Adds the panel at the bottom of the top panels.
bottom
Adds the panel at the very bottom.
before-bottom
Adds the panel at the top of the bottom panels.
before: Panel
The new panel will be added before the given panel.
after: Panel
The new panel will be added after the given panel.
replace: Panel
The new panel will replace the given panel.
stable: bool
Whether to scroll the editor to keep the text's vertical position stable, when adding a panel above it. Defaults to false.
When using the after, before or replace options, if the panel doesn't exists or has been removed, the value of the position option will be used as a fallback.
A demo of the addon is available here.
wrap/hardwrap.js
Addon to perform hard line wrapping/breaking for paragraphs of text. Adds these methods to editor instances:
wrapParagraph(?pos: {line, ch}, ?options: object)
Wraps the paragraph at the given position. If pos is not given, it defaults to the cursor position.
wrapRange(from: {line, ch}, to: {line, ch}, ?options: object)
Wraps the given range as one big paragraph.
wrapParagraphsInRange(from: {line, ch}, to: {line, ch}, ?options: object)
Wraps the paragraphs in (and overlapping with) the given range individually.
The following options are recognized:
paragraphStart, paragraphEnd: RegExp
Blank lines are always considered paragraph boundaries. These options can be used to specify a pattern that causes lines to be considered the start or end of a paragraph.
column: number
The column to wrap at. Defaults to 80.
wrapOn: RegExp
A regular expression that matches only those two-character strings that allow wrapping. By default, the addon wraps on whitespace and after dash characters.
killTrailingSpace: boolean
Whether trailing space caused by wrapping should be preserved, or deleted. Defaults to true.
A demo of the addon is available here.
merge/merge.js
Implements an interface for merging changes, using either a 2-way or a 3-way view. The CodeMirror.MergeView constructor takes arguments similar to the CodeMirror constructor, first a node to append the interface to, and then an options object. Options are passed through to the editors inside the view. These extra options are recognized:
origLeft and origRight: string
If given these provide original versions of the document, which will be shown to the left and right of the editor in non-editable CodeMirror instances. The merge interface will highlight changes between the editable document and the original(s). To create a 2-way (as opposed to 3-way) merge view, provide only one of them.
revertButtons: boolean
Determines whether buttons that allow the user to revert changes are shown. Defaults to true.
revertChunk: fn(mv: MergeView, from: CodeMirror, fromStart: Pos, fromEnd: Pos, to: CodeMirror, toStart: Pos, toEnd: Pos)
Can be used to define custom behavior when the user reverts a changed chunk.
connect: string
Sets the style used to connect changed chunks of code. By default, connectors are drawn. When this is set to "align", the smaller chunk is padded to align with the bigger chunk instead.
collapseIdentical: boolean|number
When true (default is false), stretches of unchanged text will be collapsed. When a number is given, this indicates the amount of lines to leave visible around such stretches (which defaults to 2).
allowEditingOriginals: boolean
Determines whether the original editor allows editing. Defaults to false.
showDifferences: boolean
When true (the default), changed pieces of text are highlighted.
chunkClassLocation: string|Array
By default the chunk highlights are added using addLineClass with "background". Override this to customize it to be any valid `where` parameter or an Array of valid `where` parameters.
The addon also defines commands "goNextDiff" and "goPrevDiff" to quickly jump to the next changed chunk. Demo here.
tern/tern.js
Provides integration with the Tern JavaScript analysis engine, for completion, definition finding, and minor refactoring help. See the demo for a very simple integration. For more involved scenarios, see the comments at the top of the addon and the implementation of the (multi-file) demonstration on the Tern website.

Writing CodeMirror Modes编写CodeMirror模式

Modes typically consist of a single JavaScript file. This file defines, in the simplest case, a lexer (tokenizer) for your language—a function that takes a character stream as input, advances it past a token, and returns a style for that token. More advanced modes can also handle indentation for the language.

This section describes the low-level mode interface. Many modes are written directly against this, since it offers a lot of control, but for a quick mode definition, you might want to use the simple mode addon.

The mode script should call CodeMirror.defineMode to register itself with CodeMirror. This function takes two arguments. The first should be the name of the mode, for which you should use a lowercase string, preferably one that is also the name of the files that define the mode (i.e. "xml" is defined in xml.js). The second argument should be a function that, given a CodeMirror configuration object (the thing passed to the CodeMirror function) and an optional mode configuration object (as in the mode option), returns a mode object.

Typically, you should use this second argument to defineMode as your module scope function (modes should not leak anything into the global scope!), i.e. write your whole mode inside this function.

The main responsibility of a mode script is parsing the content of the editor. Depending on the language and the amount of functionality desired, this can be done in really easy or extremely complicated ways. Some parsers can be stateless, meaning that they look at one element (token) of the code at a time, with no memory of what came before. Most, however, will need to remember something. This is done by using a state object, which is an object that is always passed when reading a token, and which can be mutated by the tokenizer.

Modes that use a state must define a startState method on their mode object. This is a function of no arguments that produces a state object to be used at the start of a document.

The most important part of a mode object is its token(stream, state) method. All modes must define this method. It should read one token from the stream it is given as an argument, optionally update its state, and return a style string, or null for tokens that do not have to be styled. For your styles, you are encouraged to use the 'standard' names defined in the themes (without the cm- prefix). If that fails, it is also possible to come up with your own and write your own CSS theme file.

A typical token string would be "variable" or "comment". Multiple styles can be returned (separated by spaces), for example "string error" for a thing that looks like a string but is invalid somehow (say, missing its closing quote). When a style is prefixed by "line-" or "line-background-", the style will be applied to the whole line, analogous to what the addLineClass method does—styling the "text" in the simple case, and the "background" element when "line-background-" is prefixed.

The stream object that's passed to token encapsulates a line of code (tokens may never span lines) and our current position in that line. It has the following API:

eol() → boolean
Returns true only if the stream is at the end of the line.
sol() → boolean
Returns true only if the stream is at the start of the line.
peek() → string
Returns the next character in the stream without advancing it. Will return a null at the end of the line.
next() → string
Returns the next character in the stream and advances it. Also returns null when no more characters are available.
eat(match: string|regexp|function(char: string) → boolean) → string
match can be a character, a regular expression, or a function that takes a character and returns a boolean. If the next character in the stream 'matches' the given argument, it is consumed and returned. Otherwise, undefined is returned.
eatWhile(match: string|regexp|function(char: string) → boolean) → boolean
Repeatedly calls eat with the given argument, until it fails. Returns true if any characters were eaten.
eatSpace() → boolean
Shortcut for eatWhile when matching white-space.
skipToEnd()
Moves the position to the end of the line.
skipTo(str: string) → boolean
Skips to the start of the next occurrence of the given string, if found on the current line (doesn't advance the stream if the string does not occur on the line). Returns true if the string was found.
match(pattern: string, ?consume: boolean, ?caseFold: boolean) → boolean
match(pattern: regexp, ?consume: boolean) → array<string>
Act like a multi-character eat—if consume is true or not given—or a look-ahead that doesn't update the stream position—if it is false. pattern can be either a string or a regular expression starting with ^. When it is a string, caseFold can be set to true to make the match case-insensitive. When successfully matching a regular expression, the returned value will be the array returned by match, in case you need to extract matched groups.
backUp(n: integer)
Backs up the stream n characters. Backing it up further than the start of the current token will cause things to break, so be careful.
column() → integer
Returns the column (taking into account tabs) at which the current token starts.
indentation() → integer
Tells you how far the current line has been indented, in spaces. Corrects for tab characters.
current() → string
Get the string between the start of the current token and the current stream position.
lookAhead(n: number) → ?string
Get the line n (>0) lines after the current one, in order to scan ahead across line boundaries. Note that you want to do this carefully, since looking far ahead will make mode state caching much less effective.
baseToken() → ?{type: ?string, size: number}
Modes added through addOverlay (and only such modes) can use this method to inspect the current token produced by the underlying mode.

By default, blank lines are simply skipped when tokenizing a document. For languages that have significant blank lines, you can define a blankLine(state) method on your mode that will get called whenever a blank line is passed over, so that it can update the parser state.

Because state object are mutated, and CodeMirror needs to keep valid versions of a state around so that it can restart a parse at any line, copies must be made of state objects. The default algorithm used is that a new state object is created, which gets all the properties of the old object. Any properties which hold arrays get a copy of these arrays (since arrays tend to be used as mutable stacks). When this is not correct, for example because a mode mutates non-array properties of its state object, a mode object should define a copyState method, which is given a state and should return a safe copy of that state.

If you want your mode to provide smart indentation (through the indentLine method and the indentAuto and newlineAndIndent commands, to which keys can be bound), you must define an indent(state, textAfter) method on your mode object.

The indentation method should inspect the given state object, and optionally the textAfter string, which contains the text on the line that is being indented, and return an integer, the amount of spaces to indent. It should usually take the indentUnit option into account. An indentation method may return CodeMirror.Pass to indicate that it could not come up with a precise indentation.

To work well with the commenting addon, a mode may define lineComment (string that starts a line comment), blockCommentStart, blockCommentEnd (strings that start and end block comments), and blockCommentLead (a string to put at the start of continued lines in a block comment). All of these are optional.

Finally, a mode may define either an electricChars or an electricInput property, which are used to automatically reindent the line when certain patterns are typed and the electricChars option is enabled. electricChars may be a string, and will trigger a reindent whenever one of the characters in that string are typed. Often, it is more appropriate to use electricInput, which should hold a regular expression, and will trigger indentation when the part of the line before the cursor matches the expression. It should usually end with a $ character, so that it only matches when the indentation-changing pattern was just typed, not when something was typed after the pattern.

So, to summarize, a mode must provide a token method, and it may provide startState, copyState, and indent methods. For an example of a trivial mode, see the diff mode, for a more involved example, see the C-like mode.

Sometimes, it is useful for modes to nest—to have one mode delegate work to another mode. An example of this kind of mode is the mixed-mode HTML mode. To implement such nesting, it is usually necessary to create mode objects and copy states yourself. To create a mode object, there are CodeMirror.getMode(options, parserConfig), where the first argument is a configuration object as passed to the mode constructor function, and the second argument is a mode specification as in the mode option. To copy a state object, call CodeMirror.copyState(mode, state), where mode is the mode that created the given state.

In a nested mode, it is recommended to add an extra method, innerMode which, given a state object, returns a {state, mode} object with the inner mode and its state for the current position. These are used by utility scripts such as the tag closer to get context information. Use the CodeMirror.innerMode helper function to, starting from a mode and a state, recursively walk down to the innermost mode and state.

To make indentation work properly in a nested parser, it is advisable to give the startState method of modes that are intended to be nested an optional argument that provides the base indentation for the block of code. The JavaScript and CSS parser do this, for example, to allow JavaScript and CSS code inside the mixed-mode HTML mode to be properly indented.

It is possible, and encouraged, to associate your mode, or a certain configuration of your mode, with a MIME type. For example, the JavaScript mode associates itself with text/javascript, and its JSON variant with application/json. To do this, call CodeMirror.defineMIME(mime, modeSpec), where modeSpec can be a string or object specifying a mode, as in the mode option.

If a mode specification wants to add some properties to the resulting mode object, typically for use with getHelpers, it may contain a modeProps property, which holds an object. This object's properties will be copied to the actual mode object.

Sometimes, it is useful to add or override mode object properties from external code. The CodeMirror.extendMode function can be used to add properties to mode objects produced for a specific mode. Its first argument is the name of the mode, its second an object that specifies the properties that should be added. This is mostly useful to add utilities that can later be looked up through getMode.

VIM Mode API

CodeMirror has a robust VIM mode that attempts to faithfully emulate VIM's most useful features. It can be enabled by including keymap/vim.js and setting the keyMap option to "vim".

Configuration配置

VIM mode accepts configuration options for customizing behavior at run time. These methods can be called at any time and will affect all existing CodeMirror instances unless specified otherwise. The methods are exposed on the CodeMirror.Vim object.

setOption(name: string, value: any, ?cm: CodeMirror, ?cfg: object)
Sets the value of a VIM option. name should be the name of an option. If cfg.scope is not set and cm is provided, then sets the global and instance values of the option. Otherwise, sets either the global or instance value of the option depending on whether cfg.scope is global or local.
getOption(name: string, ?cm: CodeMirror: ?cfg: object)
Gets the current value of a VIM option. If cfg.scope is not set and cm is provided, then gets the instance value of the option, falling back to the global value if not set. If cfg.scope is provided, then gets the global or local value without checking the other.
map(lhs: string, rhs: string, ?context: string)
Maps a key sequence to another key sequence. Implements VIM's :map command. To map ; to : in VIM would be :map ; :. That would translate to CodeMirror.Vim.map(';', ':');. The context can be normal, visual, or insert, which correspond to :nmap, :vmap, and :imap respectively.
mapCommand(keys: string, type: string, name: string, ?args: object, ?extra: object)
Maps a key sequence to a motion, operator, or action type command. The args object is passed through to the command when it is invoked by the provided key sequence. extras.context can be normal, visual, or insert, to map the key sequence only in the corresponding mode. extras.isEdit is applicable only to actions, determining whether it is recorded for replay for the . single-repeat command.

Extending VIM扩展VIM

CodeMirror's VIM mode implements a large subset of VIM's core editing functionality. But since there's always more to be desired, there is a set of APIs for extending VIM's functionality. As with the configuration API, the methods are exposed on CodeMirror.Vim and may be called at any time.

defineOption(name: string, default: any, type: string, ?aliases: array<string>, ?callback: function (?value: any, ?cm: CodeMirror) → ?any)
Defines a VIM style option and makes it available to the :set command. Type can be boolean or string, used for validation and by :set to determine which syntax to accept. If a callback is passed in, VIM does not store the value of the option itself, but instead uses the callback as a setter/getter. If the first argument to the callback is undefined, then the callback should return the value of the option. Otherwise, it should set instead. Since VIM options have global and instance values, whether a CodeMirror instance is passed in denotes whether the global or local value should be used. Consequently, it's possible for the callback to be called twice for a single setOption or getOption call. Note that right now, VIM does not support defining buffer-local options that do not have global values. If an option should not have a global value, either always ignore the cm parameter in the callback, or always pass in a cfg.scope to setOption and getOption.
defineMotion(name: string, fn: function(cm: CodeMirror, head: {line, ch}, ?motionArgs: object}) → {line, ch})
Defines a motion command for VIM. The motion should return the desired result position of the cursor. head is the current position of the cursor. It can differ from cm.getCursor('head') if VIM is in visual mode. motionArgs is the object passed into mapCommand().
defineOperator(name: string, fn: function(cm: CodeMirror, ?operatorArgs: object, ranges: array<{anchor, head}>) → ?{line, ch})
Defines an operator command, similar to defineMotion. ranges is the range of text the operator should operate on. If the cursor should be set to a certain position after the operation finishes, it can return a cursor object.
defineAction(name: string, fn: function(cm: CodeMirror, ?actionArgs: object))
Defines an action command, similar to defineMotion. Action commands can have arbitrary behavior, making them more flexible than motions and operators, at the loss of orthogonality.
defineEx(name: string, ?prefix: string, fn: function(cm: CodeMirror, ?params: object))
Defines an Ex command, and maps it to :name. If a prefix is provided, it, and any prefixed substring of the name beginning with the prefix can be used to invoke the command. If the prefix is falsy, then name is used as the prefix. params.argString contains the part of the prompted string after the command name. params.args is params.argString split by whitespace. If the command was prefixed with a line range, params.line and params.lineEnd will be set.