CodeMirror 小册子

User manual and reference guide      version 5.41.1

用户手册和参考指南

 

CodeMirror is a code-editor component that can be embedded in Web pages. The core library provides only the editor component, no accompanying buttons, auto-completion, or other IDE functionality. It does provide a rich API on top of which such functionality can be straightforwardly implemented. See the addons included in the distribution, and the list of externally hosted addons, for reusable implementations of extra features.

CodeMirror 是一个代码编辑器组件,可以嵌入到网页中。核心库只提供编辑器组件,没有伴随按钮,自动完成或其他IDE功能。它确实提供了一个丰富的API,可以直接实现这样的功能。有关额外特性的可重用实现,请参考发行版中包含的 addons, 和 外部托管附加addons的列表。

 

CodeMirror works with language-specific modes. Modes are JavaScript programs that help color (and optionally indent) text written in a given language. The distribution comes with a number of modes (see the mode/ directory), and it isn't hard to write new ones for other languages.

CodeMirror使用语言特定的模式。Modes是帮助给定语言编写的颜色(和可选的缩进)文本的javascript程序。有多种modes(查看 mode/ 目录),并且给其他语言 写一个新的 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. For example:

使用 CodeMIrror最简单的方法是简单的加载发行版本中 lib/ 目录下的脚本和样式文件,以及来自 mode/ 目录下的某一mode脚本。

 

<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:

编辑器将被插入 document body中, 没有内容并且将使用加载mode。为了对新编辑器有更多的控制,可以将配置对象作为第二个参数传递给 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). See below for a full discussion of the configuration options that CodeMirror accepts.

这将用编辑器中的一段代码初始化编辑器,并显示告诉编辑器使用javascript模式(当加载多个mode时是非常有用的)。请参考下面讨论的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. This could be used to, for example, replace a textarea with a real editor:

在不想讲编辑器附加到元素中,并且需要对插入的方式进行更多控制的情况下,CodeMirror函数的第一个参数也可以是一个函数,当给定DOM元素时,该函数会将其插入文档的某个位置。

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. See the API referencefor 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. If the variables exports and moduleexist and have type object, CommonJS-style require will be used. If not, but there is a function define with an amd property present, AMD-style (RequireJS) will be used.

CodeMIrror分布中的文件包含用在 AMD或者CommonJS环境中加载他们(以及处理他们的依赖关系)。如果变量 exports 和 module存在并且具有类型对象, 将使用CommonJS模块机制加载。如果不是,但是有一个define函数和amd属性,将使用AMD模块机制。

 

It is possible to use Browserify or similar tools to statically build modules using CodeMirror. Alternatively, use RequireJS to dynamically load dependencies at runtime. 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.

可以使用 Browserify或者类似的工具静态编译CodeMIrror模块。或者,使用 RequireJS在运行时动态加载模块。这两种方法的优点是他们不适用全局命名空间,因此可以同时加载多个版本的CodeMirror。

 

Here'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). Do not use RequireJS' paths option to configure the path to CodeMirror, since it will break loading submodules through relative paths. Use the packages configuration option instead, as in:

它将自动加载混合HTML模式依赖的模式(XML,Javascript, CSS)。不用使用RequireJS的paths选项来配置到CodeMIrror的路径,因为它会通过相对路径中断加载子模块。相反,使用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. Any option not supplied like this will be taken from CodeMirror.defaults, an object containing the default options. You can update this object to change the defaults on your page.

