用户手册和参考说明 版本 5.35.0
CodeMirror是一个可以嵌入到网页中的代码编辑工具组件。其核心库仅仅只提供编辑器组件，没有组合按钮，没有自动完成，或者其他IDE常见的功能。 但是它提供了丰富的API，基于此其上提到的功能可以直接实现。查看分发包中包含的插件， 以及外部托管插件列表，以重复使用额外功能。
CodeMirror适用于特定于语言的模式。 模式是将给定语言编写的文本提供高亮颜色（和可选缩进）格式的JavaScript程序。
该版本带有多种模式(参见 模式/
目录), 并且也不难为其他语言编写一个新的模式
基础用法
最简单的使用CodeMirror的方式是简单的加载程序lib/
目录中的js脚本和css样式文件，
然后从mode/
目录选择一个语言模式脚本添加进来。例如：
<script src="lib/codemirror.js"></script> <link rel="stylesheet" href="lib/codemirror.css"> <script src="mode/javascript/javascript.js"></script>
(或者可选的使用一个模块加载程序。 后面将会讲到)
做完这些后，一个编辑器实例就创建好了，像这样：
var myCodeMirror = CodeMirror(document.body);
编辑器将会被附加到document body中，开始时是一个空的，并且将会按我们指定的模式去加载。
为了对这个新的编辑器工具做更多的控制，
可以将一个配置对象作为第二个参数传递给CodeMirror
:
var myCodeMirror = CodeMirror(document.body, { value: "function myScript(){return 100;}\n", mode: "javascript" });
这将会初始化编辑器中的一段代码，并且已经明确的指定它要使用JavaScript语言模式（这在多种模式混合加载时很有用） 有关CodeMirror可接受的配置选项的全面讨论，参见下文。
如果不想将编辑器附加到一个标签元素中，并且需要对插入方式有更多的控制的时候，
CodeMirror
方法的第一个参数也可以是一个函数，
当给定一个DOM元素时，将其插入到文件某处，这个可以用于例如将textarea替换为真正的编辑器。
var myCodeMirror = CodeMirror(function(elt) { myTextArea.parentNode.replaceChild(elt, myTextArea); }, {value: myTextArea.value});
但是，对于使用CodeMirror的常用方法，该库提供了一种更加强大的快捷方式：
var myCodeMirror = CodeMirror.fromTextArea(myTextArea);
除此之外，当表单提交时（如果是表单的一部分的话）将确保textarea的值随编辑器的内容更新。 参见API参考对于此方法的完整说明
模块加载
在CodeMirror发行版的文件包含用于加载在AMD或者CommonJS环境中加载它们（及其依赖关系）的垫片。
如果变量exports
、module
存在并具有类型对象，将会使用CommonJS风格。
如果没有，但是有一个函数定义
与amd
属性存在，将会使用AMD风格（RequireJS）
可以用Browserify或类似静态模块构建工具来使用CodeMirror。 或者，在运行时使用RequireJS来动态加载依赖。这两种方法都具有这样的优点， 即它们不使用全局命名空间，因此可以进行诸如将多个版本的CodeMirror加载在一起的操作。
这是一个使用RequireJS来加载CodeMirror的简单示例：
require([ "cm/lib/codemirror", "cm/mode/htmlmixed/htmlmixed" ], function(CodeMirror) { CodeMirror.fromTextArea(document.getElementById("code"), { lineNumbers: true, mode: "htmlmixed" }); });
在混合HTML模式下将会自动加载依赖的模式（XML, JavaScript, 和 CSS）。
不要使用RequireJS' paths
配置项来配置CodeMirror的路径，因为这将会通过相对路径中断加载子模块。
改用包配置选项替代，例如：
require.config({ packages: [{ name: "codemirror", location: "../path/to/codemirror", main: "lib/codemirror" }] });
配置
CodeMirror函数及其fromTextArea方法都将第二个（可选）参数作为包含配置选项的对象。 任何不这样提供的选项将从CodeMirror.defaults中获取，该对象包含默认选项。 您可以更新此对象以更改页面上的默认值。
选项不以任何方式检查，因此设置假选项值必然会导致奇数错误。
这些事支持的选项：
value(值): string|CodeMirror.Doc
- 编辑器的起始值。能够是字符串，或者document object。
mode(模式): string|object
-
使用的模式。 当没有给出时，这将默认为加载的第一个模式。
它可以是一个字符串，它可以简单地命名模式，也可以是与模式相关联的MIME类型。
或者，它可以是包含模式的配置选项的对象，其
名称
属性指定模式（例如{name：“javascript”，json：true}）。 每个模式的演示页面包含有关模式支持的配置参数的信息。您可以通过检查CodeMirror.modes
和CodeMirror.mimeModes
对象来询问CodeMirror已定义哪些模式和MIME类型。 第一个将模式名称映射到其构造函数，第二个将MIME类型映射到模式规范。 lineSeparator(行分隔符): string|null
- 明确的给编辑器设置行分隔符. 默认情况下(值为null)，文档将在CRLF以及单个CR和LF上分割，
并且单个LF将用作所有输出（如
getValue
）中的行分隔符。 当给定一个特定的字符串时，行只会在该字符串上分割，输出默认情况下使用相同的分隔符。 theme(主题): string
- 主题规定了编辑器的样式. 您必须确保加载了定义相应的.cm-s- [name]样式的CSS文件（请参阅发行版中的
theme(主题)
目录）。 默认的主题样式是"default"
，对于颜色的定义都包含在codemirror.css
中。 可以一次使用多个主题类，例如"foo bar"
会将cm-s-foo
和cm-s-bar
类分配给编辑器。 indentUnit(缩进单位): integer
- 一个区块（编辑语言中的任何意义）应该缩进多少空格。默认值是2
smartIndent(智能缩进): boolean
- 是否使用模式提供的上下文相关缩进（或者只是缩进与之前相同的行）。默认为true。
tabSize(tab键宽度): integer
- 一个tab符号的宽度。默人为4。
indentWithTabs(以tab缩进): boolean
- 当缩进时，是否应该先用N个tab替换第一个N *
tabSize
空格。默认值为false。 electricChars: boolean
- 配置编辑器是否在键入字符时-当会更改其正确缩进时-重新缩进当前行（仅当模式支持缩进时才起作用）。默认为true。
specialChars(特殊字符): RegExp
- 正则表达式用于确定哪些字符由特殊占位符替换。非常适用于非打印特殊字符。默认的是
/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\ufeff]/
. specialCharPlaceholder(特殊字符占位符): function(char) → Element
- 给定由
specialChars
选项标识的特殊字符的函数会生成一个用于表示字符的DOM节点。 默认情况下，会显示一个红点（•），标题工具提示表示字符代码。 rtlMoveVisually: boolean
- 确定通过从右到左（Arabic阿拉伯文，Hebrew希伯来文）文本的水平光标移动是可视的（按左箭头向左移动光标）还是逻辑移动（按下左箭头移动到字符串中下一个较低的索引，在从右到左的文本中）。
Windows上的默认值为
false
，在其他平台上为true
。 keyMap: string
- 配置要使用的键映射。 默认值是
"default"
，这是codemirror.js
中定义的唯一键映射。 在key map(键映射)
目录中找到额外的键映射。 有关更多信息，请参阅关键地图部分。 extraKeys(额外键): object
- 可以用来为编辑器指定额外的键绑定，以及由
keyMap
定义的键绑定。 应该为null或有效的key map(键映射)值。 configureMouse: fn(cm: CodeMirror, repeat: "single" | "double" | "triple", event: Event) → Object
- 允许您配置鼠标选择和拖动的行为。该功能在按下鼠标左键时被调用。返回的对象可能具有以下属性：
unit: "char" | "word" | "line" | "rectangle" | fn(CodeMirror, Pos) → {from: Pos, to: Pos}
- 要选择的单位。 对于自定义单位，可以是内置单位之一，也可以是需要位置并返回范围的函数。
extend: bool
- 是扩展现有的选择范围还是开始新的选择范围。
addNew: bool
- 启用后，这会为现有选择添加一个新范围，而不是替换它。
moveOnDrag: bool
- 当鼠标在编辑器内部拖动内容时，它会控制它是复制（false）还是移动（true）。
lineWrapping(是否自动换行显示): boolean
- CodeMirror是否应滚动或将较长的行换行。 默认为
false
（滚动）。 lineNumbers(是否显示行号): boolean
- 是否在编辑器左侧显示行号。
firstLineNumber: integer
- 代码行数计数初始值。默认为1。
lineNumberFormatter(行号格式化): function(line: integer) → string
- 用于格式化行号的函数。该函数传递行号，并且应返回一个字符串用以在行号区域显示。
gutters: array<string>
- 可以用来添加额外的侧边栏(超出或替代行号侧边栏)。 必须是CSS类名称的数组，每个名称都定义了一个
width(宽度)
(以及可选的背景)， 以及将用于绘制侧边栏背景。可能会包含CodeMirror-linenumbers
类， 以便明确设置行号侧边栏的位置（它将默认位于所有其他侧边工具栏的右侧）。 这些类名是传递给setGutterMarker
的键。 fixedGutter(钉住侧边栏): boolean
- 确定侧边栏是否水平滚动（false），或水平滚动期间是否保持固定（true，默认）。
scrollbarStyle(滚动条样式): string
- 选择一个滚动条实现。默认是
"native"(原生)
，显示原生滚动条。 核心库也提供了"null"
样式，这将完全隐藏滚动条。 Addons(插件)可以实现额外的滚动条模型。 coverGutterNextToScrollbar: boolean
- 当
fixedGutter
处于打开状态时，并且存在水平滚动条时，默认情况下，该滚动条的左侧将显示侧边栏。 如果此选项设置为true，则它将由具有CodeMirror-gutter-filler
类的元素覆盖。 inputStyle: string
- 选择CodeMirror处理输入和焦点的方式。 核心库定义了
"textarea"
和"contenteditable"
输入模型。 在移动浏览器上，默认值为"contenteditable"
。 在桌面浏览器上，默认是"textarea"
。 在"contenteditable"
模式中，对IME和屏幕阅读器的支持更好。目的是使其成为未来现代桌面浏览器的默认设置。 readOnly(只读): boolean|string
- 这将会禁止用户编辑编辑器的内容。如果给出特殊值
"nocursor"
(而不是简单的true
) 那么编辑器的焦点也会被禁止。 showCursorWhenSelecting(选中时显示光标): boolean
- 当处于选择模式时是否应该绘制光标。默认是false。
lineWiseCopyCut(整行复制或剪切): boolean
- 当此选项激活后，默认的，当没有选择内容时，若进行复制或剪切，将会复制或剪切光标所在位置的一整行。
pasteLinesPerSelection: boolean
- 当从外部源粘贴数据时(而不是来自编辑器本身)，如果行数与选择的数量匹配，CodeMirror将默认为每个选择插入一行。
您可以将其设置为
false
以禁用该行为 undoDepth(撤销次数): integer
- 编辑器存储的撤销级别的最大数量。请注意，这包括选择更改事件。默认为200.
historyEventDelay(保存历史延迟): integer
- 不活动时间（以毫秒为单位）将导致在键入或删除时启动新的历史记录事件。 默认为1250。
tabindex: integer
- 要分配给编辑器的tab index(选项卡索引)。 如果没有给出，则不会分配标签索引。
autofocus(自动聚焦): boolean
- 可以用来在CodeMirror初始化时就获得自身焦点。默认为关闭。
如果使用
fromTextArea
，并且此选项没有给出明确的值， 则当源textarea文本域被聚焦时，它将被设置为true，或者它具有autofocus(自动聚焦)
属性并且没有其他元素被聚焦。
下面列出了一些更专业化的低级选项。 这些仅在非常特定的情况下有用，您可能想在第一次阅读本手册时跳过它们。
dragDrop(拖放): boolean
- 控制是否启用拖放功能。 默认开启。
allowDropFileTypes(允许拖放的文件类型): array<string>
- 设置时（默认为
null(空)
），只有类型在数组中的文件才能被放入编辑器。 这些字符串应该是MIME类型，并且将根据浏览器识别的File
对象的type(类型)
进行检查。 cursorBlinkRate(光标闪烁频率): number
- 设置光标闪烁的半个周期时间（以毫秒为单位）。默认的闪烁率为530ms。 通过将其设置为零，可以禁用闪烁。 负值将完全隐藏光标。
cursorScrollMargin: number
- 当在可滚动文档中接近可见视图的顶部或底部时，总是保持光标上方和下方多少额外空间。 缺省值是0。
cursorHeight(光标高度): number
- 确定光标的高度。默认是1，以为着它跨越线条的整个高度。
对于某些字体（以及某些品味）而言，较小的高度（例如
0.85
）会导致光标无法一直到达底部，看起来更好 resetSelectionOnContextMenu(单击时重置选择): boolean
- 控制当在当前选择之外单击打开上下文菜单时，光标移至点击点。 默认为
true
。 workTime, workDelay: number
-
高亮代码显示是通过一个
workTime(工作时间)
为毫秒的伪背景线程完成的，然后使用超时为workDelay
毫秒休眠。 默认值是200和300，你可以更改这些选项以使高亮功能具有更多或更少的的工作频率。 pollInterval(定时轮询间隔): number
- 指示CodeMirror应该多快地轮询其输入textarea以进行更改（何时关注）。 大部分输入都是由事件捕获的，但某些事件（如某些浏览器上的IME输入）不会生成允许CodeMirror正确检测它的事件。 因此，它定时轮询。 默认值是100毫秒。
flattenSpans: boolean
- 默认情况下，如果CodeMirror具有相同的类，则会将相邻的令牌合并为一个内联容器。 这将得到更简单的DOM树，从而表现更好。 带着某些样式（如圆角），这将改变文档的外观。 您可以将此选项设置为false以禁用此行为。
addModeClass: boolean
- 如果启用（默认为关闭），则会为每个标记添加一个额外的CSS类，指示生成它的(inner(内部))模式，以
"cm-m-"
为前缀。 例如，来自XML模式的标记将获得cm-m-xml
类。 maxHighlightLength(最长高亮字符个数): number
- 当高亮显示较长的行时，为了保持响应，编辑器将放弃高亮，并在其到达某个位置时简单地将该行的其余部分设置为纯文本。
默认值是10 000.您可以将其设置为
Infinity(无限)
以关闭此行为。 viewportMargin: integer
- 指定当前滚动到视图中的文档部分上方和下方呈现的行数。 这会影响滚动时所需的更新量以及此类更新所做的工作量。您通常应该将其保留为默认值10。
可以将其设置为
Infinity(无限)
，以确保始终呈现整个文档，从而使浏览器的文本搜索功能可以正常工作。这会对大文档的性能造成不良影响。
Events(事件)
各种与CodeMirror相关的对象发出事件，这些事件允许客户端代码响应各种情况。
这些事件的处理程序可以通过事件触发对象的on
和off
方法进行注册。
要触发自己的事件，请使用CodeMirror.signal(target, name, args...)
，其中target
是非DOM节点对象。
每个编辑器实例都会触发以下事件。instance(实例)
参数总是指编辑器本身。
"change" (instance: CodeMirror, changeObj: object)
- 每当编辑器的内容发生改变时触发此事件。
changeObj
是一个{from, to, text, removed, origin}
对象，其中包含发生的更改的有关信息，来作为第二个参数。from
和to
是变化开始和结束(例如，如果位置在第#16行行首处的位置，它将会是{ch:0, line:18}
)的位置(在变化前的坐标系统中)。text
是一个字符串数组，代表替换已更改范围的文本（按行分割）。removed
是变化之前介于from
和to
之间的文本，这些文本被此更改覆盖。 在DOM更新发生之前，此事件会在operation(操作)结束之前触发。 "changes" (instance: CodeMirror, changes: array<object>)
- 类似于
"change"
事件，但是每个operation(操作)都进行批量处理，传递在操作中发生的所有更改的数组。 此事件在操作完成之后，并且显示的更改会触发新的操作。 "beforeChange" (instance: CodeMirror, changeObj: object)
- 事件在更改被应用之前触发，其处理程序可能会选择修改或取消更改。
changeObj
对象包含from
,to
, 和text
属性，就像"change"
事件一样。 它还有一个cancel()
方法，可以调用该方法来取消更改，如果更改不是来自撤消或重做事件，还可以使用update(from, to, text)
方法，该方法可用于修改更改。 撤销和重做更改不能被修改，因为它们包含一些元信息，用于恢复仅对特定更改有效的旧标记范围。 所有要update
的三个参数都是可选的，并且可以保持不变以保持该字段的现有值不变。 注意：你不能执行任何可能导致文档或其可视化更改的"beforeChange"
处理程序。 如果这样做了，因为这个处理程序直接从CodeMirror实现的底层调用，则可能会导致编辑器损坏。 "cursorActivity" (instance: CodeMirror)
- 当光标在改变选择内容，或在编辑器内容发生任何更改时，会出发此事件。
"keyHandled" (instance: CodeMirror, name: string, event: Event)
- 通过密钥映射处理密钥后触发。
name
是所处理的键的名称（例如"Ctrl-X"
或"'q'"
），事件
是DOMkeydown
或keypress
事件。 "inputRead" (instance: CodeMirror, changeObj: object)
- 每当从隐藏的textarea中读取新输入（由用户键入或粘贴）时触发。
"electricInput" (instance: CodeMirror, line: integer)
- 如果文本输入与模式的electric模式相匹配，这会导致线条的缩进改变。
"beforeSelectionChange"(改变选区之前) (instance: CodeMirror, obj: {ranges, origin, update})
- 此事件在选择移动之前被触发。它的处理程序可以检查一组选择范围，在obj参数的
ranges
属性中以{anchor, head}
对象的数组形式出现， 并且可以通过调用此对象的update
方法来更改它们，在该对象中传递一个范围数组相同的格式。 该对象还包含一个origin
属性，用于保存传递给选择更改方法的原始字符串（如果有）。 此事件的处理程序与"beforeChange"
处理程序具有相同的限制 - 它们不应该直接更新编辑器的状态。 "viewportChange"(可视区域改变) (instance: CodeMirror, from: number, to: number)
- 每当编辑器可视区域发生变化（由于滚动，编辑或任何其他因素）时触发。
from
和to
参数赋予可视区域新的开始和结束。 "swapDoc" (instance: CodeMirror, oldDoc: Doc)
- 当使用
swapDoc
方法替换编辑器的文档时，就会触发该信号。 "gutterClick" (instance: CodeMirror, line: integer, gutter: string, clickEvent: Event)
- 当单击编辑器工具栏（行号区域）时触发。将会传递以编辑器实例作为第一个参数，单击的行号(从0开始)作为第二个参数，单击的工具栏的CSS类作为第三个参数，
以及原始的
mousedown
事件对象作为第四个参数的四个参数。 "gutterContextMenu" (instance: CodeMirror, line: integer, gutter: string, contextMenu: Event: Event)
- 当编辑器工具栏（行号区域）接收到
contextmenu
事件时触发。 将会传递以编辑器实例作为第一个参数，单击的行号(从0开始)作为第二个参数，单击的工具栏的CSS类作为第三个参数， 以及原始的contextmenu
鼠标事件对象作为第四个参数的四个参数。 你可以preventDefault(阻止默认)
事件，来表示codeMirror将不会做进一步处理。 "focus" (instance: CodeMirror, event: Event)
- 当编辑器被聚焦时触发。
"blur" (instance: CodeMirror, event: Event)
- 当编辑器失去焦点时触发。
"scroll" (instance: CodeMirror)
- 当编辑器滚动时触发。
"refresh" (instance: CodeMirror)
- 当编辑器被refreshed(刷新)或者resized(调整大小)时触发。 当使依赖于编辑器或字符大小的缓存值失效时很有用。
"optionChange" (instance: CodeMirror, option: string)
- 每次使用
setOption
更改选项时触发。 "scrollCursorIntoView" (instance: CodeMirror, event: Event)
- 当编辑器尝试将其光标滚动到视图时触发。可以连接到编辑器周围的其他可滚动容器。
当事件对象调用了
preventDefault
方法时，CodeMirror本身不会尝试滚动窗口。 "update" (instance: CodeMirror)
- 每当CodeMirror更新了其DOM展示时触发。
"renderLine" (instance: CodeMirror, line: LineHandle, element: Element)
- 每当一条线（重新）呈现给DOM时触发。在添加到文档之前，在构建DOM元素之后立即触发。 该处理程序可能会混淆结果元素的样式，或添加事件处理程序，但不应尝试更改编辑器的状态。
"mousedown", "dblclick", "touchstart", "contextmenu", "keydown", "keypress", "keyup", "cut", "copy", "paste", "dragstart", "dragenter", "dragover", "dragleave", "drop" (instance: CodeMirror, event: Event)
- CodeMirror处理此类型的DOM事件时触发。
您可以
preventDefault(阻止默认)
事件，或为其指定一个真实的codemirrorIgnore
属性，以指示CodeMirror应该不做进一步处理。
文档对象（CodeMirror.Doc
的实例）产生以下事件：
"change" (doc: CodeMirror.Doc, changeObj: object)
- 每当文档发生变更时触发。
changeObj
与传递给编辑器的"change"
事件的对象具有类似的类型。 "beforeChange" (doc: CodeMirror.Doc, change: object)
- 请参阅编辑器实例上相同事件的描述。
"cursorActivity" (doc: CodeMirror.Doc)
- 本文档中的光标或选择发生更改时触发。
"beforeSelectionChange" (doc: CodeMirror.Doc, selection: {head, anchor})
- 相当于在编辑器实例上触发的同名事件。
行处理（如由getLineHandle
返回）支持这些事件：
"delete" ()
- 行对象被删除时将被触发。一个行对象与行的起始位置相关联。 当你需要查明给定的某行上的gutter markers(工具栏标记)何时被移除是非常有用。
"change" (line: LineHandle, changeObj: object)
- 以任何方式
更改
行的文本内容时触发（但不是该行完全删除的情况）。change(更改)
对象与传递给编辑器对象上的change event(更改事件)的对象类似。
由markText
和setBookmark
返回的标记范围句柄（CodeMirror.TextMarker
）产生以下事件：
"beforeCursorEnter" ()
- 光标进入标记范围时触发。 在此事件处理程序中，编辑器状态可能会被检查但不会被修改，除了事件触发的范围可能会被清除。
"clear" (from: {line, ch}, to: {line, ch})
- 通过光标移动与
clearOnEnter
组合或通过调用clear()
方法清除范围时触发。 每次操作只能触发一次。请注意，通过文本编辑删除范围不会触发此事件，因为撤消操作可能会使范围恢复生效。from
和to
给出被清除的有限范围的文档的一部分。 "hide" ()
- 通过编辑操作将标记的最后部分从文档中移除时触发。
"unhide" ()
- 在通过编辑删除标记之后，撤消操作将标记返回。
由addLineWidget
返回的行部件(CodeMirror.LineWidget
)将触发这些事件：
"redraw" ()
- 编辑器重新将小部件添加到DOM时触发。 这会在添加窗口小部件后立即发生（如果它被滚动到视图中）， 然后当窗口滚动出视图并再次返回时，或者当编辑器选项或窗口小部件所在行需要要重画的小部件。
Key Maps(按键映射)
键映射是将键和鼠标按钮与功能相关联的方式。键映射是一个映射字符串的对象，将字符串标识为实现其功能的函数。
CodeMirror发行版附带Emacs，Vim和Sublime Text-style键盘映射。
按键由名称或字符标识。CodeMirror.keyNames
对象定义了公共按键的名称，并将它们与其关键代码关联起来。
这里定义的名字的例子是Enter
，F5
和Q
。
这些可以用Shift-
，Cmd-
，Ctrl-
和Alt-
作为前缀来指定一个修饰符。
因此，例如，Shift-Ctrl-Space将是一个有效的按键标识符。
常见示例：映射Tab键以插入空格而不是制表符。
editor.setOption("extraKeys", { Tab: function(cm) { var spaces = Array(cm.getOption("indentUnit") + 1).join(" "); cm.replaceSelection(spaces); } });
或者，可以通过用单引号括起来直接指定字符，例如'$'
或'q'
。
由于浏览器触发按键事件的方式受到限制，因此这些事件可能不会以修饰符作为前缀。
要绑定鼠标按钮，请使用名称`LeftClick`，`MiddleClick`和`RightClick`。 这些也可以用修饰符作为前缀，另外，单词`Double`或`Triple`可以放在Click之前（如`LeftDoubleClick`）来绑定双击或三击。 这种绑定的函数传递了被点击的位置作为第二个参数。
多键绑定可以通过在属性名称中用空格分隔键名来指定，例如Ctrl-X Ctrl-V
。
当映射包含多键绑定或具有未按默认顺序（Shift-Cmd-Ctrl-Alt
）指定的修饰符的键时，
必须先调用CodeMirror.normalizeKeyMap才能使用它。
该函数使用键映射并修改它以使修饰符顺序标准化并正确识别多键绑定。它将返回键映射本身。
CodeMirror.keyMap
对象将键映射与名称关联。用户代码和键映射定义可以为此对象分配额外的属性。
在预期有键映射的任何地方，都可以给出一个字符串，这个字符将在这个对象中查找。
它还包含保存默认绑定的"default"
键映射。
键映射中的属性值可以是单个参数（CodeMirror实例）的函数，字符串或false
。
字符串指的是下面描述的commands(命令)。如果该属性设置为false
，则CodeMirror将离开对浏览器的处理。
快捷键处理函数可能会返回CodeMirror.Pass
来表明它已决定不处理该快捷键，并且应转交给其他处理程序（或默认行为）。
映射到以字符"go"
开头的命令名或具有真实motion(运动)
属性（应该用于光标移动操作）的函数的键，
即使在存在额外的Shift
修饰符时也会被触发（即"Up":"goLineUp"
同时与up和shift-up相匹配）。这用于轻松实现shift辅助选择。
通过定义fallthrough
属性，关键按键映射可以相互推迟。
这表明当在映射本身中没有找到对应按键时，应该搜索一个或多个其他映射。它可以保存单个键映射或一系列键映射。
当键映射变为活动状态时需要设置某些东西时，或者在停用时删除某些东西，
它可以包含attach(附加)
属性和/或detach(分离)
属性，
这些属性应该包含采用编辑器实例和下一个或上一个键映射的函数。
请注意，这仅适用于top-level keymap(顶级键盘映射)，
而不适用于使用extraKeys
或addKeyMap
添加的贯穿式映射或映射。
Commands(操作命令)
命令是可以在编辑器上执行的无参数操作。它们的主要用途是用于按键绑定。通过向CodeMirror.commands
对象添加属性来定义命令。
库本身定义了许多常用命令，其中大多数命令由默认的键绑定使用。命令属性的值必须是一个参数（编辑器实例）的函数。
下面的一些命令在默认的键盘映射中被引用，但是没有被核心库定义。这些旨在由用户代码或插件定义。
命令也可以使用execCommand
方法运行。
selectAll
Ctrl-A (PC), Cmd-A (Mac)- 选择编辑器的全部内容。
singleSelection
Esc- 当存在多个选择时，这将取消选择除主要选择以外的所有选择。
killLine
Ctrl-K (Mac)- Emacs式的killLine。删除光标后面的部分。如果只包含空格，则行尾的换行符也会被删除。
deleteLine
Ctrl-D (PC), Cmd-D (Mac)- 删除光标下的整行，包括最后的换行符。
delLineLeft
- 删除光标前面的那一行。
delWrappedLineLeft
Cmd-Backspace (Mac)- 从光标所在视线的左侧删除光标所在行的部分。
delWrappedLineRight
Cmd-Delete (Mac)- 从光标所在视线的右侧删除光标所在行的部分。
undo
Ctrl-Z (PC), Cmd-Z (Mac)- 撤销上次更改。撤消上次更改。 请注意，由于浏览器仍不能使脚本对上下文菜单作出反应或自定义上下文菜单， 因此在CodeMirror实例的上下文菜单中选择撤销（或重做）不起作用。
redo
Ctrl-Y (PC), Shift-Cmd-Z (Mac), Cmd-Y (Mac)- 重做上次撤销的更改。
undoSelection
Ctrl-U (PC), Cmd-U (Mac)- 撤消对选定内容的最后一次更改，或者如果仅选定内容没有更改历史，则撤消最后一次更改。
redoSelection
Alt-U (PC), Shift-Cmd-U (Mac)- 重做对所选内容的最后一次更改，如果选定内容没有之前的更改，则重做最后一次文本更改。
goDocStart
Ctrl-Home (PC), Cmd-Up (Mac), Cmd-Home (Mac)- 将光标移动到文档的起始位置。
goDocEnd
Ctrl-End (PC), Cmd-End (Mac), Cmd-Down (Mac)- 将光标移动到文档的末尾位置。
goLineStart
Alt-Left (PC), Ctrl-A (Mac)- 将光标移动到行的起始位置。
goLineStartSmart
Home- 移动到行中文本的开头，或者如果光标已经在此处，则移动到行的实际开头(包括空白)。
goLineEnd
Alt-Right (PC), Ctrl-E (Mac)- 将光标移动到行的末尾位置。
goLineRight
Cmd-Right (Mac)- 将光标移动到其所在的可视线的右侧。
goLineLeft
Cmd-Left (Mac)- 将光标移动到其所在的可视线的左侧。如果此行已换行，则可能不是行的开头。
goLineLeftSmart
- 将光标移至其所在视觉线的左侧。如果已经在行的起始位置，将表现得像
goLineStartSmart
一样的行为。 goLineUp
Up, Ctrl-P (Mac)- 将光标向上移动一行。
goLineDown
Down, Ctrl-N (Mac)- 将光标向下移动一行。
goPageUp
PageUp, Shift-Ctrl-V (Mac)- 将光标向上移动一个屏幕，并向上滚动相同的距离。
goPageDown
PageDown, Ctrl-V (Mac)- 将光标向下移动一个屏幕，并向下滚动相同的距离。
goCharLeft
Left, Ctrl-B (Mac)- 将光标向左移动一个字符，到达行首时移至上一行。
goCharRight
Right, Ctrl-F (Mac)- 将光标向右移动一个字符，到达行首时移至下一行。
goColumnLeft
- 将光标向左移动一个字符，但不要越过线边界。
goColumnRight
- 将光标向右移动一个字符，但不要越过线边界。
goWordLeft
Alt-B (Mac)- 将光标移到上一个单词的开头。
goWordRight
Alt-F (Mac)- 将光标移到下一个单词的末尾。
goGroupLeft
Ctrl-Left (PC), Alt-Left (Mac)- 移动到光标之前的群组左侧。组是一段文字字符、一段标点字符、一行换行符或一段以上空白字符。
goGroupRight
Ctrl-Right (PC), Alt-Right (Mac)- 移动到光标后的群组右侧。(见 上文).
delCharBefore
Shift-Backspace, Ctrl-H (Mac)- 删除光标前的字符。
delCharAfter
Delete, Ctrl-D (Mac)- 删除光标后的字符。
delWordBefore
Alt-Backspace (Mac)- 删除至光标前的单词开头。
delWordAfter
Alt-D (Mac)- 删除至光标后的单词末尾。
delGroupBefore
Ctrl-Backspace (PC), Alt-Backspace (Mac)- 删除光标前组左侧的。
delGroupAfter
Ctrl-Delete (PC), Ctrl-Alt-Backspace (Mac), Alt-Delete (Mac)- 删除至光标后组的开始。
indentAuto
Shift-Tab- 自动缩进当前行或选定内容。
indentMore
Ctrl-] (PC), Cmd-] (Mac)- 按一个缩进单位缩进当前行或选定内容。
indentLess
Ctrl-[ (PC), Cmd-[ (Mac)- 按一个缩进单位对当前行或选定内容取消缩进。
insertTab
- 在光标处插入制表符。
insertSoftTab
- 在光标处插入与制表符宽度匹配的若干空白字符。
defaultTab
Tab- 如果选择了某个对象，将其缩进一个缩进单位。如果未选择任何内容，则插入制表符。
transposeChars
Ctrl-T (Mac)- 交换光标前后的字符。
newlineAndIndent
Enter- 插入换行符并自动缩进新行。
toggleOverwrite
Insert- 翻转overwrite覆写标志。
save
Ctrl-S (PC), Cmd-S (Mac)- 未由核心库定义，仅在键映射中引用。旨在为用户代码定义save命令提供一种简单的方法。
find
Ctrl-F (PC), Cmd-F (Mac)findNext
Ctrl-G (PC), Cmd-G (Mac)findPrev
Shift-Ctrl-G (PC), Shift-Cmd-G (Mac)replace
Shift-Ctrl-F (PC), Cmd-Alt-F (Mac)replaceAll
Shift-Ctrl-R (PC), Shift-Cmd-Alt-F (Mac)- 不是由核心库定义的，而是在搜索插件(或自定义客户端插件)中定义的。
Customized Styling(自定义样式)
在一定程度上，可以通过修改样式表文件来更改CodeMirror的外观。
由模式提供的样式表仅提供该模式的颜色，并且可以以非常直接的方式进行调整。
要设置编辑器本身的样式，可以更改或覆盖在codemirror.css
中定义的样式。
必须注意这一点，因为该文件中的许多规则对于代码镜像正常运行是必要的。 当然，调整颜色应该是安全的，而且如果小心一点，很多其他的东西也可以改变。 此文件中定义的CSS类提供以下角色:
CodeMirror
- 编辑器的外部元素。这应该用于编辑器的宽度、高度、边框和定位。也可用于设置编辑器内所有内容的样式(如字体和字号)，或设置背景。
将此类的高度样式设置为auto将使编辑器调整大小以适合其内容(建议在执行此操作时也将viewportMargin选项设置为Infinity )。 Setting
this class'
height
style toauto
will make the editor resize to fit its content (it is recommended to also set theviewportMargin
option toInfinity
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-matchingbracket
,CodeMirror-nonmatchingbracket
- These are used to style matched (or unmatched) brackets.
If your page's style sheets do funky things to
all div
or pre
elements (you probably
shouldn't do that), you'll have to define rules to cancel these
effects out again for elements under the CodeMirror
class.
Themes are also simply CSS files, which define colors for
various syntactic elements. See the files in
the theme
directory.
Programming API(编程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 sticky
property
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"
). doc.replaceRange(replacement: string, from: {line, ch}, to: {line, ch}, ?origin: string)
- Replace the part of the document between
from
andto
with the given string.from
andto
must be{line, ch}
objects.to
can be left off to simply insert the string at positionfrom
. Whenorigin
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. 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 first line of 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 last line of 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
andend
line numbers are given, the range fromstart
up to (not including)end
, and callf
for each line, passing the line handle. This is a faster way to visit a range of line handlers than callinggetLineHandle
for each of them. Note that line handles have atext
property containing the line's content (as a string). 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. IfcloseEvent
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 tochangeGeneration
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
select
argument works the same as inreplaceSelection
. 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
andhead
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 forsetSelection
. doc.setSelection(anchor: {line, ch}, ?head: {line, ch}, ?options: object)
- Set a single selection range.
anchor
andhead
should be{line, ch}
objects.head
defaults toanchor
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 assetSelection
. 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 assetSelection
. doc.extendSelections(heads: array<{line, ch}>, ?options: object)
- An equivalent
of
extendSelection
that acts on all selections at once. doc.extendSelectionsBy(f: function(range: {anchor, head}) → {line, ch}), ?options: object)
- Applies the given function to all existing selections, and
calls
extendSelections
on the result. doc.setExtending(value: boolean)
- Sets or clears the 'extending' flag, which acts similar to
the shift key, in that it will cause cursor movement and calls
to
extendSelection
to leave the selection anchor in place. doc.getExtending() → boolean
- Get the value of the 'extending' flag.
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), andunit
one of the string"char"
,"column"
, or"word"
. Will return a position that is produced by movingamount
times the distance specified byunit
. Whenvisually
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 ahitSide
property set to true. cm.findPosV(start: {line, ch}, amount: integer, unit: string) → {line, ch, ?hitSide: boolean}
- Similar to
findPosH
, but used for vertical motion.unit
may be"line"
or"page"
. The other arguments and the returned value have the same interpretation as they have infindPosH
. cm.findWordAt(pos: {line, ch}) → {anchor: {line, ch}, head: {line, ch}}
- Returns the start and end of the 'word' (the stretch of letters, whitespace, or punctuation) at the given position.
Configuration methods
cm.setOption(option: string, value: any)
- Change the configuration of the editor.
option
should the name of an option, andvalue
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 theextraKeys
andkeyMap
options, and between them, the maps added earlier have a lower precedence than those added later, unless thebottom
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 thename
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 atoken
method). Theoptions
parameter is optional. If given, it should be an object, optionally containing the following options:opaque: bool
- Defaults to off, but can be given to allow the overlay
styling, when not
null
, to override the styling of the base mode entirely, instead of the two being applied together. priority: number
- Determines the ordering in which the overlays are applied. Those with high priority are applied after those with lower priority, and able to override the opaqueness of the ones that come before. Defaults to 0.
cm.removeOverlay(mode: string|object)
- Pass this the exact value passed for the
mode
parameter toaddOverlay
, or a string that corresponds to thename
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
. 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:
- 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 whengetHistory
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
andto
should be{line, ch}
objects. Theoptions
parameter is optional. When given, it should be an object that may contain the following configuration options:className: string
- Assigns a CSS class to the marked stretch of text.
inclusiveLeft: boolean
- Determines whether text inserted on the left of the marker will end up inside or outside of it.
inclusiveRight: boolean
- Like
inclusiveLeft
, but for the right side. atomic: boolean
- Atomic ranges act as a single unit when cursor movement is
concerned—i.e. it is impossible to place the cursor inside of
them. In atomic ranges,
inclusiveLeft
andinclusiveRight
have a different meaning—they will prevent the cursor from being placed respectively directly before and directly after the range. collapsed: boolean
- Collapsed ranges do not show up in the display. Setting a range to be collapsed will automatically make it atomic.
clearOnEnter: boolean
- When enabled, will cause the mark to clear itself whenever
the cursor enters its range. This is mostly useful for
text-replacement widgets that need to 'snap open' when the
user tries to edit them. The
"clear"
event fired on the range handle can be used to be notified when this happens. clearWhenEmpty: boolean
- Determines whether the mark is automatically cleared when it becomes empty. Default is true.
replacedWith: Element
- Use a given node to display this range. Implies both collapsed and atomic. The given DOM node must be an inline element (as opposed to a block element).
handleMouseEvents: boolean
- When
replacedWith
is given, this determines whether the editor will capture mouse and drag events occurring in this widget. Default is false—the events will be left alone for the default browser handler, or specific handlers on the widget, to capture. readOnly: boolean
- A read-only span can, as long as it is not cleared, not be
modified except by
calling
setValue
to reset the whole document. Note: adding a read-only span currently clears the undo history of the editor, because existing undo events being partially nullified by read-only spans would corrupt the history (in the current implementation). addToHistory: boolean
- When set to true (default is false), adding this marker will create an event in the undo history that can be individually undone (clearing the marker).
startStyle: string
- Can be used to specify an extra CSS class to be applied to the leftmost span that is part of the marker.
endStyle: string
- Equivalent
to
startStyle
, but for the rightmost span. css: string
- A string of CSS to be applied to the covered text. For example
"color: #fe3"
. title: string
- When given, will give the nodes created
for this span a HTML
title
attribute with the given value. - 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.
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, orundefined
if the marker is no longer in the document, and finallychanged()
, which you can call if you've done something that might change the size of the marker (for example changing the content of areplacedWith
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()
andclear()
. The first returns the current position of the bookmark, if it is still in the document, and the second explicitly removes the bookmark. The options argument is optional. If given, the following properties are recognized:widget: Element
- Can be used to display a DOM
node at the current location of the bookmark (analogous to
the
replacedWith
option tomarkText
). 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 eithernull
, to clear the marker, or a DOM element, to set it. The DOM element will be shown in the specified gutter next to the specified line. doc.clearGutter(gutterID: string)
- Remove all gutter markers in the gutter with the given ID.
doc.addLineClass(line: integer|LineHandle, where: string, class: string) → LineHandle
- Set a CSS class name for the given line.
line
can be a number or a line handle.where
determines to which element this class should be applied, can can be one of"text"
(the text element, which lies in front of the selection),"background"
(a background element that will be behind the selection),"gutter"
(the line's gutter space), or"wrap"
(the wrapper node that wraps all of the line's elements, including gutter elements).class
should be the name of the class to apply. doc.removeLineClass(line: integer|LineHandle, where: string, class: string) → LineHandle
- Remove a CSS class from a line.
line
can be a line handle or number.where
should be one of"text"
,"background"
, or"wrap"
(seeaddLineClass
).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}
, wheregutterMarkers
is an object mapping gutter IDs to marker elements, andwidgets
is an array of line widgets attached to this line, and the various class properties refer to classes added withaddLineClass
. 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. WhenscrollIntoView
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 callremoveChild
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, andnode
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.
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
andheight
can be either numbers (interpreted as pixels) or CSS units ("100%"
, for example). You can passnull
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
orundefined
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 benull
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. Themargin
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. Ifmode
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. Ifmode
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 fromcursorCoords
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 optionalmode
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 thatcoordsChar
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
(seecoordsChar
), 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 theviewportChange
event. cm.refresh()
- If your code does something to change the size of the editor element (window resizes are already listened for), or unhides it, you should probably follow up by calling this method to ensure CodeMirror is still looking as intended. See also the autorefresh addon.
Mode, state, and token-related methods
When writing language-aware functionality, it can often be useful to hook into the knowledge that the CodeMirror language mode has. See the section on modes for a more detailed description of how these work.
doc.getMode() → object
- Gets the (outer) mode object for the editor. Note that this
is distinct from
getOption("mode")
, which gives you the mode specification, rather than the resolved, instantiated mode object. cm.getModeAt(pos: {line, ch}) → object
- Gets the inner mode at a given position. This will return
the same as
getMode
for simple modes, but will return an inner mode for nesting modes (such ashtmlmixed
). cm.getTokenAt(pos: {line, ch}, ?precise: boolean) → object
- Retrieves information about the token the current mode found
before the given position (a
{line, ch}
object). The returned object has the following properties:start
- The character (on the given line) at which the token starts.
end
- The character at which the token ends.
string
- The token's string.
type
- The token type the mode assigned
to the token, such as
"keyword"
or"comment"
(may also be null). state
- The mode's state at the end of this token.
precise
is true, the token will be guaranteed to be accurate based on recent edits. If false or not specified, the token will use cached state information, which will be faster but might not be accurate if edits were recently made and highlighting has not yet completed. cm.getLineTokens(line: integer, ?precise: boolean) → array<{start, end, string, type, state}>
- This is similar
to
getTokenAt
, but collects all tokens for a given line into an array. It is much cheaper than repeatedly callinggetTokenAt
, which re-parses the part of the line before the token for every call. cm.getTokenTypeAt(pos: {line, ch}) → string
- This is a (much) cheaper version
of
getTokenAt
useful for when you just need the type of the token at a given position, and no other information. Will returnnull
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 (seeregisterHelper
), in which the values will be looked up. When the mode itself has a property that corresponds to thetype
, 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'shelperType
property and finally the mode's name are used. - For example, the JavaScript mode has a
property
fold
containing"brace"
. When thebrace-fold
addon is loaded, that defines a helper namedbrace
in thefold
namespace. This is then used by thefoldcode
addon to figure out that it can use that folding function to fold JavaScript code. - When any 'global' helpers are defined for the given namespace, their predicates are called on the current mode and editor, and all those that declare they are applicable will also be added to the array that is returned.
cm.getHelper(pos: {line, ch}, type: string) → helper
- Returns the first applicable helper value.
See
getHelpers
. cm.getStateAfter(?line: integer, ?precise: boolean) → object
- Returns the mode's parser state, if any, at the end of the
given line number. If no line number is given, the state at the
end of the document is returned. This can be useful for storing
parsing errors in the state, or getting other kinds of
contextual information for a line.
precise
is defined as ingetTokenAt()
.
Miscellaneous methods
cm.operation(func: () → any) → any
- CodeMirror internally buffers changes and only updates its DOM structure after it has finished performing some operation. If you need to perform a lot of operations on a CodeMirror instance, you can call this method with a function argument. It will call the function, buffering up all changes, and only doing the expensive update after the function returns. This can be a lot faster. The return value from this method will be the return value of your function.
cm.startOperation()
cm.endOperation()
- In normal circumstances, use the above
operation
method. But if you want to buffer operations happening asynchronously, or that can't all be wrapped in a callback function, you can callstartOperation
to tell CodeMirror to start buffering changes, andendOperation
to actually render all the updates. Be careful: if you use this API and forget to callendOperation
, the editor will just never update. cm.indentLine(line: integer, ?dir: string|integer)
- Adjust the indentation of the given line. The second
argument (which defaults to
"smart"
) may be one of:"prev"
- Base indentation on the indentation of the previous line.
"smart"
- Use the mode's smart indentation if available, behave
like
"prev"
otherwise. "add"
- Increase the indentation of the line by one indent unit.
"subtract"
- Reduce the indentation of the line.
<integer>
- Add (positive number) or reduce (negative number) the indentation by the given amount of spaces.
cm.toggleOverwrite(?value: boolean)
- Switches between overwrite and normal insert mode (when not given an argument), or sets the overwrite mode to a specific state (when given an argument).
cm.isReadOnly() → boolean
- Tells you whether the editor's content can be edited by the user.
doc.lineSeparator()
- Returns the preferred line separator string for this
document, as per the option
by the same name. When that option is
null
, the string"\n"
is returned. cm.execCommand(name: string)
- Runs the command with the given name on the editor.
doc.posFromIndex(index: integer) → {line, ch}
- Calculates and returns a
{line, ch}
object for a zero-basedindex
who's value is relative to the start of the editor's text. If theindex
is out of range of the text then the returned object is clipped to start or end of the text respectively. doc.indexFromPos(object: {line, ch}) → integer
- The reverse of
posFromIndex
. cm.focus()
- Give the editor focus.
cm.getInputField() → Element
- Returns the input field for the editor. Will be a textarea
or an editable div, depending on the value of
the
inputStyle
option. cm.getWrapperElement() → Element
- Returns the DOM node that represents the editor, and controls its size. Remove this from your tree to delete an editor instance.
cm.getScrollerElement() → Element
- Returns the DOM node that is responsible for the scrolling of the editor.
cm.getGutterElement() → Element
- Fetches the DOM node that contains the editor gutters.
Static properties
The CodeMirror
object itself provides
several useful properties.
CodeMirror.version: string
- It contains a string that indicates the version of the
library. This is a triple of
integers
"major.minor.patch"
, wherepatch
is zero for releases, and something else (usually one) for dev snapshots. CodeMirror.fromTextArea(textArea: TextAreaElement, ?config: object)
- This method provides another way to initialize an editor. It
takes a textarea DOM node as first argument and an optional
configuration object as second. It will replace the textarea
with a CodeMirror instance, and wire up the form of that
textarea (if any) to make sure the editor contents are put into
the textarea when the form is submitted. The text in the
textarea will provide the content for the editor. A CodeMirror
instance created this way has three additional methods:
cm.save()
- Copy the content of the editor into the textarea.
cm.toTextArea()
- Remove the editor, and restore the original textarea (with the editor's current content). If you dynamically create and destroy editors made with `fromTextArea`, without destroying the form they are part of, you should make sure to call `toTextArea` to remove the editor, or its `"submit"` handler on the form will cause a memory leak.
cm.getTextArea() → TextAreaElement
- Returns the textarea that the instance was based on.
CodeMirror.defaults: object
- An object containing default values for all options. You can assign to its properties to modify defaults (though this won't affect editors that have already been created).
CodeMirror.defineExtension(name: string, value: any)
- If you want to define extra methods in terms of the
CodeMirror API, it is possible to
use
defineExtension
. This will cause the given value (usually a method) to be added to all CodeMirror instances created from then on. CodeMirror.defineDocExtension(name: string, value: any)
- Like
defineExtension
, but the method will be added to the interface forDoc
objects instead. CodeMirror.defineOption(name: string, default: any, updateFunc: function)
- Similarly,
defineOption
can be used to define new options for CodeMirror. TheupdateFunc
will be called with the editor instance and the new value when an editor is initialized, and whenever the option is modified throughsetOption
. CodeMirror.defineInitHook(func: function)
- If your extension just needs to run some
code whenever a CodeMirror instance is initialized,
use
CodeMirror.defineInitHook
. Give it a function as its only argument, and from then on, that function will be called (with the instance as argument) whenever a new CodeMirror instance is initialized. CodeMirror.registerHelper(type: string, name: string, value: helper)
- Registers a helper value with the given
name
in the given namespace (type
). This is used to define functionality that may be looked up by mode. Will create (if it doesn't already exist) a property on theCodeMirror
object for the giventype
, pointing to an object that maps names to values. I.e. after doingCodeMirror.registerHelper("hint", "foo", myFoo)
, the valueCodeMirror.hint.foo
will point tomyFoo
. 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 bygetHelpers
whenever the givenpredicate
returns true when called with the local mode and editor. CodeMirror.Pos(line: integer, ?ch: integer, ?sticky: string)
- A constructor for the objects that are used to represent
positions in editor documents.
sticky
defaults to null, but can be set to"before"
or"after"
to make the position explicitly associate with the character before or after it. CodeMirror.changeEnd(change: object) → {line, ch}
- Utility function that computes an end position from a change
(an object with
from
,to
, andtext
properties, as passed to various event handlers). The returned position will be the end of the changed range, after the change is applied. CodeMirror.countColumn(line: string, index: number, tabSize: number) → number
- Find the column position at a given string index using a given tabsize.
Addons(插件)
The addon
directory in the distribution contains a
number of reusable components that implement extra editor
functionality (on top of extension functions
like defineOption
, defineExtension
,
and registerHelper
). In
brief, they are:
dialog/dialog.js
- Provides a very simple way to query users for text input.
Adds the
openDialog(template, callback, options) → closeFunction
method to CodeMirror instances, which can be called with an HTML fragment or a detached DOM node that provides the prompt (should include aninput
orbutton
tag), and a callback function that is called when the user presses enter. It returns a functioncloseFunction
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 returnstrue
, 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 thekeyup
event. onInput: fn(event: InputEvent, value: string, close: fn()) → bool
- Same as
onKeyDown
but for theinput
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. Ifduration
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 mathing 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
orfindPrevious
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.
search/search.js
- 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 ofopenDialog
when available to make prompting for search queries less ugly. search/jump-to-line.js
- Implements a
jumpToLine
command and bindingAlt-G
to it. Acceptslinenumber
,+/-linenumber
,line:char
,scroll%
and:linenumber
formats. This will make use ofopenDialog
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 toCodeMirror-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 aclear
method that can be called to remove the matches. Depends on theannotatescrollbar
addon, and thematchesonscrollbar.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 thesimplescrollbar
addon to make sure of this. If this addon is loaded, thesearch
addon will automatically use it. edit/matchbrackets.js
- Defines an option
matchBrackets
which, when set to true or an options object, causes matching brackets to be highlighted whenever the cursor is next to them. It also adds a methodmatchBrackets
that forces this to happen once, and a methodfindMatchingBracket
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.
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 withpairs
and optionallyexplode
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 acloseBrackets
property, that overrides the configuration given in the option. But you can add anoverride
property with a truthy value to override mode-specific configuration. Demo here. - Defines an option
matchTags
that, when enabled, will cause the tags around the cursor to be highlighted (using theCodeMirror-matchingtag
class). Also defines a commandtoMatchingTag
, which you can bind a key to in order to jump to the tag matching the one under the cursor. Depends on theaddon/fold/xml-fold.js
addon. Demo here. edit/trailingspace.js
- Adds an option
showTrailingSpace
which, when enabled, adds the CSS classcm-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 acloseTag
command that closes the nearest open tag. Depends on thefold/xml-fold.js
addon. See the demo. edit/continuelist.js
- Markdown specific. Defines
a
"newlineAndIndentContinueMarkdownList"
command that can be bound toenter
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(from: {line, ch}, to: {line, ch}, ?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.
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
.
toggleComment
command, which is a shorthand command for callingtoggleComment
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 aPos
), 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 usesgetHelpers
with a"fold"
type to find folding functions appropriate for the local mode. There are files in theaddon/fold/
directory providingCodeMirror.fold.brace
, which finds blocks in brace languages (JavaScript, C, Java, etc),CodeMirror.fold.indent
, for languages where indentation determines block structure (Python, Haskell), andCodeMirror.fold.xml
, for XML-style languages, andCodeMirror.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.
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 thegutters
option, giving it the classCodeMirror-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 totrue
, 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.
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 aCodeMirror.colorize
function that can be called with an array (or other array-ish collection) of DOM nodes that represent the code snippets. By default, it'll get allpre
tags. Will read thedata-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 theopen
fields of the passed objects. When in a sub-mode, it will go back to the top mode again when theclose
string is encountered. Pass"\n"
foropen
orclose
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. (AnddelimStyle
is ignored.)
- When
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 (thehint
option), which is a function that take an editor instance and options object, and return a{list, from, to}
object, wherelist
is an array of strings or objects (the completions), andfrom
andto
give the start and end of the token that is being completed as{line, ch}
objects. An optionalselectedHint
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 callsgetHelpers
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 usesCodeMirror.hint.fromList
to complete from those. - When completions aren't simple strings, they should be
objects with the following properties:
text: string
- The completion text. This is the only required property.
displayText: string
- The text that should be displayed in the menu.
className: string
- A CSS class name to apply to the completion's line in the menu.
render: fn(Element, self, data)
- A method used to create the DOM structure for showing the completion by appending it to its first argument.
hint: fn(CodeMirror, self, data)
- A method used to actually apply the completion, instead of the default behavior.
from: {line, ch}
- Optional
from
position that will be used bypick()
instead of the global one passed with the full list of completions. to: {line, ch}
- Optional
to
position that will be used bypick()
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 anhintOptions
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 asupportsSelection
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()
, andclose()
methods (see the source for details), that can be used to change the focused element, pick the current element or close the menu. AdditionallymenuSize()
can give you access to the size of the current dropdown menu,length
give you the number of available completions, anddata
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.
"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.
addon/hint/show-hint.css
. Check out the demo for an example. hint/javascript-hint.js
- Defines a simple hinting function for JavaScript
(
CodeMirror.hint.javascript
) and CoffeeScript (CodeMirror.hint.coffeescript
) code. This will simply use the JavaScript environment that the editor runs in as a source of information about objects and their properties. hint/xml-hint.js
- Defines
CodeMirror.hint.xml
, which produces hints for XML tagnames, attribute names, and attribute values, guided by aschemaInfo
option (a property of the second argument passed to the hinting function, or the third argument passed toCodeMirror.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 propertieschildren
(an array of valid child element names, omit to simply allow all tags to appear) andattrs
(an object mapping attribute names tonull
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 aschemaInfo
option, and aCodeMirror.hint.html
hinting function that automatically callsCodeMirror.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), andrange
, 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, anddefaultTable
, a string corresponding to a table name intables
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 classcm-matchhighlight
),trim
, which controls whether whitespace is trimmed from the selection, andshowToken
which can be set totrue
or to a regexp matching the characters that make up a word. When enabled, it causes the current word to be highlighted when nothing is selected (defaults to off). Demo here. lint/lint.js
- Defines an interface component for showing linting warnings,
with pluggable warning sources
(see
html-lint.js
,json-lint.js
,javascript-lint.js
,coffeescript-lint.js
, andcss-lint.js
in the same directory). Defines alint
option that can be set to an annotation source (for exampleCodeMirror.lint.javascript
), to an options object (in which case thegetAnnotations
field is used as annotation source), or simply totrue
. 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 anasync
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 alintOnChange: false
option to disable that. Depends onaddon/lint/lint.css
. A demo can be found here. selection/mark-selection.js
- Causes the selected text to be marked with the CSS class
CodeMirror-selectedtext
when thestyleSelectedText
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 classCodeMirror-activeline
, adds a background with the classCodeMirror-activeline-background
, and adds the classCodeMirror-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).
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 setCodeMirror.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 definesCodeMirror.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, wherename
is the human-readable name,mime
the MIME type, andmode
the name of the mode file that defines this MIME. There are optional propertiesmimes
, which holds an array of MIME types for modes with multiple MIMEs associated, andext
, which holds an array of file extensions associated with this mode. Four convenience functions,CodeMirror.findModeByMIME
,CodeMirror.findModeByExtension
,CodeMirror.findModeByFileName
andCodeMirror.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-levelmode
directory, not underaddon
. Demo. comment/continuecomment.js
- Adds a
continueComments
option, which sets whether the editor will make the next line continue a comment when you press Enter inside a comment block. Can be set to a boolean to enable/disable this functionality. Set to a string, it will continue comments using a custom shortcut. Set to an object, it will use thekey
property for a custom shortcut and the booleancontinueLineComment
property to determine whether single-line comments should be continued (defaulting totrue
). 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 aCodeMirror-empty
CSS class whenever it doesn't contain any text. See the demo. display/fullscreen.js
- Defines an option
fullScreen
that, when set totrue
, will make the editor full-screen (as in, taking up the whole browser window). Depends onfullscreen.css
. Demo here. display/autorefresh.js
- This addon can be useful when initializing an editor in a
hidden DOM node, in cases where it is difficult to
call
refresh
when the editor becomes visible. It defines an optionautoRefresh
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 thescrollbarStyle
option. Depends onsimplescrollbars.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 whoseupdate
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'sclear
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 thecolumn
property. TheclassName
property can be used to assign a custom style to a ruler. Demo here. display/panel.js
- Defines an
addPanel
method for CodeMirror instances, which places a DOM node above or below an editor, and shrinks the editor to make room for the node. The method takes as first argument as DOM node, and as second an optional options object. ThePanel
object returned by this method has aclear
method that is used to remove the panel, and achanged
method that can be used to notify the addon when the size of the panel's DOM node has changed.
The method accepts the following options:position: string
- Controls the position of the newly added panel. The
following values are recognized:
top (default)
- Adds the panel at the very top.
after-top
- Adds the panel at the bottom of the top panels.
bottom
- Adds the panel at the very bottom.
before-bottom
- Adds the panel at the top of the bottom panels.
before: Panel
- The new panel will be added before the given panel.
after: Panel
- The new panel will be added after the given panel.
replace: Panel
- The new panel will replace the given panel.
stable: bool
- Whether to scroll the editor to keep the text's vertical position stable, when adding a panel above it. Defaults to false.
after
,before
orreplace
options, if the panel doesn't exists or has been removed, the value of theposition
option will be used as a fallback.
A demo of the addon is available here. wrap/hardwrap.js
- Addon to perform hard line wrapping/breaking for paragraphs
of text. Adds these methods to editor instances:
wrapParagraph(?pos: {line, ch}, ?options: object)
- Wraps the paragraph at the given position.
If
pos
is not given, it defaults to the cursor position. wrapRange(from: {line, ch}, to: {line, ch}, ?options: object)
- Wraps the given range as one big paragraph.
wrapParagraphsInRange(from: {line, ch}, to: {line, ch}, ?options: object)
- Wraps the paragraphs in (and overlapping with) the given range individually.
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.
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 theCodeMirror
constructor, first a node to append the interface to, and then an options object. Options are passed through to the editors inside the view. These extra options are recognized:origLeft
andorigRight: 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.
"goNextDiff"
and"goPrevDiff"
to quickly jump to the next changed chunk. Demo here. tern/tern.js
- Provides integration with the Tern JavaScript analysis engine, for completion, definition finding, and minor refactoring help. See the demo for a very simple integration. For more involved scenarios, see the comments at the top of the addon and the implementation of the (multi-file) demonstration on the Tern website.
Writing CodeMirror Modes(编写CodeMirror模式)
Modes typically consist of a single JavaScript file. This file defines, in the simplest case, a lexer (tokenizer) for your language—a function that takes a character stream as input, advances it past a token, and returns a style for that token. More advanced modes can also handle indentation for the language.
This section describes the low-level mode interface. Many modes are written directly against this, since it offers a lot of control, but for a quick mode definition, you might want to use the simple mode addon.
The mode script should
call CodeMirror.defineMode
to
register itself with CodeMirror. This function takes two
arguments. The first should be the name of the mode, for which you
should use a lowercase string, preferably one that is also the
name of the files that define the mode (i.e. "xml"
is
defined in xml.js
). The second argument should be a
function that, given a CodeMirror configuration object (the thing
passed to the CodeMirror
function) and an optional
mode configuration object (as in
the mode
option), returns
a mode object.
Typically, you should use this second argument
to defineMode
as your module scope function (modes
should not leak anything into the global scope!), i.e. write your
whole mode inside this function.
The main responsibility of a mode script is parsing the content of the editor. Depending on the language and the amount of functionality desired, this can be done in really easy or extremely complicated ways. Some parsers can be stateless, meaning that they look at one element (token) of the code at a time, with no memory of what came before. Most, however, will need to remember something. This is done by using a state object, which is an object that is always passed when reading a token, and which can be mutated by the tokenizer.
Modes that use a state must define
a startState
method on their mode
object. This is a function of no arguments that produces a state
object to be used at the start of a document.
The most important part of a mode object is
its token(stream, state)
method. All
modes must define this method. It should read one token from the
stream it is given as an argument, optionally update its state,
and return a style string, or null
for tokens that do
not have to be styled. For your styles, you are encouraged to use
the 'standard' names defined in the themes (without
the cm-
prefix). If that fails, it is also possible
to come up with your own and write your own CSS theme file.
A typical token string would
be "variable"
or "comment"
. Multiple
styles can be returned (separated by spaces), for
example "string error"
for a thing that looks like a
string but is invalid somehow (say, missing its closing quote).
When a style is prefixed by "line-"
or "line-background-"
, the style will be applied to
the whole line, analogous to what
the addLineClass
method
does—styling the "text"
in the simple case, and
the "background"
element
when "line-background-"
is prefixed.
The stream object that's passed
to token
encapsulates a line of code (tokens may
never span lines) and our current position in that line. It has
the following API:
eol() → boolean
- Returns true only if the stream is at the end of the line.
sol() → boolean
- Returns true only if the stream is at the start of the line.
peek() → string
- Returns the next character in the stream without advancing
it. Will return a
null
at the end of the line. next() → string
- Returns the next character in the stream and advances it.
Also returns
null
when no more characters are available. eat(match: string|regexp|function(char: string) → boolean) → string
match
can be a character, a regular expression, or a function that takes a character and returns a boolean. If the next character in the stream 'matches' the given argument, it is consumed and returned. Otherwise,undefined
is returned.eatWhile(match: string|regexp|function(char: string) → boolean) → boolean
- Repeatedly calls
eat
with the given argument, until it fails. Returns true if any characters were eaten. eatSpace() → boolean
- Shortcut for
eatWhile
when matching white-space. skipToEnd()
- Moves the position to the end of the line.
skipTo(str: string) → boolean
- Skips to the start of the next occurrence of the given string, if found on the current line (doesn't advance the stream if the string does not occur on the line). Returns true if the string was found.
match(pattern: string, ?consume: boolean, ?caseFold: boolean) → boolean
match(pattern: regexp, ?consume: boolean) → array<string>
- Act like a
multi-character
eat
—ifconsume
is true or not given—or a look-ahead that doesn't update the stream position—if it is false.pattern
can be either a string or a regular expression starting with^
. When it is a string,caseFold
can be set to true to make the match case-insensitive. When successfully matching a regular expression, the returned value will be the array returned bymatch
, in case you need to extract matched groups. backUp(n: integer)
- Backs up the stream
n
characters. Backing it up further than the start of the current token will cause things to break, so be careful. column() → integer
- Returns the column (taking into account tabs) at which the current token starts.
indentation() → integer
- Tells you how far the current line has been indented, in spaces. Corrects for tab characters.
current() → string
- Get the string between the start of the current token and the current stream position.
lookAhead(n: number) → ?string
- Get the line
n
(>0) lines after the current one, in order to scan ahead across line boundaries. Note that you want to do this carefully, since looking far ahead will make mode state caching much less effective. baseToken() → ?{type: ?string, size: number}
- Modes added
through
addOverlay
(and only such modes) can use this method to inspect the current token produced by the underlying mode.
By default, blank lines are simply skipped when
tokenizing a document. For languages that have significant blank
lines, you can define
a blankLine(state)
method on your
mode that will get called whenever a blank line is passed over, so
that it can update the parser state.
Because state object are mutated, and CodeMirror
needs to keep valid versions of a state around so that it can
restart a parse at any line, copies must be made of state objects.
The default algorithm used is that a new state object is created,
which gets all the properties of the old object. Any properties
which hold arrays get a copy of these arrays (since arrays tend to
be used as mutable stacks). When this is not correct, for example
because a mode mutates non-array properties of its state object, a
mode object should define
a copyState
method, which is given a
state and should return a safe copy of that state.
If you want your mode to provide smart indentation
(through the indentLine
method and the indentAuto
and newlineAndIndent
commands, to which keys can be
bound), you must define
an indent(state, textAfter)
method
on your mode object.
The indentation method should inspect the given state object,
and optionally the textAfter
string, which contains
the text on the line that is being indented, and return an
integer, the amount of spaces to indent. It should usually take
the indentUnit
option into account. An indentation method may
return CodeMirror.Pass
to indicate that it
could not come up with a precise indentation.
To work well with
the commenting addon, a mode may
define lineComment
(string that
starts a line
comment), blockCommentStart
, blockCommentEnd
(strings that start and end block comments),
and blockCommentLead
(a string to put at the start of
continued lines in a block comment). All of these are
optional.
Finally, a mode may define either
an electricChars
or an electricInput
property, which are used to automatically reindent the line when
certain patterns are typed and
the electricChars
option is enabled. electricChars
may be a string, and
will trigger a reindent whenever one of the characters in that
string are typed. Often, it is more appropriate to
use electricInput
, which should hold a regular
expression, and will trigger indentation when the part of the
line before the cursor matches the expression. It should
usually end with a $
character, so that it only
matches when the indentation-changing pattern was just typed, not when something was
typed after the pattern.
So, to summarize, a mode must provide
a token
method, and it may
provide startState
, copyState
,
and indent
methods. For an example of a trivial mode,
see the diff mode, for a more
involved example, see the C-like
mode.
Sometimes, it is useful for modes to nest—to have one
mode delegate work to another mode. An example of this kind of
mode is the mixed-mode HTML
mode. To implement such nesting, it is usually necessary to
create mode objects and copy states yourself. To create a mode
object, there are CodeMirror.getMode(options,
parserConfig)
, where the first argument is a configuration
object as passed to the mode constructor function, and the second
argument is a mode specification as in
the mode
option. To copy a
state object, call CodeMirror.copyState(mode, state)
,
where mode
is the mode that created the given
state.
In a nested mode, it is recommended to add an
extra method, innerMode
which, given
a state object, returns a {state, mode}
object with
the inner mode and its state for the current position. These are
used by utility scripts such as the tag
closer to get context information. Use
the CodeMirror.innerMode
helper function to, starting
from a mode and a state, recursively walk down to the innermost
mode and state.
To make indentation work properly in a nested parser, it is
advisable to give the startState
method of modes that
are intended to be nested an optional argument that provides the
base indentation for the block of code. The JavaScript and CSS
parser do this, for example, to allow JavaScript and CSS code
inside the mixed-mode HTML mode to be properly indented.
It is possible, and encouraged, to associate
your mode, or a certain configuration of your mode, with
a MIME type. For
example, the JavaScript mode associates itself
with text/javascript
, and its JSON variant
with application/json
. To do this,
call CodeMirror.defineMIME(mime,
modeSpec)
, where modeSpec
can be a string or
object specifying a mode, as in
the mode
option.
If a mode specification wants to add some properties to the
resulting mode object, typically for use
with getHelpers
, it may
contain a modeProps
property, which holds an object.
This object's properties will be copied to the actual mode
object.
Sometimes, it is useful to add or override mode
object properties from external code.
The CodeMirror.extendMode
function
can be used to add properties to mode objects produced for a
specific mode. Its first argument is the name of the mode, its
second an object that specifies the properties that should be
added. This is mostly useful to add utilities that can later be
looked up through getMode
.
VIM Mode API(VIM模式API)
CodeMirror has a robust VIM mode that attempts to faithfully
emulate VIM's most useful features. It can be enabled by
including keymap/vim.js
and setting the keyMap
option to
"vim"
.
Configuration
VIM mode accepts configuration options for customizing
behavior at run time. These methods can be called at any time
and will affect all existing CodeMirror instances unless
specified otherwise. The methods are exposed on the
CodeMirror.Vim
object.
setOption(name: string, value: any, ?cm: CodeMirror, ?cfg: object)
- Sets the value of a VIM option.
name
should be the name of an option. Ifcfg.scope
is not set andcm
is provided, then sets the global and instance values of the option. Otherwise, sets either the global or instance value of the option depending on whethercfg.scope
isglobal
orlocal
. getOption(name: string, ?cm: CodeMirror: ?cfg: object)
- Gets the current value of a VIM option. If
cfg.scope
is not set andcm
is provided, then gets the instance value of the option, falling back to the global value if not set. Ifcfg.scope
is provided, then gets theglobal
orlocal
value without checking the other. map(lhs: string, rhs: string, ?context: string)
- Maps a key sequence to another key sequence. Implements
VIM's
:map
command. To map ; to : in VIM would be:map ; :
. That would translate toCodeMirror.Vim.map(';', ':');
. Thecontext
can benormal
,visual
, orinsert
, which correspond to:nmap
,:vmap
, and:imap
respectively. mapCommand(keys: string, type: string, name: string, ?args: object, ?extra: object)
- Maps a key sequence to a
motion
,operator
, oraction
type command. The args object is passed through to the command when it is invoked by the provided key sequence.extras.context
can benormal
,visual
, orinsert
, to map the key sequence only in the corresponding mode.extras.isEdit
is applicable only to actions, determining whether it is recorded for replay for the.
single-repeat command.
Extending VIM
CodeMirror's VIM mode implements a large subset of VIM's core
editing functionality. But since there's always more to be
desired, there is a set of APIs for extending VIM's
functionality. As with the configuration API, the methods are
exposed on CodeMirror.Vim
and may
be called at any time.
defineOption(name: string, default: any, type: string, ?aliases: array<string>, ?callback: function (?value: any, ?cm: CodeMirror) → ?any)
- Defines a VIM style option and makes it available to the
:set
command. Type can beboolean
orstring
, used for validation and by:set
to determine which syntax to accept. If acallback
is passed in, VIM does not store the value of the option itself, but instead uses the callback as a setter/getter. If the first argument to the callback isundefined
, then the callback should return the value of the option. Otherwise, it should set instead. Since VIM options have global and instance values, whether aCodeMirror
instance is passed in denotes whether the global or local value should be used. Consequently, it's possible for the callback to be called twice for a singlesetOption
orgetOption
call. Note that right now, VIM does not support defining buffer-local options that do not have global values. If an option should not have a global value, either always ignore thecm
parameter in the callback, or always pass in acfg.scope
tosetOption
andgetOption
. defineMotion(name: string, fn: function(cm: CodeMirror, head: {line, ch}, ?motionArgs: object}) → {line, ch})
- Defines a motion command for VIM. The motion should return
the desired result position of the cursor.
head
is the current position of the cursor. It can differ fromcm.getCursor('head')
if VIM is in visual mode.motionArgs
is the object passed intomapCommand()
. defineOperator(name: string, fn: function(cm: CodeMirror, ?operatorArgs: object, ranges: array<{anchor, head}>) → ?{line, ch})
- Defines an operator command, similar to
defineMotion
.ranges
is the range of text the operator should operate on. If the cursor should be set to a certain position after the operation finishes, it can return a cursor object. defineAction(name: string, fn: function(cm: CodeMirror, ?actionArgs: object))
- Defines an action command, similar to
defineMotion
. Action commands can have arbitrary behavior, making them more flexible than motions and operators, at the loss of orthogonality. defineEx(name: string, ?prefix: string, fn: function(cm: CodeMirror, ?params: object))
- Defines an Ex command, and maps it to
:name
. If a prefix is provided, it, and any prefixed substring of thename
beginning with theprefix
can be used to invoke the command. If theprefix
is falsy, thenname
is used as the prefix.params.argString
contains the part of the prompted string after the command name.params.args
isparams.argString
split by whitespace. If the command was prefixed with aline range
,params.line
andparams.lineEnd
will be set.