4
<title>CodeMirror: User Manual</title>
5
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Droid+Sans|Droid+Sans:bold"/>
6
<link rel="stylesheet" type="text/css" href="docs.css"/>
7
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
8
<style>dl dl {margin: 0;}</style>
12
<h1><span class="logo-braces">{ }</span> <a href="http://codemirror.net/">CodeMirror</a></h1>
15
<img src="baboon.png" class="logo" alt="logo"/>/* User manual and
19
<div class="clear"><div class="leftbig blk">
21
<h2 id="overview">Overview</h2>
23
<p>CodeMirror is a code-editor component that can be embedded in
24
Web pages. The code library provides <em>only</em> the editor
25
component, no accompanying buttons, auto-completion, or other IDE
26
functionality. It does provide a rich API on top of which such
27
functionality can be straightforwardly implemented. See
28
the <a href="#addons">add-ons</a> included in the distribution,
30
the <a href="http://www.octolabs.com/javascripts/codemirror-ui/">CodeMirror
31
UI</a> project, for reusable implementations of extra features.</p>
33
<p>CodeMirror works with language-specific modes. Modes are
34
JavaScript programs that help color (and optionally indent) text
35
written in a given language. The distribution comes with a few
36
modes (see the <code>mode/</code> directory), and it isn't hard
37
to <a href="#modeapi">write new ones</a> for other languages.</p>
39
<h2 id="usage">Basic Usage</h2>
41
<p>The easiest way to use CodeMirror is to simply load the script
42
and style sheet found under <code>lib/</code> in the distribution,
43
plus a mode script from one of the <code>mode/</code> directories
44
and a theme stylesheet from <code>theme/</code>. (See
45
also <a href="compress.html">the compression helper</a>.) For
48
<pre><script src="lib/codemirror.js"></script>
49
<link rel="stylesheet" href="../lib/codemirror.css">
50
<script src="mode/javascript/javascript.js"></script></pre>
52
<p>Having done this, an editor instance can be created like
55
<pre>var myCodeMirror = CodeMirror(document.body);</pre>
57
<p>The editor will be appended to the document body, will start
58
empty, and will use the mode that we loaded. To have more control
59
over the new editor, a configuration object can be passed
60
to <code>CodeMirror</code> as a second argument:</p>
62
<pre>var myCodeMirror = CodeMirror(document.body, {
63
value: "function myScript(){return 100;}\n",
67
<p>This will initialize the editor with a piece of code already in
68
it, and explicitly tell it to use the JavaScript mode (which is
69
useful when multiple modes are loaded).
70
See <a href="#config">below</a> for a full discussion of the
71
configuration options that CodeMirror accepts.</p>
73
<p>In cases where you don't want to append the editor to an
74
element, and need more control over the way it is inserted, the
75
first argument to the <code>CodeMirror</code> function can also
76
be a function that, when given a DOM element, inserts it into the
77
document somewhere. This could be used to, for example, replace a
78
textarea with a real editor:</p>
80
<pre>var myCodeMirror = CodeMirror(function(elt) {
81
myTextArea.parentNode.replaceChild(elt, myTextArea);
82
}, {value: myTextArea.value});</pre>
84
<p>However, for this use case, which is a common way to use
85
CodeMirror, the library provides a much more powerful
88
<pre>var myCodeMirror = CodeMirror.fromTextArea(myTextArea);</pre>
90
<p>This will, among other things, ensure that the textarea's value
91
is updated when the form (if it is part of a form) is submitted.
92
See the <a href="#fromTextArea">API reference</a> for a full
93
description of this method.</p>
95
<h2 id="config">Configuration</h2>
97
<p>Both the <code>CodeMirror</code> function and
98
its <code>fromTextArea</code> method take as second (optional)
99
argument an object containing configuration options. Any option
100
not supplied like this will be taken
101
from <code>CodeMirror.defaults</code>, an object containing the
102
default options. You can update this object to change the defaults
105
<p>Options are not checked in any way, so setting bogus option
106
values is bound to lead to odd errors.</p>
108
<p>These are the supported options:</p>
111
<dt id="option_value"><code>value (string)</code></dt>
112
<dd>The starting value of the editor.</dd>
114
<dt id="option_mode"><code>mode (string or object)</code></dt>
115
<dd>The mode to use. When not given, this will default to the
116
first mode that was loaded. It may be a string, which either
117
simply names the mode or is
118
a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type
119
associated with the mode. Alternatively, it may be an object
120
containing configuration options for the mode, with
121
a <code>name</code> property that names the mode (for
122
example <code>{name: "javascript", json: true}</code>). The demo
123
pages for each mode contain information about what configuration
124
parameters the mode supports. You can ask CodeMirror which modes
125
and MIME types are loaded with
126
the <code>CodeMirror.listModes</code>
127
and <code>CodeMirror.listMIMEs</code> functions.</dd>
129
<dt id="option_theme"><code>theme (string)</code></dt>
130
<dd>The theme to style the editor with. You must make sure the
131
CSS file defining the corresponding <code>.cm-s-[name]</code>
132
styles is loaded (see
133
the <a href="../theme/"><code>theme</code></a> directory in the
134
distribution). The default is <code>"default"</code>, for which
135
colors are included in <code>codemirror.css</code>. It is
136
possible to use multiple theming classes at once—for
137
example <code>"foo bar"</code> will assign both
138
the <code>cm-s-foo</code> and the <code>cm-s-bar</code> classes
141
<dt id="option_indentUnit"><code>indentUnit (integer)</code></dt>
142
<dd>How many spaces a block (whatever that means in the edited
143
language) should be indented. The default is 2.</dd>
145
<dt id="option_smartIndent"><code>smartIndent (boolean)</code></dt>
146
<dd>Whether to use the context-sensitive indentation that the
147
mode provides (or just indent the same as the line before).
148
Defaults to true.</dd>
150
<dt id="option_tabSize"><code>tabSize (integer)</code></dt>
151
<dd>The width of a tab character. Defaults to 4.</dd>
153
<dt id="option_indentWithTabs"><code>indentWithTabs (boolean)</code></dt>
154
<dd>Whether, when indenting, the first N*<code>tabSize</code>
155
spaces should be replaced by N tabs. Default is false.</dd>
157
<dt id="option_electricChars"><code>electricChars (boolean)</code></dt>
158
<dd>Configures whether the editor should re-indent the current
159
line when a character is typed that might change its proper
160
indentation (only works if the mode supports indentation).
161
Default is true.</dd>
163
<dt id="option_autoClearEmptyLines"><code>autoClearEmptyLines (boolean)</code></dt>
164
<dd>When turned on (default is off), this will clear
165
automatically clear lines consisting only of whitespace when the
166
cursor leaves them. This is mostly useful to prevent auto
167
indentation from introducing trailing whitespace in a file.</dd>
169
<dt id="option_keyMap"><code>keyMap (string)</code></dt>
170
<dd>Configures the keymap to use. The default
171
is <code>"default"</code>, which is the only keymap defined
172
in <code>codemirror.js</code> itself. Extra keymaps are found in
173
the <a href="../keymap/"><code>keymap</code></a> directory. See
174
the <a href="#keymaps">section on keymaps</a> for more
177
<dt id="option_extraKeys"><code>extraKeys (object)</code></dt>
178
<dd>Can be used to specify extra keybindings for the editor,
179
alongside the ones defined
180
by <a href="#option_keyMap"><code>keyMap</code></a>. Should be
181
either null, or a valid <a href="#keymaps">keymap</a> value.</dd>
183
<dt id="option_lineWrapping"><code>lineWrapping (boolean)</code></dt>
184
<dd>Whether CodeMirror should scroll or wrap for long lines.
185
Defaults to <code>false</code> (scroll).</dd>
187
<dt id="option_lineNumbers"><code>lineNumbers (boolean)</code></dt>
188
<dd>Whether to show line numbers to the left of the editor.</dd>
190
<dt id="option_firstLineNumber"><code>firstLineNumber (integer)</code></dt>
191
<dd>At which number to start counting lines. Default is 1.</dd>
193
<dt id="option_gutter"><code>gutter (boolean)</code></dt>
194
<dd>Can be used to force a 'gutter' (empty space on the left of
195
the editor) to be shown even when no line numbers are active.
196
This is useful for setting <a href="#setMarker">markers</a>.</dd>
198
<dt id="option_fixedGutter"><code>fixedGutter (boolean)</code></dt>
199
<dd>When enabled (off by default), this will make the gutter
200
stay visible when the document is scrolled horizontally.</dd>
202
<dt id="option_readOnly"><code>readOnly (boolean)</code></dt>
203
<dd>This disables editing of the editor content by the user. If
204
the special value <code>"nocursor"</code> is given (instead of
205
simply <code>true</code>), focusing of the editor is also
208
<dt id="option_onChange"><code>onChange (function)</code></dt>
209
<dd>When given, this function will be called every time the
210
content of the editor is changed. It will be given the editor
211
instance as first argument, and an <code>{from, to, text, next}</code>
212
object containing information about the changes
213
that occurred as second argument. <code>from</code>
214
and <code>to</code> are the positions (in the pre-change
215
coordinate system) where the change started and
216
ended (for example, it might be <code>{ch:0, line:18}</code> if the
217
position is at the beginning of line #19). <code>text</code>
218
is an array of strings representing the text that replaced the changed
219
range (split by line). If multiple changes happened during a single
220
operation, the object will have a <code>next</code> property pointing to
221
another change object (which may point to another, etc).</dd>
223
<dt id="option_onCursorActivity"><code>onCursorActivity (function)</code></dt>
224
<dd>Will be called when the cursor or selection moves, or any
225
change is made to the editor content.</dd>
227
<dt id="option_onGutterClick"><code>onGutterClick (function)</code></dt>
228
<dd>When given, will be called whenever the editor gutter (the
229
line-number area) is clicked. Will be given the editor instance
230
as first argument, the (zero-based) number of the line that was
231
clicked as second argument, and the raw <code>mousedown</code>
232
event object as third argument.</dd>
234
<dt id="option_onFocus"><code>onFocus, onBlur (function)</code></dt>
235
<dd>The given functions will be called whenever the editor is
236
focused or unfocused.</dd>
238
<dt id="option_onScroll"><code>onScroll (function)</code></dt>
239
<dd>When given, will be called whenever the editor is
242
<dt id="option_onHighlightComplete"><code>onHighlightComplete (function)</code></dt>
243
<dd>Whenever the editor's content has been fully highlighted,
244
this function (if given) will be called. It'll be given a single
245
argument, the editor instance.</dd>
247
<dt id="option_onUpdate"><code>onUpdate (function)</code></dt>
248
<dd>Will be called whenever CodeMirror updates its DOM display.</dd>
250
<dt id="option_matchBrackets"><code>matchBrackets (boolean)</code></dt>
251
<dd>Determines whether brackets are matched whenever the cursor
252
is moved next to a bracket.</dd>
254
<dt id="option_workTime"><code>workTime, workDelay (number)</code></dt>
255
<dd>Highlighting is done by a pseudo background-thread that will
256
work for <code>workTime</code> milliseconds, and then use
257
timeout to sleep for <code>workDelay</code> milliseconds. The
258
defaults are 200 and 300, you can change these options to make
259
the highlighting more or less aggressive.</dd>
261
<dt id="option_pollInterval"><code>pollInterval (number)</code></dt>
262
<dd>Indicates how quickly CodeMirror should poll its input
263
textarea for changes. Most input is captured by events, but some
264
things, like IME input on some browsers, doesn't generate events
265
that allow CodeMirror to properly detect it. Thus, it polls.
266
Default is 100 milliseconds.</dd>
268
<dt id="option_undoDepth"><code>undoDepth (integer)</code></dt>
269
<dd>The maximum number of undo levels that the editor stores.
272
<dt id="option_tabindex"><code>tabindex (integer)</code></dt>
273
<dd>The <a href="http://www.w3.org/TR/html401/interact/forms.html#adef-tabindex">tab
274
index</a> to assign to the editor. If not given, no tab index
275
will be assigned.</dd>
277
<dt id="option_autofocus"><code>autofocus (boolean)</code></dt>
278
<dd>Can be used to make CodeMirror focus itself on
279
initialization. Defaults to off.
280
When <a href="#fromTextArea"><code>fromTextArea</code></a> is
281
used, and no explicit value is given for this option, it will
282
inherit the setting from the textarea's <code>autofocus</code>
285
<dt id="option_onKeyEvent"><code>onKeyEvent (function)</code></dt>
286
<dd>This provides a rather low-level hook into CodeMirror's key
287
handling. If provided, this function will be called on
288
every <code>keydown</code>, <code>keyup</code>,
289
and <code>keypress</code> event that CodeMirror captures. It
290
will be passed two arguments, the editor instance and the key
291
event. This key event is pretty much the raw key event, except
292
that a <code>stop()</code> method is always added to it. You
293
could feed it to, for example, <code>jQuery.Event</code> to
294
further normalize it.<br>This function can inspect the key
295
event, and handle it if it wants to. It may return true to tell
296
CodeMirror to ignore the event. Be wary that, on some browsers,
297
stopping a <code>keydown</code> does not stop
298
the <code>keypress</code> from firing, whereas on others it
299
does. If you respond to an event, you should probably inspect
300
its <code>type</code> property and only do something when it
301
is <code>keydown</code> (or <code>keypress</code> for actions
302
that need character data).</dd>
305
<h2 id="keymaps">Keymaps</h2>
307
<p>Keymaps are ways to associate keys with functionality. A keymap
308
is an object mapping strings that identify the keys to functions
309
that implement their functionality.</p>
311
<p>Keys are identified either by name or by character.
312
The <code>CodeMirror.keyNames</code> object defines names for
313
common keys and associates them with their key codes. Examples of
314
names defined here are <code>Enter</code>, <code>F5</code>,
315
and <code>Q</code>. These can be prefixed
316
with <code>Shift-</code>, <code>Cmd-</code>, <code>Ctrl-</code>,
317
and <code>Alt-</code> (in that order!) to specify a modifier. So
318
for example, <code>Shift-Ctrl-Space</code> would be a valid key
321
<p>Alternatively, a character can be specified directly by
322
surrounding it in single quotes, for example <code>'$'</code>
323
or <code>'q'</code>. Due to limitations in the way browsers fire
324
key events, these may not be prefixed with modifiers.</p>
326
<p>The <code>CodeMirror.keyMap</code> object associates keymaps
327
with names. User code and keymap definitions can assign extra
328
properties to this object. Anywhere where a keymap is expected, a
329
string can be given, which will be looked up in this object. It
330
also contains the <code>"default"</code> keymap holding the
331
default bindings.</p>
333
<p>The values of properties in keymaps can be either functions of
334
a single argument (the CodeMirror instance), or strings. Such
335
strings refer to properties of the
336
<code>CodeMirror.commands</code> object, which defines a number of
337
common commands that are used by the default keybindings, and maps
338
them to functions. A key handler function may throw
339
<code>CodeMirror.Pass</code> to indicate that it has decided not
340
to handle the key, and other handlers (or the default behavior)
341
should be given a turn.</p>
343
<p>Keys mapped to command names that start with the
344
characters <code>"go"</code> (which should be used for
345
cursor-movement actions) will be fired even when an
346
extra <code>Shift</code> modifier is present (i.e. <code>"Up":
347
"goLineUp"</code> matches both up and shift-up). This is used to
348
easily implement shift-selection.</p>
350
<p>Keymaps can defer to each other by defining
351
a <code>fallthrough</code> property. This indicates that when a
352
key is not found in the map itself, one or more other maps should
353
be searched. It can hold either a single keymap or an array of
356
<p>When a keymap contains a <code>catchall</code> property, the
357
handler function under that property will be called for all keys
358
dispatched through the keymap.</p>
360
<h2 id="styling">Customized Styling</h2>
362
<p>Up to a certain extent, CodeMirror's look can be changed by
363
modifying style sheet files. The style sheets supplied by modes
364
simply provide the colors for that mode, and can be adapted in a
365
very straightforward way. To style the editor itself, it is
366
possible to alter or override the styles defined
367
in <a href="../lib/codemirror.css"><code>codemirror.css</code></a>.</p>
369
<p>Some care must be taken there, since a lot of the rules in this
370
file are necessary to have CodeMirror function properly. Adjusting
371
colors should be safe, of course, and with some care a lot of
372
other things can be changed as well. The CSS classes defined in
373
this file serve the following roles:</p>
376
<dt id="class_CodeMirror"><code>CodeMirror</code></dt>
377
<dd>The outer element of the editor. This should be used for
378
borders and positioning. Can also be used to set styles that
379
should hold for everything inside the editor (such as font
380
and font size), or to set a background.</dd>
382
<dt id="class_CodeMirror_scroll"><code>CodeMirror-scroll</code></dt>
383
<dd>This determines whether the editor scrolls (<code>overflow:
384
auto</code> + fixed height). By default, it does. Giving
385
this <code>height: auto; overflow: visible;</code> will cause
386
the editor to resize to fit its content.</dd>
388
<dt id="class_CodeMirror_focused"><code>CodeMirror-focused</code></dt>
389
<dd>Whenever the editor is focused, the top element gets this
390
class. This is used to hide the cursor and give the selection a
391
different color when the editor is not focused.</dd>
393
<dt id="class_CodeMirror_gutter"><code>CodeMirror-gutter</code></dt>
394
<dd>Use this for giving a background or a border to the editor
395
gutter. Don't set any padding here,
396
use <code>CodeMirror-gutter-text</code> for that. By default,
397
the gutter is 'fluid', meaning it will adjust its width to the
398
maximum line number or line marker width. You can also set a
399
fixed width if you want.</dd>
401
<dt id="class_CodeMirror_gutter_text"><code>CodeMirror-gutter-text</code></dt>
402
<dd>Used to style the actual line numbers. For the numbers to
403
line up, you must make sure that the font in the gutter is the
404
same as the one in the rest of the editor, so you should
405
probably only set font style and size in
406
the <code>CodeMirror</code> class.</dd>
408
<dt id="class_CodeMirror_lines"><code>CodeMirror-lines</code></dt>
409
<dd>The visible lines. If this has vertical
410
padding, <code>CodeMirror-gutter</code> should have the same
413
<dt id="class_CodeMirror_cursor"><code>CodeMirror-cursor</code></dt>
414
<dd>The cursor is a block element that is absolutely positioned.
415
You can make it look whichever way you want.</dd>
417
<dt id="class_CodeMirror_selected"><code>CodeMirror-selected</code></dt>
418
<dd>The selection is represented by <code>span</code> elements
419
with this class.</dd>
421
<dt id="class_CodeMirror_matchingbracket"><code>CodeMirror-matchingbracket</code>,
422
<code>CodeMirror-nonmatchingbracket</code></dt>
423
<dd>These are used to style matched (or unmatched) brackets.</dd>
426
<p>The actual lines, as well as the cursor, are represented
427
by <code>pre</code> elements. By default no text styling (such as
428
bold) that might change line height is applied. If you do want
429
such effects, you'll have to give <code>CodeMirror pre</code> a
430
fixed height. Also, you must still take care that character width
433
<p>If your page's style sheets do funky things to
434
all <code>div</code> or <code>pre</code> elements (you probably
435
shouldn't do that), you'll have to define rules to cancel these
436
effects out again for elements under the <code>CodeMirror</code>
439
<p>Themes are also simply CSS files, which define colors for
440
various syntactic elements. See the files in
441
the <a href="../theme/"><code>theme</code></a> directory.</p>
443
<h2 id="api">Programming API</h2>
445
<p>A lot of CodeMirror features are only available through its API.
446
This has the disadvantage that you need to do work to enable them,
447
and the advantage that CodeMirror will fit seamlessly into your
450
<p>Whenever points in the document are represented, the API uses
451
objects with <code>line</code> and <code>ch</code> properties.
452
Both are zero-based. CodeMirror makes sure to 'clip' any positions
453
passed by client code so that they fit inside the document, so you
454
shouldn't worry too much about sanitizing your coordinates. If you
455
give <code>ch</code> a value of <code>null</code>, or don't
456
specify it, it will be replaced with the length of the specified
460
<dt id="getValue"><code>getValue() → string</code></dt>
461
<dd>Get the current editor content.</dd>
462
<dt id="setValue"><code>setValue(string)</code></dt>
463
<dd>Set the editor content.</dd>
465
<dt id="getSelection"><code>getSelection() → string</code></dt>
466
<dd>Get the currently selected code.</dd>
467
<dt id="replaceSelection"><code>replaceSelection(string)</code></dt>
468
<dd>Replace the selection with the given string.</dd>
470
<dt id="focus"><code>focus()</code></dt>
471
<dd>Give the editor focus.</dd>
472
<dt id="scrollTo"><code>scrollTo(x, y)</code></dt>
473
<dd>Scroll the editor to a given (pixel) position. Both
474
arguments may be left as <code>null</code>
475
or <code>undefined</code> to have no effect.</dd>
477
<dt id="setOption"><code>setOption(option, value)</code></dt>
478
<dd>Change the configuration of the editor. <code>option</code>
479
should the name of an <a href="#config">option</a>,
480
and <code>value</code> should be a valid value for that
482
<dt id="getOption"><code>getOption(option) → value</code></dt>
483
<dd>Retrieves the current value of the given option for this
484
editor instance.</dd>
486
<dt id="cursorCoords"><code>cursorCoords(start, mode) → object</code></dt>
487
<dd>Returns an <code>{x, y, yBot}</code> object containing the
488
coordinates of the cursor. If <code>mode</code>
489
is <code>"local"</code>, they will be relative to the top-left
490
corner of the editable document. If it is <code>"page"</code> or
491
not given, they are relative to the top-left corner of the
492
page. <code>yBot</code> is the coordinate of the bottom of the
493
cursor. <code>start</code> is a boolean indicating whether you
494
want the start or the end of the selection.</dd>
495
<dt id="charCoords"><code>charCoords(pos, mode) → object</code></dt>
496
<dd>Like <code>cursorCoords</code>, but returns the position of
497
an arbitrary characters. <code>pos</code> should be
498
a <code>{line, ch}</code> object.</dd>
499
<dt id="coordsChar"><code>coordsChar(object) → pos</code></dt>
500
<dd>Given an <code>{x, y}</code> object (in page coordinates),
501
returns the <code>{line, ch}</code> position that corresponds to
504
<dt id="undo"><code>undo()</code></dt>
505
<dd>Undo one edit (if any undo events are stored).</dd>
506
<dt id="redo"><code>redo()</code></dt>
507
<dd>Redo one undone edit.</dd>
508
<dt id="historySize"><code>historySize() → object</code></dt>
509
<dd>Returns an object with <code>{undo, redo}</code> properties,
510
both of which hold integers, indicating the amount of stored
511
undo and redo operations.</dd>
512
<dt id="clearHistory"><code>clearHistory()</code></dt>
513
<dd>Clears the editor's undo history.</dd>
515
<dt id="indentLine"><code>indentLine(line, dir)</code></dt>
516
<dd>Reset the given line's indentation to the indentation
517
prescribed by the mode. If the second argument is given,
518
indentation will be increased (if <code>dir</code> is true) or
519
decreased (if false) by an <a href="#option_indentUnit">indent
520
unit</a> instead.</dd>
522
<dt id="getTokenAt"><code>getTokenAt(pos) → object</code></dt>
523
<dd>Retrieves information about the token the current mode found
524
at the given position (a <code>{line, ch}</code> object). The
525
returned object has the following properties:
527
<dt><code>start</code></dt><dd>The character (on the given line) at which the token starts.</dd>
528
<dt><code>end</code></dt><dd>The character at which the token ends.</dd>
529
<dt><code>string</code></dt><dd>The token's string.</dd>
530
<dt><code>className</code></dt><dd>The class the mode assigned
531
to the token. (Can be null when no class was assigned.)</dd>
532
<dt><code>state</code></dt><dd>The mode's state at the end of this token.</dd>
535
<dt id="markText"><code>markText(from, to, className) → object</code></dt>
536
<dd>Can be used to mark a range of text with a specific CSS
537
class name. <code>from</code> and <code>to</code> should
538
be <code>{line, ch}</code> objects. The method will return an
539
object with two methods, <code>clear()</code>, which removes the
540
mark, and <code>find()</code>, which returns a <code>{from,
541
to}</code> (both document positions), indicating the current
542
position of the marked range.</dd>
544
<dt id="setBookmark"><code>setBookmark(pos) → object</code></dt>
545
<dd>Inserts a bookmark, a handle that follows the text around it
546
as it is being edited, at the given position. A bookmark has two
547
methods <code>find()</code> and <code>clear()</code>. The first
548
returns the current position of the bookmark, if it is still in
549
the document, and the second explicitly removes the
552
<dt id="findMarksAt"><code>findMarksAt(pos) → array</code></dt>
553
<dd>Returns an array of all the bookmarks and marked ranges
554
present at the given position.</dd>
556
<dt id="setMarker"><code>setMarker(line, text, className) → lineHandle</code></dt>
557
<dd>Add a gutter marker for the given line. Gutter markers are
558
shown in the line-number area (instead of the number for this
559
line). Both <code>text</code> and <code>className</code> are
560
optional. Setting <code>text</code> to a Unicode character like
561
● tends to give a nice effect. To put a picture in the gutter,
562
set <code>text</code> to a space and <code>className</code> to
563
something that sets a background image. If you
564
specify <code>text</code>, the given text (which may contain
565
HTML) will, by default, replace the line number for that line.
566
If this is not what you want, you can include the
567
string <code>%N%</code> in the text, which will be replaced by
568
the line number.</dd>
569
<dt id="clearMarker"><code>clearMarker(line)</code></dt>
570
<dd>Clears a marker created
571
with <code>setMarker</code>. <code>line</code> can be either a
572
number or a handle returned by <code>setMarker</code> (since a
573
number may now refer to a different line if something was added
575
<dt id="setLineClass"><code>setLineClass(line, className, backgroundClassName) → lineHandle</code></dt>
576
<dd>Set a CSS class name for the given line. <code>line</code>
577
can be a number or a line handle (as returned
578
by <code>setMarker</code> or this
579
function). <code>className</code> will be used to style the text
580
for the line, and <code>backgroundClassName</code> to style its
581
background (which lies behind the selection).
582
Pass <code>null</code> to clear the classes for a line.</dd>
583
<dt id="hideLine"><code>hideLine(line) → lineHandle</code></dt>
584
<dd>Hide the given line (either by number or by handle). Hidden
585
lines don't show up in the editor, and their numbers are skipped
586
when <a href="#option_lineNumbers">line numbers</a> are enabled.
587
Deleting a region around them does delete them, and coping a
588
region around will include them in the copied text.</dd>
589
<dt id="showLine"><code>showLine(line) → lineHandle</code></dt>
590
<dd>The inverse of <code>hideLine</code>—re-shows a previously
591
hidden line, by number or by handle.</dd>
593
<dt id="onDeleteLine"><code>onDeleteLine(line, func)</code></dt>
594
<dd>Register a function that should be called when the line is
595
deleted from the document.</dd>
597
<dt id="lineInfo"><code>lineInfo(line) → object</code></dt>
598
<dd>Returns the line number, text content, and marker status of
599
the given line, which can be either a number or a handle
600
returned by <code>setMarker</code>. The returned object has the
601
structure <code>{line, handle, text, markerText, markerClass,
602
lineClass, bgClass}</code>.</dd>
604
<dt id="getLineHandle"><code>getLineHandle(num) → lineHandle</code></dt>
605
<dd>Fetches the line handle for the given line number.</dd>
607
<dt id="addWidget"><code>addWidget(pos, node, scrollIntoView)</code></dt>
608
<dd>Puts <code>node</code>, which should be an absolutely
609
positioned DOM node, into the editor, positioned right below the
610
given <code>{line, ch}</code> position.
611
When <code>scrollIntoView</code> is true, the editor will ensure
612
that the entire node is visible (if possible). To remove the
613
widget again, simply use DOM methods (move it somewhere else, or
614
call <code>removeChild</code> on its parent).</dd>
616
<dt id="matchBrackets"><code>matchBrackets()</code></dt>
617
<dd>Force matching-bracket-highlighting to happen.</dd>
619
<dt id="lineCount"><code>lineCount() → number</code></dt>
620
<dd>Get the number of lines in the editor.</dd>
622
<dt id="getCursor"><code>getCursor(start) → object</code></dt>
623
<dd><code>start</code> is a boolean indicating whether the start
624
or the end of the selection must be retrieved. If it is not
625
given, the current cursor pos, i.e. the side of the selection
626
that would move if you pressed an arrow key, is chosen.
627
A <code>{line, ch}</code> object will be returned.</dd>
628
<dt id="somethingSelected"><code>somethingSelected() → boolean</code></dt>
629
<dd>Return true if any text is selected.</dd>
630
<dt id="setCursor"><code>setCursor(pos)</code></dt>
631
<dd>Set the cursor position. You can either pass a
632
single <code>{line, ch}</code> object, or the line and the
633
character as two separate parameters.</dd>
634
<dt id="setSelection"><code>setSelection(start, end)</code></dt>
635
<dd>Set the selection range. <code>start</code>
636
and <code>end</code> should be <code>{line, ch}</code> objects.</dd>
638
<dt id="getLine"><code>getLine(n) → string</code></dt>
639
<dd>Get the content of line <code>n</code>.</dd>
640
<dt id="setLine"><code>setLine(n, text)</code></dt>
641
<dd>Set the content of line <code>n</code>.</dd>
642
<dt id="removeLine"><code>removeLine(n)</code></dt>
643
<dd>Remove the given line from the document.</dd>
645
<dt id="getRange"><code>getRange(from, to) → string</code></td>
646
<dd>Get the text between the given points in the editor, which
647
should be <code>{line, ch}</code> objects.</dd>
648
<dt id="replaceRange"><code>replaceRange(string, from, to)</code></dt>
649
<dd>Replace the part of the document between <code>from</code>
650
and <code>to</code> with the given string. <code>from</code>
651
and <code>to</code> must be <code>{line, ch}</code>
652
objects. <code>to</code> can be left off to simply insert the
653
string at position <code>from</code>.</dd>
655
<dt id="posFromIndex"><code>posFromIndex(index) → object</code></dt>
656
<dd>Calculates and returns a <code>{line, ch}</code> object for a
657
zero-based <code>index</code> who's value is relative to the start of the
658
editor's text. If the <code>index</code> is out of range of the text then
659
the returned object is clipped to start or end of the text
661
<dt id="indexFromPos"><code>indexFromPos(object) → number</code></dt>
662
<dd>The reverse of <a href="#posFromIndex"><code>posFromIndex</code></a>.</dd>
665
<p>The following are more low-level methods:</p>
668
<dt id="operation"><code>operation(func) → result</code></dt>
669
<dd>CodeMirror internally buffers changes and only updates its
670
DOM structure after it has finished performing some operation.
671
If you need to perform a lot of operations on a CodeMirror
672
instance, you can call this method with a function argument. It
673
will call the function, buffering up all changes, and only doing
674
the expensive update after the function returns. This can be a
675
lot faster. The return value from this method will be the return
676
value of your function.</dd>
678
<dt id="refresh"><code>refresh()</code></dt>
679
<dd>If your code does something to change the size of the editor
680
element (window resizes are already listened for), or unhides
681
it, you should probably follow up by calling this method to
682
ensure CodeMirror is still looking as intended.</dd>
684
<dt id="getInputField"><code>getInputField() → textarea</code></dt>
685
<dd>Returns the hidden textarea used to read input.</dd>
686
<dt id="getWrapperElement"><code>getWrapperElement() → node</code></dt>
687
<dd>Returns the DOM node that represents the editor. Remove this
688
from your tree to delete an editor instance.</dd>
689
<dt id="getScrollerElement"><code>getScrollerElement() → node</code></dt>
690
<dd>Returns the DOM node that is responsible for the sizing and
691
the scrolling of the editor. You can change
692
the <code>height</code> and <code>width</code> styles of this
693
element to resize an editor. (You might have to call
694
the <a href="#refresh"><code>refresh</code></a> method
696
<dt id="getGutterElement"><code>getGutterElement() → node</code></dt>
697
<dd>Fetches the DOM node that represents the editor gutter.</dd>
699
<dt id="getStateAfter"><code>getStateAfter(line) → state</code></dt>
700
<dd>Returns the mode's parser state, if any, at the end of the
701
given line number. If no line number is given, the state at the
702
end of the document is returned. This can be useful for storing
703
parsing errors in the state, or getting other kinds of
704
contextual information for a line.</dd>
707
<p id="fromTextArea">Finally, the <code>CodeMirror</code> object
708
itself has a method <code>fromTextArea</code>. This takes a
709
textarea DOM node as first argument and an optional configuration
710
object as second. It will replace the textarea with a CodeMirror
711
instance, and wire up the form of that textarea (if any) to make
712
sure the editor contents are put into the textarea when the form
713
is submitted. A CodeMirror instance created this way has two
714
additional methods:</p>
717
<dt id="save"><code>save()</code></dt>
718
<dd>Copy the content of the editor into the textarea.</dd>
720
<dt id="toTextArea"><code>toTextArea()</code></dt>
721
<dd>Remove the editor, and restore the original textarea (with
722
the editor's current content).</dd>
724
<dt id="getTextArea"><code>getTextArea() → textarea</code></dt>
725
<dd>Returns the textarea that the instance was based on.</dd>
728
<p id="defineExtension">If you want to define extra methods in terms
729
of the CodeMirror API, it is possible to
730
use <code>CodeMirror.defineExtension(name, value)</code>. This
731
will cause the given value (usually a method) to be added to all
732
CodeMirror instances created from then on.</p>
734
<h2 id="addons">Add-ons</h2>
736
<p>The <code>lib/util</code> directory in the distribution
737
contains a number of reusable components that implement extra
738
editor functionality. In brief, they are:</p>
741
<dt id="util_dialog"><a href="../lib/util/dialog.js"><code>dialog.js</code></a></dt>
742
<dd>Provides a very simple way to query users for text input.
743
Adds an <code>openDialog</code> method to CodeMirror instances,
744
which can be called with an HTML fragment that provides the
745
prompt (should include an <code>input</code> tag), and a
746
callback function that is called when text has been entered.
747
Depends on <code>lib/util/dialog.css</code>.</dd>
748
<dt id="util_searchcursor"><a href="../lib/util/searchcursor.js"><code>searchcursor.js</code></a></dt>
749
<dd>Adds the <code>getSearchCursor(query, start, caseFold) →
750
cursor</code> method to CodeMirror instances, which can be used
751
to implement search/replace functionality. <code>query</code>
752
can be a regular expression or a string (only strings will match
753
across lines—if they contain newlines). <code>start</code>
754
provides the starting position of the search. It can be
755
a <code>{line, ch}</code> object, or can be left off to default
756
to the start of the document. <code>caseFold</code> is only
757
relevant when matching a string. It will cause the search to be
758
case-insensitive. A search cursor has the following methods:
760
<dt><code>findNext(), findPrevious() → boolean</code></dt>
761
<dd>Search forward or backward from the current position.
762
The return value indicates whether a match was found. If
763
matching a regular expression, the return value will be the
764
array returned by the <code>match</code> method, in case you
765
want to extract matched groups.</dd>
766
<dt><code>from(), to() → object</code></dt>
767
<dd>These are only valid when the last call
768
to <code>findNext</code> or <code>findPrevious</code> did
769
not return false. They will return <code>{line, ch}</code>
770
objects pointing at the start and end of the match.</dd>
771
<dt><code>replace(text)</code></dt>
772
<dd>Replaces the currently found match with the given text
773
and adjusts the cursor position to reflect the
777
<dt id="util_search"><a href="../lib/util/search.js"><code>search.js</code></a></dt>
778
<dd>Implements the search commands. CodeMirror has keys bound to
779
these by default, but will not do anything with them unless an
780
implementation is provided. Depends
781
on <code>searchcursor.js</code>, and will make use
782
of <a href="#util_dialog"><code>openDialog</code></a> when
783
available to make prompting for search queries less ugly.</dd>
784
<dt id="util_foldcode"><a href="../lib/util/foldcode.js"><code>foldcode.js</code></a></dt>
785
<dd>Helps with code folding.
786
See <a href="../demo/folding.html">the demo</a> for an example.
787
Call <code>CodeMirror.newFoldFunction</code> with a range-finder
788
helper function to create a function that will, when applied to
789
a CodeMirror instance and a line number, attempt to fold or
790
unfold the block starting at the given line. A range-finder is a
791
language-specific function that also takes an instance and a
792
line number, and returns an end line for the block, or null if
793
no block is started on that line. This file
794
provides <code>CodeMirror.braceRangeFinder</code>, which finds
795
blocks in brace languages (JavaScript, C, Java,
796
etc), <code>CodeMirror.indentRangeFinder</code>, for languages
797
where indentation determines block structure (Python, Haskell),
798
and <code>CodeMirror.tagRangeFinder</code>, for XML-style
800
<dt id="util_runmode"><a href="../lib/util/runmode.js"><code>runmode.js</code></a></dt>
801
<dd>Can be used to run a CodeMirror mode over text without
802
actually opening an editor instance.
803
See <a href="../demo/runmode.html">the demo</a> for an
805
<dt id="util_simple-hint"><a href="../lib/util/simple-hint.js"><code>simple-hint.js</code></a></dt>
806
<dd>Provides a framework for showing autocompletion hints.
807
Defines <code>CodeMirror.simpleHint</code>, which takes a
808
CodeMirror instance and a hinting function, and pops up a widget
809
that allows the user to select a completion. Hinting functions
810
are function that take an editor instance, and return
811
a <code>{list, from, to}</code> object, where <code>list</code>
812
is an array of strings (the completions), and <code>from</code>
813
and <code>to</code> give the start and end of the token that is
814
being completed. Depends
815
on <code>lib/util/simple-hint.css</code>.</dd>
816
<dt id="util_javascript-hint"><a href="../lib/util/javascript-hint.js"><code>javascript-hint.js</code></a></dt>
817
<dd>Defines <code>CodeMirror.javascriptHint</code>
818
and <code>CodeMirror.coffeescriptHint</code>, which are simple
819
hinting functions for the JavaScript and CoffeeScript
821
<dt id="util_match-highlighter"><a href="../lib/util/match-highlighter.js"><code>match-highlighter.js</code></a></dt>
822
<dd>Adds a <code>matchHighlight</code> method to CodeMirror
823
instances that can be called (typically from
824
a <a href="#option_onCursorActivity"><code>onCursorActivity</code></a>
825
handler) to highlight all instances of a currently selected word
826
with the a classname given as a first argument to the method.
828
the <a href="#util_searchcursor"><code>searchcursor</code></a>
829
add-on. Demo <a href="../demo/matchhighlighter.html">here</a>.</dd>
830
<dt id="util_closetag"><a href="../lib/util/closetag.js"><code>closetag.js</code></a></dt>
831
<dd>Provides utility functions for adding automatic tag closing
833
the <a href="../demo/closetag.html">demo</a>.</dd>
836
<h2 id="modeapi">Writing CodeMirror Modes</h2>
838
<p>Modes typically consist of a single JavaScript file. This file
839
defines, in the simplest case, a lexer (tokenizer) for your
840
language—a function that takes a character stream as input,
841
advances it past a token, and returns a style for that token. More
842
advanced modes can also handle indentation for the language.</p>
844
<p id="defineMode">The mode script should
845
call <code>CodeMirror.defineMode</code> to register itself with
846
CodeMirror. This function takes two arguments. The first should be
847
the name of the mode, for which you should use a lowercase string,
848
preferably one that is also the name of the files that define the
849
mode (i.e. <code>"xml"</code> is defined <code>xml.js</code>). The
850
second argument should be a function that, given a CodeMirror
851
configuration object (the thing passed to
852
the <code>CodeMirror</code> function) and an optional mode
853
configuration object (as in
854
the <a href="#option_mode"><code>mode</code></a> option), returns
857
<p>Typically, you should use this second argument
858
to <code>defineMode</code> as your module scope function (modes
859
should not leak anything into the global scope!), i.e. write your
860
whole mode inside this function.</p>
862
<p>The main responsibility of a mode script is <em>parsing</em>
863
the content of the editor. Depending on the language and the
864
amount of functionality desired, this can be done in really easy
865
or extremely complicated ways. Some parsers can be stateless,
866
meaning that they look at one element (<em>token</em>) of the code
867
at a time, with no memory of what came before. Most, however, will
868
need to remember something. This is done by using a <em>state
869
object</em>, which is an object that is always passed when
870
reading a token, and which can be mutated by the tokenizer.</p>
872
<p id="startState">Modes that use a state must define
873
a <code>startState</code> method on their mode object. This is a
874
function of no arguments that produces a state object to be used
875
at the start of a document.</p>
877
<p id="token">The most important part of a mode object is
878
its <code>token(stream, state)</code> method. All modes must
879
define this method. It should read one token from the stream it is
880
given as an argument, optionally update its state, and return a
881
style string, or <code>null</code> for tokens that do not have to
882
be styled. For your styles, you can either use the 'standard' ones
883
defined in the themes (without the <code>cm-</code> prefix), or
884
define your own (as the <a href="../mode/diff/index.html">diff</a>
885
mode does) and have people include a custom CSS file for your
888
<p id="StringStream">The stream object encapsulates a line of code
889
(tokens may never span lines) and our current position in that
890
line. It has the following API:</p>
893
<dt><code>eol() → boolean</code></dt>
894
<dd>Returns true only if the stream is at the end of the
896
<dt><code>sol() → boolean</code></dt>
897
<dd>Returns true only if the stream is at the start of the
900
<dt><code>peek() → character</code></dt>
901
<dd>Returns the next character in the stream without advancing
902
it. Will return <code>undefined</code> at the end of the
904
<dt><code>next() → character</code></dt>
905
<dd>Returns the next character in the stream and advances it.
906
Also returns <code>undefined</code> when no more characters are
909
<dt><code>eat(match) → character</code></dt>
910
<dd><code>match</code> can be a character, a regular expression,
911
or a function that takes a character and returns a boolean. If
912
the next character in the stream 'matches' the given argument,
913
it is consumed and returned. Otherwise, <code>undefined</code>
915
<dt><code>eatWhile(match) → boolean</code></dt>
916
<dd>Repeatedly calls <code>eat</code> with the given argument,
917
until it fails. Returns true if any characters were eaten.</dd>
918
<dt><code>eatSpace() → boolean</code></dt>
919
<dd>Shortcut for <code>eatWhile</code> when matching
921
<dt><code>skipToEnd()</code></dt>
922
<dd>Moves the position to the end of the line.</dd>
923
<dt><code>skipTo(ch) → boolean</code></dt>
924
<dd>Skips to the next occurrence of the given character, if
925
found on the current line (doesn't advance the stream if the
926
character does not occur on the line). Returns true if the
927
character was found.</dd>
928
<dt><code>match(pattern, consume, caseFold) → boolean</code></dt>
930
multi-character <code>eat</code>—if <code>consume</code> is true
931
or not given—or a look-ahead that doesn't update the stream
932
position—if it is false. <code>pattern</code> can be either a
933
string or a regular expression starting with <code>^</code>.
934
When it is a string, <code>caseFold</code> can be set to true to
935
make the match case-insensitive. When successfully matching a
936
regular expression, the returned value will be the array
937
returned by <code>match</code>, in case you need to extract
940
<dt><code>backUp(n)</code></dt>
941
<dd>Backs up the stream <code>n</code> characters. Backing it up
942
further than the start of the current token will cause things to
943
break, so be careful.</dd>
944
<dt><code>column() → integer</code></dt>
945
<dd>Returns the column (taking into account tabs) at which the
946
current token starts. Can be used to find out whether a token
947
starts a new line.</dd>
948
<dt><code>indentation() → integer</code></dt>
949
<dd>Tells you how far the current line has been indented, in
950
spaces. Corrects for tab characters.</dd>
952
<dt><code>current() → string</code></dt>
953
<dd>Get the string between the start of the current token and
954
the current stream position.</dd>
957
<p id="blankLine">By default, blank lines are simply skipped when
958
tokenizing a document. For languages that have significant blank
959
lines, you can define a <code>blankLine(state)</code> method on
960
your mode that will get called whenever a blank line is passed
961
over, so that it can update the parser state.</p>
963
<p id="copyState">Because state object are mutated, and CodeMirror
964
needs to keep valid versions of a state around so that it can
965
restart a parse at any line, copies must be made of state objects.
966
The default algorithm used is that a new state object is created,
967
which gets all the properties of the old object. Any properties
968
which hold arrays get a copy of these arrays (since arrays tend to
969
be used as mutable stacks). When this is not correct, for example
970
because a mode mutates non-array properties of its state object, a
971
mode object should define a <code>copyState</code> method,
972
which is given a state and should return a safe copy of that
975
<p id="compareStates">By default, CodeMirror will stop re-parsing
976
a document as soon as it encounters a few lines that were
977
highlighted the same in the old parse as in the new one. It is
978
possible to provide an explicit way to test whether a state is
979
equivalent to another one, which CodeMirror will use (instead of
980
the unchanged-lines heuristic) to decide when to stop
981
highlighting. You do this by providing
982
a <code>compareStates</code> method on your mode object, which
983
takes two state arguments and returns a boolean indicating whether
984
they are equivalent. See the XML mode, which uses this to provide
985
reliable highlighting of bad closing tags, as an example.</p>
987
<p id="indent">If you want your mode to provide smart indentation
988
(though the <a href="#indentLine"><code>indentLine</code></a>
989
method and the <code>indentAuto</code>
990
and <code>newlineAndIndent</code> commands, which keys can be
991
<a href="#option_extraKeys">bound</a> to), you must define
992
an <code>indent(state, textAfter)</code> method on your mode
995
<p>The indentation method should inspect the given state object,
996
and optionally the <code>textAfter</code> string, which contains
997
the text on the line that is being indented, and return an
998
integer, the amount of spaces to indent. It should usually take
999
the <a href="#option_indentUnit"><code>indentUnit</code></a>
1000
option into account.</p>
1002
<p id="electricChars">Finally, a mode may define
1003
an <code>electricChars</code> property, which should hold a string
1004
containing all the characters that should trigger the behaviour
1006
the <a href="#option_electricChars"><code>electricChars</code></a>
1009
<p>So, to summarize, a mode <em>must</em> provide
1010
a <code>token</code> method, and it <em>may</em>
1011
provide <code>startState</code>, <code>copyState</code>,
1012
<code>compareStates</code>, and <code>indent</code> methods. For
1013
an example of a trivial mode, see
1014
the <a href="../mode/diff/diff.js">diff mode</a>, for a more involved
1015
example, see the <a href="../mode/clike/clike.js">C-like
1018
<p>Sometimes, it is useful for modes to <em>nest</em>—to have one
1019
mode delegate work to another mode. An example of this kind of
1020
mode is the <a href="../mode/htmlmixed/htmlmixed.js">mixed-mode HTML
1021
mode</a>. To implement such nesting, it is usually necessary to
1022
create mode objects and copy states yourself. To create a mode
1023
object, there are <code>CodeMirror.getMode(options,
1024
parserConfig)</code>, where the first argument is a configuration
1025
object as passed to the mode constructor function, and the second
1026
argument is a mode specification as in
1027
the <a href="#option_mode"><code>mode</code></a> option. To copy a
1028
state object, call <code>CodeMirror.copyState(mode, state)</code>,
1029
where <code>mode</code> is the mode that created the given
1032
<p>To make indentation work properly in a nested parser, it is
1033
advisable to give the <code>startState</code> method of modes that
1034
are intended to be nested an optional argument that provides the
1035
base indentation for the block of code. The JavaScript and CSS
1036
parser do this, for example, to allow JavaScript and CSS code
1037
inside the mixed-mode HTML mode to be properly indented.</p>
1039
<p>Finally, it is possible to associate your mode, or a certain
1040
configuration of your mode, with
1041
a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type. For
1042
example, the JavaScript mode associates itself
1043
with <code>text/javascript</code>, and its JSON variant
1044
with <code>application/json</code>. To do this,
1045
call <code>CodeMirror.defineMIME(mime, modeSpec)</code>,
1046
where <code>modeSpec</code> can be a string or object specifying a
1047
mode, as in the <a href="#option_mode"><code>mode</code></a>
1050
</div><div class="rightsmall blk">
1055
<li><a href="#overview">Overview</a></li>
1056
<li><a href="#usage">Basic Usage</a></li>
1057
<li><a href="#config">Configuration</a></li>
1058
<li><a href="#keymaps">Keymaps</a></li>
1059
<li><a href="#styling">Customized Styling</a></li>
1060
<li><a href="#api">Programming API</a></li>
1061
<li><a href="#addons">Add-ons</a></li>
1062
<li><a href="#modeapi">Writing CodeMirror Modes</a></li>
1067
<div style="height: 2em"> </div>