CodeMirror函数和fromTextArea方法都采用包含配置选项的对象作为第二个(可选)的参数。任何不提供这样的选项会默认使用CodeMirror.defaults, 一个包含默认选项的对象。你可以更新此对象以更改页面上的默认值。

 

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. 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}). 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.modesand CodeMirror.mimeModes objects. The first maps mode names to their constructors, and the second maps MIME types to mode specs.
使用模式。如果没有给出,会默认加载第一个mode。它可以是一个简单字符串命名的mode,或者是与该mode相关联的MIME类型。或者,它可以是包含配置选项的mode,具有name属性命名的mode(例如 {name: 'javascript', json: true}).每个mode的demo页面包含mode支持的配置参数的信息。你可以通过检查CodeMIrror.modes 和 CodeMirror.mimeModes 对象了解 CodeMirror定义了哪些modes和MIME类型。第一个映射 mode 命名为他们额构造函数,第二个 映射 MIME 到mode规范。
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). When a specific string is given, lines will only be split on that string, and output will, by default, use that same separator.
为编辑器显示设置行分隔符。默认情况下(值为null),文档将在 CRLFs 以及单独的CRs和LFs上被分割,并且单个LF将在所有输出中作为行分隔符(如getValue)。当给定一个特定的字符串时,行只会在该字符串上被拆分,默认情况下,输出将使用相同的分隔符。
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). The default is "default", for which colors are included in 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.
theme是编辑器的风格。你必须确保定义相应的CSS文件。.cm-s-[name] 样式加载(请查看分类中的 theme 目录)。 默认值是 'default', 颜色都在 codemirror.css中。可以同时使用多个主题类,例如 '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.
tab字符的宽度,默认是 4
indentWithTabs: boolean
Whether, when indenting, the first N*tabSize spaces should be replaced by N tabs. Default is false.
是否在缩进时,第一个 N * tabSize 空格应该被 N个tabs替换。 默认为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.
配置 当一个字符被键入可能会改变他的缩进时编辑器是否应该重新缩进当前行(只有mode支持缩进时有效)。默认 值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]/.
用于确定哪些字符应该由特殊placeholder替换的正则表达式。主要用于非打印特殊字符串(什么是非打印字符串?)。 默认是  /[\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. By default, a red dot (•) is shown, with a title tooltip to indicate the character code.
给定一个由 specialChars 选项定义的特殊字符的函数,该函数生成一个用于表示字符的DOM节点。默认情况下,显示一个红点(·),用一个标题工具提示来指示字符代码。
direction: "ltr" | "rtl"
Flips overall layout and selects base paragraph direction to be left-to-right or right-to-left. Default is "ltr". 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. 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.
翻转整体布局,选择基本段落方向,从左到右或从右到左。默认是 ‘ltr’,。CodeMirror对每行应用Unicode双向算法,但不自动检测基本方法----它被设置为所有行的编辑器方向。当基本方向与用户意图不匹配时,产生的顺序有时是错误的。(例如,前导和尾随标点跳转到错误的一边)。因此,多语种输入有助于用户切换这个选项。
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. Extra key maps are found in the key map directory. See the section on key maps for more information.
配置要使用的键映射。默认值是 ‘default’, 这是定义在codemirror.js 本身唯一的映射。额外的 键映射在 keymap目录下可以找到。在key maps章节查看更过的信息。
extraKeys: object
Can be used to specify extra key bindings for the editor, alongside the ones defined by keyMap. Should be either null, or a valid key map value.
可以为编辑器制定额外的键绑定,以及由keymap定义的键绑定。应该为null 或者有效的keymap值。
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-click时返回 rectangle(或者在ChormeOS, meta-shift-clicks), 另外返回 ‘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-click, 在其他平台上是 control-click。
moveOnDrag: bool
When the mouse even drags content around inside the editor, this controls whether it is copied (false) or moved (true). By default, this is enabled by alt-clicking on Mac OS, and ctrl-clicking elsewhere.
当鼠标甚至在编辑器内部拖动内容时,它控制是否是复制(false)还是移动(true)。默认,在Mac OS上 alt-cliciking 和在其他平台上 ctrl-clicking 启动它。
lineWrapping: boolean
Whether CodeMirror should scroll or wrap for long lines. Defaults to false (scroll).
CodeMirror是否应该滚动或者长列表。默认值为 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. Mayinclude 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). These class names are the keys passed to setGutterMarker.
可以用来增加额外的gutters(超过或代替函数gutter)。应该是一个CSS类名的数组,每个类名定义一个宽度(以及可选的背景),并将用来绘制 gutters的背景。可以包括 CodeMIrror-linenumbers 类名, 一遍显示设置行号gutter的位置(默认情况下位于所有其他gutter的右侧)。类名是传递到 setGutterMarker的 keys。
fixedGutter: boolean
Determines whether the gutter scrolls along with the content horizontally (false) or whether it stays fixed during horizontal scrolling (true, the default).
决定gutter是否与内容水平滚动(false)还是在水平滚动时保持固定(true, 默认值)
scrollbarStyle: string
Chooses a scrollbar implementation. The default is "native", showing native scrollbars. The core library also provides the "null" style, which completely hides the scrollbars. Addons can implement additional scrollbar models.
选择一个滚动条实现。默认值是 ‘active’, 显示native滚动条。核心库还提供 null 样式, 它完全隐藏滚动条。  addons 可以实现额外的滚动条模型。
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. If this option is set to true, it will be covered by an element with class CodeMirror-gutter-filler.
当fixedGutter设置, 并且有一个水平滚动的滚动条,默认情况下,该滚动条的左边显示gutter。 如果这个选项设置为true, 它将被一个带有类名为 CodeMIrror-gutter-filler 的元素所覆盖。
inputStyle: string
Selects the way CodeMirror handles input and focus. The core library defines the "textarea" and "contenteditable" input models. On mobile browsers, the default is "contenteditable". On desktop browsers, the default is "textarea". Support for IME and screen readers is better in the "contenteditable" model. The intention is to make it the default on modern desktop browsers in the future.
选择CodeMIrror控制输入和聚焦的方式。核心库定义了 ‘textarea’ 和 ‘contenteditable' 输入模型。 在手机浏览器里, 默认是 "contenteditable"。在桌面浏览器中,默认是“textarea”. 支持 "IME"和屏幕阅读器在 "contenteditable"模型中更好。其目的是是它成为未来现代桌面浏览器的默认。
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. You can set this to false to disable that behavior.
当从外部源(不是编辑器材本身)粘贴某些内容时,如果行的数量与选择的数量匹配,CodeMirror会默认的在每个选中区插入一行。你可以设置这个为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. If not given, no tab index will be assigned.
分配给编辑器的tab索引。如果没有给出,则不分配 tab索引。
autofocus: boolean
Can be used to make CodeMirror focus itself on initialization. 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.
可以是CodeMirror在初始化时获取焦点。默认为关闭。当使用 fromTextArea时,并且没有为这个选项给出显示值,那么当源文本被聚焦时,或者它具有自动聚焦属性并且没有其它元素被聚焦时,它将被设置为true。
phrases: ?object
Some addons run user-visible strings (such as labels in the interface) through the phrase method to allow for translation. 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. Otherwise, the value of the property corresponding to that string is returned.
一些插件通过 phrase方法运行用户可见的字符串(如接口中的标签)以允许translation。 此选项决定phrase方法的返回值。当它为null或者没有以输入的字符串命名的属性对象时,返回该字符串。否则返回与该字符串对应的属性的值。

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. The strings should be MIME types, and will be checked against the type of the File object as reported by the browser.
当设置(默认为null),只有文件类型在数组中才可以在编辑器中被dropped(被放入)。这个字符串应该是 MIME类型,并且将根据浏览器所报告的文件对象的类型进行检查。
cursorBlinkRate: number
Half-period in milliseconds used for cursor blinking. The default blink rate is 530ms. By setting this to zero, blinking can be disabled. A negative value hides the cursor entirely.
用于光标闪烁的半个周期(毫秒)。默认的闪烁评率是530ms。
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. 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
决定光标的高度。默认值为1,这意味着它跨域整个行的高度。对于一些字体(一些喜好)一个更小的高度(比如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 workTimemilliseconds, and then use timeout to sleep for workDelay milliseconds. The defaults are 200 and 300, you can change these options to make the highlighting more or less aggressive.
高亮是由一个伪线程后台完成的,该线程在 workTime 毫秒后开始工作,然后在 workDelay毫秒后使用超时来睡眠。默认值是 200 和 300, 你可以改变这些选项使高亮或多或少 aggressive。
pollInterval: number
Indicates how quickly CodeMirror should poll its input textarea for changes (when focused). 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. Thus, it polls. Default is 100 milliseconds.
指示CodeMirror检测输入文本的变化应该有多快(当聚焦时)。大多数输入通过事件捕获的,但是有些东西,像在一些浏览器上的 IME 输入,不会产生事件让CodeMIrro正常的检测到它。
因此,检测。默认值是100毫秒。
flattenSpans: boolean
By default, CodeMirror will combine adjacent tokens into a single span if they have the same class. This will result in a simpler DOM tree, and thus perform better. 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.
默认情况下,如果他们具有相同的class,CodeMIrror会将相邻的tokens结合为一个单独的span。这将会导致一个更简单的DOM树,并且表现得更好。通过一些样式(比如一些圆角),这回改变文档表现的方式。你可以设置这个选项为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-". For example, tokens from the XML mode will get the cm-m-xml class.
当启用(默认关闭), 一个额外的 CSS class会添加到每个token, 指示产生它的 inner mode, 前缀是“cm-m-”. 例如, XML mode 的tokens会有一个 cm-m-xml 的class。
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. You can set this to Infinity to turn off this behavior.
当高亮长行时,为了保持响应性,编辑器会放弃并简单的将行的其余部分设置为纯文本样式直到达到某个位置。默认值是10000. 你可以设置这个为 Infinitiy 来关闭这个行为。
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. Can be set to Infinity to make sure the whole document is always rendered, and thus the browser's text search works on it. This will have bad effects on performance of big documents.
指定当前滚动到视图中的文档部分上方和下方呈现的行数。这影响了滚动时所需的更新量以及这种更新所需的工作量。你应该通常不设置它,让它保持默认值 10. 可以设置为 Infinity,确保整个文档一直被渲染,因此浏览器文本搜索就可以作用在文档上。这将对大文档有不好的表现。

Events

Various CodeMirror-related objects emit events, which allow client code to react to various situations. Handlers for such events can be registered with the on and offmethods on the objects that the event fires on. To fire your own events, use CodeMirror.signal(target, name, args...), where target is a non-DOM-node object.

各种与CodeMIrror相关对象触发的事件,允许客户端代码对各种情况作出响应。此类事件的处理程序可以用事件触发的对象上的on 和 off 方法注册。要触发自己的事件,请使用 CodeMirror.signal(target, name, args....), 其中target是非 DOM节点对象。

 

 

An editor instance fires the following events. The instance argument always refers to the editor itself.

编辑器实例触发以下事件。实例参数总是引用编辑器本身。

 

 

"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. 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). text is an array of strings representing the text that replaced the changed range (split by line). removedis the text that used to be between from and to, which is overwritten by this change. This event is fired before the end of an operation, before the DOM updates happen.
编辑器内容每次更改后触发。changeObj作为第二个参数,是一个{from,to,text, removed, origin} 对象,包含发生变化的信息。from和to是变更开始和结束的位置(在变更前坐标系中)(例如,如果该位置位于#19行的开头,则可能是{ch: 0, line: 18})。 text是表示替换更改范围的文本的字符串数组(按行拆分)。removed是通过这次更改重写的 from 和to 之间的文本。在DOM更新之前发生,在operation 快要结束前触发。
"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. This event is fired after the operation finished, and display changes it makes will trigger a new operation.
像 change 事件, 但每次 operation都是批次处理, 传递一个包含operation中发生的改变的数组。此事件在每次 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 fromto, and text properties, as with the "change" event. 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. 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. Note: you may not do anything from a "beforeChange" handler that would cause changes to the document or its visualization. Doing so will, since this handler is called directly from the bowels of the CodeMirror implementation, probably cause the editor to become corrupted.
"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.
通过key map的key 被handled后触发。name是 handled key 的名称 (例如 “control-x” 或者 ’q‘), 事件是DOM  keydown或者keypress事件。
"inputRead" (instance: CodeMirror, changeObj: object)
Fired whenever new input is read from the hidden textarea (typed or pasted by the user).
每当从隐藏文本中读取新输入就会触发(由用户键入或粘贴)
"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 rangesproperty of the obj argument, and optionally change them by calling the updatemethod on this object, passing an array of ranges in the same format. The object also contains an origin property holding the origin string passed to the selection-changing method, if any. Handlers for this event have the same restriction as "beforeChange" handlers — they should not do anything to directly update the state of the editor.
"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.
每当编辑器的视窗发生变化(由于滚动,编辑,或其他因素)。from 和 to参数提供视窗新的起点和结束。
"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.
"gutterContextMenu" (instance: CodeMirror, line: integer, gutter: string, contextMenu: Event: Event)
Fires when the editor gutter (the line-number area) receives a contextmenu event. 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. You can preventDefault the event, to signal that CodeMirror should do no further handling.
"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.
"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.
"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. Fired right after the DOM element is built, before it is added to the document. 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.
每当一行被重新渲染到DOM时触发。在DOM元素被构建之后,在它被添加到文档之前启动。处理程序可能会扰乱结果元素的样式,或者添加事件处理程序,但是不应该尝试更改编辑器的状态。
"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. You can preventDefaultthe event, or give it a truthy codemirrorIgnore property, to signal that CodeMirror should do no further handling.

Document objects (instances of CodeMirror.Doc) emit the following events:

"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.
"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 startof 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.

Marked range handles (CodeMirror.TextMarker), as returned by markText and setBookmark, emit the following events:

"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. 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.
当范围被清除时,通过clearOnEnter结合光标移动 或者调用它的clear()方法时被触发。 注意,通过文本编辑删除范围不会触发此事件,因为撤销操作可能会使范围重新存在。当被清除时,from和to会给出范围spaned的一部分文档。
"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:

"redraw" ()
Fired whenever the editor re-adds the widget to the 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.
当编辑器重新将widget添加到DOM时触发。

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 EmacsVim, and Sublime Text-style keymaps.

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. Examples of names defined here are EnterF5, and Q. These can be prefixed with Shift-Cmd-Ctrl-, and Alt- to specify a modifier. So for example, Shift-Ctrl-Space would be a valid key identifier.

Common example: map the Tab key to insert spaces instead of a tab character.

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'. 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`. 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. 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. When 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. This 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. 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.

The values of properties in key maps can be either functions of a single argument (the CodeMirror instance), strings, or false. Strings refer to commands, which are described below. If the property is set to false, CodeMirror leaves handling of the key up to the browser. 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.

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). This is used to easily implement shift-selection.

Key maps can defer to each other by defining a fallthrough property. 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. Note that this only works for the top-level keymap, not for fallthrough maps or maps added with extraKeys or 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. 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.

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. 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.
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.
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.
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. 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的外观。mode提供的样式表只为该mode提供颜色,并且可以以非常简单的方式进行修改。为了编辑编辑器本身,可以改变或重写在 CodeMIrror.css中定义的样式。

 

Some care must be taken there, since a lot of the rules in this file are necessary to have CodeMirror function properly. 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:

需要注意的是,因为该文件中的许多规则都必须正确的具有CodeMIrro修改功能。当然,调整颜色应该是安全的,并且在一些关心的情况下,页可以改变很多其他的东西。此文件中定义的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.
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. 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.
CodeMirror-matchingbracketCodeMirror-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. See the files in the theme directory.

Programming API

A lot of CodeMirror features are only available through its 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. Both are zero-based. 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. If you give ch a value of null, or don't specify it, it will be replaced with the length of the specified line. Such positions may also have a stickyproperty holding "before" or "after", whether the position is associated with the character before or after it. 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. Methods prefixed with cm. are only available on CodeMirror instances.

Constructor

Constructing an editor instance is done with the CodeMirror(place: Element|fn(Element), ?option: object) constructor. If the place argument is a DOM element, the editor will be appended to it. If it is a function, it will be called, and is expected to place the editor into the document. options may be an element mapping option names to values. The options that it doesn't explicitly specify (or all options, if it is not passed) will be taken from 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.

See CodeMirror.fromTextArea for another way to construct an editor instance.

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").
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. An optional third argument can be given to indicate the line separator string to use (defaults to "\n").
在编辑器材中的给定点之间获取文本,它应该是 {line, ch}对象。可以选择一个可选的第三个参数来指示要使用的行分隔符字符串(默认 "\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. fromand to must be {line, ch} objects. to can be left off to simply insert the string at position 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.
用给定的字符串将文档的from到to的部分替换。from 和to 必须是 {line,ch}对象。to 可以省略简单地在from位置插入字符串。如果提供 origin, 它将被传递给 change 事件,并且它的第一个字母将用于决定这种改变是否可以与以前的历史事件合并,从seletion origins以描述的方式。
doc.getLine(n: integer) → string
Get the content of line 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.
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.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).
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. This is a faster way to visit a range of line handlers than calling getLineHandle for each of them. Note that line handles have a text property containing the line's content (as a string).
遍历整个文档或者start和end行号,范围从 start 到 to(不包括),并且每行通过line handle调用 f 函数处理。这是访问一系列行为处理程序的更快方法, 而不是为每个 调用 getLIneHandle方法。注意,行句柄具有包含行内容的文本属性(字符串)。
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. 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.
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. 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).
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.

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.
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.
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 selectargument works the same as in replaceSelection.
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. 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). Omitting the argument is the same as passing "head". A {line, ch}object will be returned.
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.
doc.somethingSelected() → boolean
Return true if any text is selected.
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. Will replace all selections with a single, empty selection at the given position. The supported options are the same as for setSelection.
doc.setSelection(anchor: {line, ch}, ?head: {line, ch}, ?options: object)
Set a single selection range. anchor and head should be {line, ch} objects. headdefaults to anchor when not given. These options are supported:
scroll: boolean
Determines whether the selection head should be scrolled into view. Defaults to 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. When it starts with *, it will always replace the previous event (if that had the same origin). Built-in motion uses the "+move" origin. User input uses the "+input" origin.
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. 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. Supports the same options as setSelection.
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.
将给定函数应用于所有现有的选中区,并调用结果的 extendSelection。
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.
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.
用于寻找水平光标运动的目标位置。start 是一个{line, ch}对象, amount是整数(可能是否定的), unit 是 "char", "column", "word"字符串中的一个。会返回由移动量(amount)诚意单位(unit)指定的距离所产生的位置。
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.
在给定位置返回 “word”的开头和结尾(字母,空白或标点的延伸)

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.
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:
启用高亮覆盖。这是一个无状态的迷你模式, 可以用来添加额外的高亮显示。例如,search addon 使用它来突出显示当前正在搜索的术语。mode可以是 mode spec 或者 mode对象 (具有token方法的对象)。 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 toshould be {line, ch} objects. The options parameter is optional. When given, it should be an object that may contain the following configuration options:
可用于标记具有特定CSS类名的文本范围。to和from 应该是 {line,ch}对象。options参数是可选的。在给定的情况下,它应该是一个可以包含以下配置选项的对象。
className: string
Assigns a CSS class to the marked stretch of text.
将CSS类分配给标记的文本扩展。
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, inclusiveLeftand inclusiveRight have a different meaning—they will prevent the cursor from being placed respectively directly before and directly after the range.
当光标移动时,原子范围作为单个单元,即不可能将光标放在其中。在原子范围中, inclusiveLeft 和 inclusiveRIght 具有不同的含义,它们将防止光标分别直接放在范围之前和之后。
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".
title: string
When given, will give the nodes created for this span a HTML title attribute with the given value.
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:
在给定的位置, 插入一个书签,一个句柄,在它被编辑的位置上跟着它的文本。一个bookmark有 find() 和 clear() 两个方法。如果书签仍然在文档中,则第一个返回书签当前位置, 第二个显示的删除标签。options参数是可选的,如果给定,则识别以下属性:
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. wheredetermines 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.
如果你的代码做了某些事情来改变编辑器元素的大小(已经侦听了窗口大小),或者取消隐藏它,name你可能应该通过调用此方法来跟踪以确保CodeMirror仍然如逾期的那样显示。请参考 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:
检索有关token 的信息, 即在给定位置({line, ch})之前找到前端mode。返回的对象具有如下属性:
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.
该token结束时的mode 状态。
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.
如果 precise为true, 则基于最近的编辑,token将被保证是准确的。如果未false或者没有指定,则token使用缓存状态额信息,如果最近进行了编辑并且高亮显示没有完成,则缓存状态信息将更快,但是可能不准确。
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.
这类似于getTokenAt, 但将给定的所有的token收集到一个数组中,它比重复的调用getTokenAt要便宜得多, getTokenAt在每次调用之前重新解析token之前的行的一部分。
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 foldnamespace. 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.
获取给定位置的适用辅助值集。Helpers提供了一种适合于mode的查找功能的方法。type参数提供 helper命名空间(参考 registerHelper),其中的值将被查找。当mode本身具有与type对应的属性时,该属性直接确定用于查找helper值得键(它可以是一个字符串,页可以是一个字符串数组)。如果失败, 则使用mode 的 helpType属性, 最后使用mode 的名称。
例如, javascript mode 有一个 包含 brace 的属性 fold。 当加载 brace-fold 插件时, 在 fold命名空间中定义了一个名为 brace的 helper。然后, foldcode addon  使用它来确定它可以使用折叠功能来折叠javascript代码。
在为给定的命名空间定义任何 global helper时, 在当前mode 和编辑器上调用他们的谓词,并且声明它们适用的所有谓词也将被添加到返回的数组中。
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().
如果有的话, 在给定行数的结尾返回 mode 解析器的状态。如果没有给出行号, 则返回文档末尾的状态。这可以用于存储状态中的解析错误,或者获取从其他类型的上下文信息。precise 在 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.
CodeMIrror内部缓冲区改变,并且只有在DOM结构完成一些操作后才更新它。如果需要在CodeMirror实例上执行大量操作,可以用函数参数调用此方法。它将调用函数,缓冲所有的更改,并且只有函数返回之后进行昂贵的更新。这可能要快得多。此方法的返回值将是你函数的返回值。
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.
在正常情况下,采用上述 operation方法。但是,如果你希望缓冲操作异步发生,或者这些操作不能全部包装在回调函数中,你可以调用 startOperation 来告诉 CodeMirror 开始缓冲更改,而 endOperation 则实际呈现所有更新。小心,如果你使用这个API,忘记调用endOperation, 则编辑器永远也不会更新。
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:
调整给定行的缩进。第二个参数(默认 ’smart‘)可能是以下其中一个:
"prev"
Base indentation on the indentation of the previous line.
基于上一行的缩进。
"smart"
Use the mode's smart indentation if available, behave like "prev" otherwise.
如果可用请使用该模式的只能缩进,否则表现像 prev
"add"
Increase the indentation of the line by one indent unit.
基于 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.
计算并返回一个基于0的index的{line,ch}对象,该值相对于编辑器的文本的开始。如果index超出文本范围,则将返回的对象分别剪裁到文本的开头或者结尾。
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.
允许给定的字符串与 phrases option 一起translated。
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.
返回编辑器的输入区域。将取决于inputStyle 选项的值,将是textarea或者可编辑的div。
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对象本身提供了一些有用的属性。

 

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:
这个方法提供另外一种方式来初始化一个编辑器。它接收一个textarea DOM 节点作为第一个参数,和一个可选的 配置对象作为第二个参数。它将用CodeMirror实例替换textarea,并将textarea(如果有的话)的表单连接起来,以确保在提交表单时将编辑器内容放入textarea中。
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.
删除编辑器,并恢复原始 textarea(使用编辑器的当前内容)。如果动态的创建和销毁由 fromTextArea生成的编辑器,而不销毁他们所属的表单,则应该确保调用toTextArea来删除编辑器,否则表单上的 submit处理程序将导致内存泄露。
cm.getTextArea() → TextAreaElement
Returns the textarea that the instance was based on.
返回基于实例的textarea。
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).
包含所有options的默认值得对象。你可以指定其属性来修改默认值(虽然这不会影响已经创建的编辑器)。
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 API 定义额外的方法,可以使用 defineExtension。 这将导致给定值(通常是方法)被添加到从那时起创建的所有CodeMirrror实例。
CodeMirror.defineDocExtension(name: string, value: any)
Like defineExtension, but the method will be added to the interface for Doc objects instead.
像 defineExtension,但该方法将被添加到 Doc对象的接口中。
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.
同样, defineOption可以用来为CodeMirror定义新的options。 在初始化编辑器实例时,以及通过setOptions修改选项,将通过编辑器实例和新值调用 undateFunc。
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实例初始化后运行一些代码,请使用 CodeMirror.defineInitHook。 给它一个函数作为唯一的参数,从那时起,每当初始化一个新的CodeMIrror实例时,就会调用该函数(以实例作为参数)。
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.
在给定的命名空间(type)中用给定的 name 注册一个helper值。这用于定义可以通过模式查找的功能。将为给定的type在CodeMirror对象上创建属性(如果它不存在),指向将名称映射到值得对象。例如, 通过 CodeMirror.registerHelper('hint', 'foo', myFoo), CodeMirrror.hint.foo 就会指定 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.
像 registerHelper一样,但是也将 helper 注册为 global, 这意味着当使用本地模式和编辑器调用给定 predicate返回true时,它将有 getHelpers包含。
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.
用于在编辑器文档中表示位置的对象的构造函数。sticky默认值为null, 但是也可以设置 before 或者 after 使位置明确地关联之前或之后的字符。
CodeMirror.changeEnd(change: object) → {line, ch}
Utility function that computes an end position from a change (an object with fromto, 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.
实用程序函数,用于计算更改(具有 from, to, text 属性的对象,如传递给观众事件处理程序)的结束位置。在应用更改之后,返回的位置将是更改范围的结束。
CodeMirror.countColumn(line: string, index: number, tabSize: number) → number
Find the column position at a given string index using a given tabsize.
实用给定的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 defineOptiondefineExtension, and registerHelper). In brief, they are:

发行版中的addon目录包含许多可重用的组件,这些组件实现了额外的编辑器功能(处理像defineOption,defineExtension和registerHelper这样的扩展函数之外)。简言之,它们是:

 

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+/-linenumberline:charscroll% 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 searchaddon 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.jsaddon. 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" commandthat 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.colorizefunction 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 closestring 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:
提供一个显示自动完成提示的框架。定义一个可选的选项对象editor.showHint, 并弹出一个允许用户选择完成的小部件。查找提示是通过一个提示函数(提示选项)完成的,该函数接收编辑器实例和选项对象,并返回 {list, from, to}对象,其中list是字符串或对象的数组(完成),以及from和to给出token 的开始和结束,即已经完成的{line, ch}对象。 可以将可选的 selectedHint属性(整数)添加到完成对象中,可以控制初始选择的提示。
如果没有给出任何提示函数, 该插件将使用 CodeMirror.hint.auto, 它用hint类型调用 getHelpers以查找适用的提示函数,并逐个尝试他们。如果失败了,它将寻找一个 hintWords 帮助程序来获取模式的可完成单词列表,并使用 CodeMirror.hint.fromList俩完成这些单词。
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 demofor 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.jsjson-lint.jsjavascript-lint.jscoffeescript-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-selectedtextwhen 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 modethe 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.findModeByExtensionCodeMirror.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 addonDemo.
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.cssDemo 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.
添加一个rulers选项, 它可以用来显示编辑器中的一个或多个垂直rulers。如果定义了该选项,则应该给出一个数组{column, [, className, color, lineStyle, width]} 对象或者数字(表示列)。该ruler将显示在有数字或column属性指示的列中。className属性可用于将自定义的属性赋给ruler。
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:
为CodeMirror实例定义 addPanel方法, 该方法将DOM节点置于编辑器崇上方或者下方, 并缩小编辑器为节点留出空间。该方法以DOM节点作为第一个参数, 第二个参数为可选选项对象。通过该方法返回的panel对象有一个 clear方法移除panel, 以及一个 changed方法,当panels DOM节点的大小发生变化时,该方法可用于通知 addon。
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 afterbefore 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.
在给定位置包裹段落。如果未给出pos, 则默认值为光标的位置。
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 CodeMirrorconstructor, 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 addonand the implementation of the (multi-file) demonstration on the Tern website.
posted @ 2018-11-16 16:58  她在村口等我  阅读(977)  评论(0编辑  收藏  举报