/* User manual and reference guide */
CodeMirror is a code-editor component that can be embedded in Web pages. The core library provides only the editor component, no accompanying buttons, auto-completion, or other IDE functionality. It does provide a rich API on top of which such functionality can be straightforwardly implemented. See the add-ons included in the distribution, and the CodeMirror UI project, for reusable implementations of extra features.
CodeMirror works with language-specific modes. Modes are
JavaScript programs that help color (and optionally indent) text
written in a given language. The distribution comes with a number
of modes (see the mode/
directory), and it isn't hard to write new
ones for other languages.
The easiest way to use CodeMirror is to simply load the script
and style sheet found under lib/
in the distribution,
plus a mode script from one of the mode/
directories.
(See the compression helper for an
easy way to combine scripts.) For example:
<script src="lib/codemirror.js"></script> <link rel="stylesheet" href="../lib/codemirror.css"> <script src="mode/javascript/javascript.js"></script>
Having done this, an editor instance can be created like this:
var myCodeMirror = CodeMirror(document.body);
The editor will be appended to the document body, will start
empty, and will use the mode that we loaded. To have more control
over the new editor, a configuration object can be passed
to CodeMirror
as a second argument:
var myCodeMirror = CodeMirror(document.body, { value: "function myScript(){return 100;}\n", mode: "javascript" });
This will initialize the editor with a piece of code already in it, and explicitly tell it to use the JavaScript mode (which is useful when multiple modes are loaded). See below for a full discussion of the configuration options that CodeMirror accepts.
In cases where you don't want to append the editor to an
element, and need more control over the way it is inserted, the
first argument to the CodeMirror
function can also
be a function that, when given a DOM element, inserts it into the
document somewhere. This could be used to, for example, replace a
textarea with a real editor:
var myCodeMirror = CodeMirror(function(elt) { myTextArea.parentNode.replaceChild(elt, myTextArea); }, {value: myTextArea.value});
However, for this use case, which is a common way to use CodeMirror, the library provides a much more powerful shortcut:
var myCodeMirror = CodeMirror.fromTextArea(myTextArea);
This will, among other things, ensure that the textarea's value is updated with the editor's contents when the form (if it is part of a form) is submitted. See the API reference for a full description of this method.
Both the CodeMirror
function and
its fromTextArea
method take as second (optional)
argument an object containing configuration options. Any option
not supplied like this will be taken
from CodeMirror.defaults
, an object containing the
default options. You can update this object to change the defaults
on your page.
Options are not checked in any way, so setting bogus option values is bound to lead to odd errors.
These are the supported options:
value (string or Doc)
mode (string or object)
name
property that names the mode (for
example {name: "javascript", json: true}
). The demo
pages for each mode contain information about what configuration
parameters the mode supports. You can ask CodeMirror which modes
and MIME types have been defined by inspecting
the CodeMirror.modes
and CodeMirror.mimeModes
objects. The first maps
mode names to their constructors, and the second maps MIME types
to mode specs.theme (string)
.cm-s-[name]
styles is loaded (see
the theme
directory in the
distribution). The default is "default"
, for which
colors are included in codemirror.css
. It is
possible to use multiple theming classes at once—for
example "foo bar"
will assign both
the cm-s-foo
and the cm-s-bar
classes
to the editor.indentUnit (integer)
smartIndent (boolean)
tabSize (integer)
indentWithTabs (boolean)
tabSize
spaces should be replaced by N tabs. Default is false.electricChars (boolean)
rtlMoveVisually (boolean)
false
on Windows, and true
on other platforms.keyMap (string)
"default"
, which is the only keymap defined
in codemirror.js
itself. Extra keymaps are found in
the keymap
directory. See
the section on keymaps for more
information.extraKeys (object)
keyMap
. Should be
either null, or a valid keymap value.lineWrapping (boolean)
false
(scroll).lineNumbers (boolean)
firstLineNumber (integer)
lineNumberFormatter (function)
gutters (array)
width
(and optionally a
background), and which will be used to draw the background of
the gutters. May include
the CodeMirror-linenumbers
class, in order to
explicitly set the position of the line number gutter (it will
default to be to the right of all other gutters). These class
names are the keys passed
to setGutterMarker
.fixedGutter (boolean)
readOnly (boolean)
"nocursor"
is given (instead of
simply true
), focusing of the editor is also
disallowed.showCursorWhenSelecting (boolean)
undoDepth (integer)
tabindex (integer)
autofocus (boolean)
fromTextArea
is
used, and no explicit value is given for this option, it will be
set to true when either the source textarea is focused, or it
has an autofocus
attribute and no other element is
focused.Below this a few more specialized, low-level options are listed. These are only useful in very specific situations, you might want to skip them the first time you read this manual.
dragDrop (boolean)
onDragEvent (function)
dragenter
, dragover
,
or drop
event. It will be passed the editor instance
and the event object as arguments. The callback can choose to
handle the event itself, in which case it should
return true
to indicate that CodeMirror should not
do anything further.onKeyEvent (function)
keydown
, keyup
,
and keypress
event that CodeMirror captures. It
will be passed two arguments, the editor instance and the key
event. This key event is pretty much the raw key event, except
that a stop()
method is always added to it. You
could feed it to, for example, jQuery.Event
to
further normalize it.keydown
does not stop
the keypress
from firing, whereas on others it
does. If you respond to an event, you should probably inspect
its type
property and only do something when it
is keydown
(or keypress
for actions
that need character data).cursorBlinkRate (number)
cursorHeight (number)
0.85
),
which causes the cursor to not reach all the way to the bottom
of the line, looks betterworkTime, workDelay (number)
workTime
milliseconds, and then use
timeout to sleep for workDelay
milliseconds. The
defaults are 200 and 300, you can change these options to make
the highlighting more or less aggressive.pollInterval (number)
flattenSpans (boolean)
viewportMargin (integer)
Infinity
to make sure the whole document is
always rendered, and thus the browser's text search works on it.
This will have bad effects on performance of big
documents.A CodeMirror instance emits a number of events, which allow
client code to react to various situations. These are registered
with the on
method (and
removed with the off
method). These are the events that fire on the instance object.
The name of the event is followed by the arguments that will be
passed to the handler. The instance
argument always
refers to the editor instance.
"change" (instance, changeObj)
changeObj
is a {from, to, text,
next}
object containing information about the changes
that occurred as second argument. from
and to
are the positions (in the pre-change
coordinate system) where the change started and ended (for
example, it might be {ch:0, line:18}
if the
position is at the beginning of line #19). text
is
an array of strings representing the text that replaced the
changed range (split by line). If multiple changes happened
during a single operation, the object will have
a next
property pointing to another change object
(which may point to another, etc)."beforeChange" (instance, change)
change
object
has from
, to
, and text
properties, as with
the "change"
event, but
never a next
property, since this is fired for each
individual change, and not batched per operation. It also
has update(from, to, text)
and cancel()
methods, which may be used to modify
or cancel the change. All three arguments to update
are optional, and can be left off to leave the existing value
for that field intact. Note: you may not do
anything from a "beforeChange"
handler that would
cause changes to the document or its visualization. Doing so
will, since this handler is called directly from the bowels of
the CodeMirror implementation, probably cause the editor to
become corrupted."cursorActivity" (instance)
"beforeSelectionChange" (instance, selection)
selection
parameter is an object
with head
and anchor
properties
holding {line, ch}
objects, which the handler can
read and update. Handlers for this event have the same
restriction
as "beforeChange"
handlers — they should not do anything to directly update the
state of the editor."viewportChange" (instance, from, to)
from
and to
arguments
give the new start and end of the viewport."gutterClick" (instance, line, gutter, clickEvent)
mousedown
event object as
fourth argument."focus", "blur" (instance)
"scroll" (instance)
"update" (instance)
It is also possible to register events on
other objects. Use CodeMirror.on(handle, "eventName",
func)
to register handlers on objects that don't have their
own on
method. Document objects (instances
of CodeMirror.Doc
) emit the
following events:
"change" (doc, changeObj)
changeObj
has a similar type as the
object passed to the
editor's "change"
event, but it never has a next
property, because
document change events are not batched (whereas editor change
events are)."beforeChange" (doc, change)
"cursorActivity" (doc)
"beforeSelectionChange" (doc, selection)
Line handles (as returned by, for
example, getLineHandle
)
support these events:
"delete" ()
"change" ()
Marked range handles, as returned
by markText
and setBookmark
, emit the
following events:
"clear" ()
clearOnEnter
or through a call to its clear()
method. Will only
be fired once per handle. Note that deleting the range through
text editing does not fire this event, because an undo
action might bring the range back into existence."hide" ()
"unhide" ()
Line widgets, returned
by addLineWidget
, fire
these events:
"redraw" ()
Keymaps are ways to associate keys with functionality. A keymap is an object mapping strings that identify the keys to functions that implement their functionality.
Keys are identified either by name or by character.
The CodeMirror.keyNames
object defines names for
common keys and associates them with their key codes. Examples of
names defined here are Enter
, F5
,
and Q
. These can be prefixed
with Shift-
, Cmd-
, Ctrl-
,
and Alt-
(in that order!) to specify a modifier. So
for example, Shift-Ctrl-Space
would be a valid key
identifier.
Alternatively, a character can be specified directly by
surrounding it in single quotes, for example '$'
or 'q'
. Due to limitations in the way browsers fire
key events, these may not be prefixed with modifiers.
The CodeMirror.keyMap
object associates keymaps
with names. User code and keymap definitions can assign extra
properties to this object. Anywhere where a keymap is expected, a
string can be given, which will be looked up in this object. It
also contains the "default"
keymap holding the
default bindings.
The values of properties in keymaps can be either functions of
a single argument (the CodeMirror instance), strings, or
false
. Such strings refer to properties of the
CodeMirror.commands
object, which defines a number of
common commands that are used by the default keybindings, and maps
them to functions. If the property is set to false
,
CodeMirror leaves handling of the key up to the browser. A key
handler function may return CodeMirror.Pass
to indicate
that it has decided not to handle the key, and other handlers (or
the default behavior) should be given a turn.
Keys mapped to command names that start with the
characters "go"
(which should be used for
cursor-movement actions) will be fired even when an
extra Shift
modifier is present (i.e. "Up":
"goLineUp"
matches both up and shift-up). This is used to
easily implement shift-selection.
Keymaps can defer to each other by defining
a fallthrough
property. This indicates that when a
key is not found in the map itself, one or more other maps should
be searched. It can hold either a single keymap or an array of
keymaps.
When a keymap contains a nofallthrough
property
set to true
, keys matched against that map will be
ignored if they don't match any of the bindings in the map (no
further child maps will be tried, and the default effect of
inserting a character will not occur).
Up to a certain extent, CodeMirror's look can be changed by
modifying style sheet files. The style sheets supplied by modes
simply provide the colors for that mode, and can be adapted in a
very straightforward way. To style the editor itself, it is
possible to alter or override the styles defined
in codemirror.css
.
Some care must be taken there, since a lot of the rules in this file are necessary to have CodeMirror function properly. Adjusting colors should be safe, of course, and with some care a lot of other things can be changed as well. The CSS classes defined in this file serve the following roles:
CodeMirror
CodeMirror-scroll
overflow: auto
+
fixed height). By default, it does. Setting
the CodeMirror
class to have height:
auto
and giving this class overflow-x: auto;
overflow-y: hidden;
will cause the editor
to resize to fit its
content.CodeMirror-focused
CodeMirror-gutters
CodeMirror-linenumbers
CodeMirror-linenumber
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
CodeMirror-cursor
CodeMirror-selected
span
elements
with this class.CodeMirror-matchingbracket
,
CodeMirror-nonmatchingbracket
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.
A lot of CodeMirror features are only available through its API. Thus, you need to write code (or use add-ons) 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.
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.
doc.getValue() → string
"\n"
).doc.setValue(string)
doc.getRange(from, to) → string
{line, ch}
objects. An optional third
argument can be given to indicate the line separator string to
use (defaults to "\n"
).doc.replaceRange(string, from, to)
from
and to
with the given string. from
and to
must be {line, ch}
objects. to
can be left off to simply insert the
string at position from
.doc.getLine(n) → string
n
.doc.setLine(n, text)
n
.doc.removeLine(n)
doc.lineCount() → number
doc.firstLine() → number
doc.lastLine() → number
doc.lineCount() - 1
respectively,
but for linked sub-views,
or documents instantiated with a non-zero
first line, it might return other values.doc.getLineHandle(num) → lineHandle
doc.getLineNumber(handle) → integer
null
when it is no longer in the
document).doc.eachLine(f) | doc.eachLine(start, end, f)
start
and end
line numbers are given, the range
from start
up to (not including) end
,
and call f
for each line, passing the line handle.
This is a faster way to visit a range of line handlers than
calling getLineHandle
for each of them. Note that line handles have
a text
property containing the line's content (as a
string).doc.markClean()
doc.isClean() → boolean
markClean
).doc.getSelection() → string
doc.replaceSelection(string)
doc.getCursor(start) → object
start
is a an optional string indicating which
end of the selection to return. It may
be "start"
, "end"
, "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.somethingSelected() → boolean
doc.setCursor(pos)
{line, ch}
object, or the line and the
character as two separate parameters.doc.setSelection(anchor, head)
anchor
and head
should be {line, ch}
objects. head
defaults to anchor
when
not given.doc.extendSelection(pos, pos2)
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. pos2
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).doc.setExtending(bool)
extendSelection
to leave the selection anchor in place.cm.findPosH(start, amount, unit, visually) → object
start
is a {line, ch}
object, amount
an integer (may be negative),
and unit
one of the
string "char"
, "column"
,
or "word"
. Will return a position that is produced
by moving amount
times the distance specified
by unit
. When visually
is true, motion
in right-to-left text will be visual rather than logical. When
the motion was clipped by hitting the end or start of the
document, the returned value will have a hitSide
property set to true.cm.findPosV(start, amount, unit) → object
findPosH
,
but used for vertical motion. unit
may
be "line"
or "page"
. The other
arguments and the returned value have the same interpretation as
they have in findPosH
.cm.setOption(option, value)
option
should the name of an option,
and value
should be a valid value for that
option.cm.getOption(option) → value
cm.addKeyMap(map)
extraKeys
option. Maps added in this way have a lower precedence
than extraKeys
, a higher precedence than the
base keyMap
, and
between them, the maps added earlier have a higher precedence
than those added later.cm.removeKeyMap(map)
addKeyMap
. Either
pass in the keymap object itself, or a string, which will be
compared against the name
property of the active
keymaps.cm.addOverlay(mode, options)
mode
can be a mode
spec or a mode object (an object with
a token
method).
The option
parameter is optional. If given it
should be an object. Currently, only the opaque
option is recognized. This 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.cm.removeOverlay(mode)
mode
parameter
to addOverlay
to remove
an overlay again.cm.on(type, func)
CodeMirror.on(object, type, func)
version
that allows registering of events on any object.cm.off(type, func)
CodeMirror.off(object, type,
func)
also exists.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, mode,
firstLineNumber)
constructor. The last two arguments are
optional and can be used to set a mode for the document and make
it start at a line number other than 0, respectively.
cm.getDoc() → doc
doc.getEditor() → editor
null
.cm.swapDoc(doc) → doc
doc.copy(copyHistory) → doc
copyHistory
is true, the history will also be
copied. Can not be called directly on an editor.doc.linkedDoc(options) → doc
from, to (integer)
mode (mode spec)
doc.unlinkDoc(doc)
doc.iterLinkedDocs(function)
doc.undo()
doc.redo()
doc.historySize() → object
{undo, redo}
properties,
both of which hold integers, indicating the amount of stored
undo and redo operations.doc.clearHistory()
doc.getHistory() → object
doc.setHistory(object)
getHistory
. Note that
this will have entirely undefined results if the editor content
isn't also the same as it was when getHistory
was
called.doc.markText(from, to, options) → object
from
and to
should
be {line, ch}
objects. The options
parameter is optional. When given, it should be an object that
may contain the following configuration options:
className (string)
inclusiveLeft (boolean)
inclusiveRight
(boolean)inclusiveLeft
,
but for the right side.atomic (boolean)
inclusiveLeft
and inclusiveRight
have a different meaning—they
will prevent the cursor from being placed respectively
directly before and directly after the range.collapsed (boolean)
clearOnEnter (boolean)
"clear"
event
fired on the range handle can be used to be notified when this
happens.replacedWith (dom node)
readOnly
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).startStyle
endStyle
startStyle
, but for the rightmost span.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, or undefined
if the
marker is no longer in the document, and
finally getOptions(copyWidget)
, which returns an
object representing the options for the marker.
If copyWidget
is given an true, it will clone the
value of
the replacedWith
option, if any.doc.setBookmark(pos, options) → object
find()
and clear()
. The first
returns the current position of the bookmark, if it is still in
the document, and the second explicitly removes the bookmark.
The options argument is optional. If given, the following
properties are recognized:
widget
replacedWith
option to markText
).insertLeft
doc.findMarksAt(pos) → array
doc.getAllMarks() → array
cm.setGutterMarker(line, gutterID, value) → lineHandle
gutters
option)
to the given value. Value can be either null
, to
clear the marker, or a DOM element, to set it. The DOM element
will be shown in the specified gutter next to the specified
line.cm.clearGutter(gutterID)
cm.addLineClass(line, where, class) → lineHandle
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), 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.cm.removeLineClass(line, where, class) → lineHandle
line
can be a
line handle or number. where
should be one
of "text"
, "background"
,
or "wrap"
(see addLineClass
). class
can be left off to remove all classes for the specified node, or
be a string to remove only a specific class.cm.lineInfo(line) → object
{line, handle, text,
gutterMarkers, textClass, bgClass, wrapClass, widgets}
,
where gutterMarkers
is an object mapping gutter IDs
to marker elements, and widgets
is an array
of line widgets attached to this
line, and the various class properties refer to classes added
with addLineClass
.cm.addWidget(pos, node, scrollIntoView)
node
, which should be an absolutely
positioned DOM node, into the editor, positioned right below the
given {line, ch}
position.
When scrollIntoView
is true, the editor will ensure
that the entire node is visible (if possible). To remove the
widget again, simply use DOM methods (move it somewhere else, or
call removeChild
on its parent).cm.addLineWidget(line, node, options) → object
line
should be either an integer or a
line handle, and node
should be a DOM node, which
will be displayed below the given line. options
,
when given, should be an object that configures the behavior of
the widget. The following options are supported (all default to
false):
coverGutter (boolean)
noHScroll (boolean)
above (boolean)
showIfHidden (boolean)
line
property
pointing at the line handle that it is associated with, and the following methods:
clear()
changed()
cm.setSize(width, height)
width
and height
height
can be either numbers (interpreted as pixels) or CSS units
("100%"
, for example). You can
pass null
for either of them to indicate that that
dimension should not be changed.cm.scrollTo(x, y)
null
or undefined
to have no effect.cm.getScrollInfo()
{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(pos)
pos
may be
either a {line, ch}
position, referring to a given
character, null
, to refer to the cursor, or
a {left, top, right, bottom}
object, in
editor-local coordinates.cm.cursorCoords(where, mode) → object
{left, top, bottom}
object
containing the coordinates of the cursor position.
If mode
is "local"
, they will be
relative to the top-left corner of the editable document. If it
is "page"
or not given, they are relative to the
top-left corner of the page. 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, mode) → object
pos
should be a {line, ch}
object. This differs from cursorCoords
in that
it'll give the size of the whole character, rather than just the
position that the cursor would have when it would sit at that
position.cm.coordsChar(object) → pos
{left, top}
object (in page coordinates),
returns the {line, ch}
position that corresponds to
it.cm.defaultTextHeight() → number
cm.getViewport() → object
{from, to}
object indicating the
start (inclusive) and end (exclusive) of the currently rendered
part of the document. In big documents, when most content is
scrolled out of view, CodeMirror will only render the visible
part, and a margin around it. See also
the viewportChange
event.cm.refresh()
When writing language-aware functionality, it can often be useful to hook into the knowledge thate the CodeMirror language mode has. See the section on modes for a more detailed description of how these work.
doc.getMode() → object
getOption("mode")
, which gives you
the mode specification, rather than the resolved, instantiated
mode object.cm.getTokenAt(pos) → object
{line, ch}
object). The
returned object has the following properties:
start
end
string
type
"keyword"
or "comment"
(may also be null).state
cm.getStateAfter(line) → state
cm.operation(func) → result
cm.indentLine(line, dir)
"smart"
) may be one of:
"prev"
"smart"
"prev"
otherwise."add"
"subtract"
doc.posFromIndex(index) → object
{line, ch}
object for a
zero-based index
who's value is relative to the start of the
editor's text. If the index
is out of range of the text then
the returned object is clipped to start or end of the text
respectively.doc.indexFromPos(object) → number
posFromIndex
.cm.focus()
cm.getInputField() → textarea
cm.getWrapperElement() → node
cm.getScrollerElement() → node
cm.getGutterElement() → node
The CodeMirror
object itself provides
several useful properties. Firstly, its version
property contains a string that indicates the version of the
library. For releases, this simply
contains "major.minor"
(for
example "2.33"
. For beta versions, " B"
(space, capital B) is added at the end of the string, for
development snapshots, " +"
(space, plus) is
added.
The CodeMirror.fromTextArea
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. A CodeMirror instance created this way has three
additional methods:
cm.save()
cm.toTextArea()
cm.getTextArea() → textarea
If you want to define extra methods in terms
of the CodeMirror API, it is possible to
use CodeMirror.defineExtension(name, value)
. This
will cause the given value (usually a method) to be added to all
CodeMirror instances created from then on.
Similarly, CodeMirror.defineOption(name,
default, updateFunc)
can be used to define new options for
CodeMirror. The updateFunc
will be called with the
editor instance and the new value when an editor is initialized,
and whenever the option is modified
through setOption
.
If your extention 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.
The addon
directory in the distribution contains a
number of reusable components that implement extra editor
functionality. In brief, they are:
dialog/dialog.js
openDialog
method to CodeMirror instances,
which can be called with an HTML fragment that provides the
prompt (should include an input
tag), and a
callback function that is called when text has been entered.
Depends on addon/dialog/dialog.css
.search/searchcursor.js
getSearchCursor(query, start, caseFold) →
cursor
method to CodeMirror instances, which can be used
to implement search/replace functionality. query
can be a regular expression or a string (only strings will match
across lines—if they contain newlines). 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. caseFold
is only
relevant when matching a string. It will cause the search to be
case-insensitive. A search cursor has the following methods:
findNext(), findPrevious() → boolean
match
method, in case you
want to extract matched groups.from(), to() → object
findNext
or findPrevious
did
not return false. They will return {line, ch}
objects pointing at the start and end of the match.replace(text)
search/search.js
searchcursor.js
, and will make use
of openDialog
when
available to make prompting for search queries less ugly.edit/matchbrackets.js
matchBrackets
which, when set
to true, causes matching brackets to be highlighted whenever the
cursor is next to them. It also adds a
method matchBrackets
that forces this to happen
once, and a method findMatchingBracket
that can be
used to run the bracket-finding algorithm that this uses
internally.edit/closebrackets.js
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)
to customize it. Demo
here.fold/foldcode.js
CodeMirror.newFoldFunction
with a range-finder
helper function to create a function that will, when applied to
a CodeMirror instance and a line number, attempt to fold or
unfold the block starting at the given line. A range-finder is a
language-specific function that also takes an instance and a
line number, and returns an range to be folded, or null if
no block is started on that line. This file
provides CodeMirror.braceRangeFinder
, which finds
blocks in brace languages (JavaScript, C, Java,
etc), CodeMirror.indentRangeFinder
, for languages
where indentation determines block structure (Python, Haskell),
and CodeMirror.tagRangeFinder
, for XML-style
languages.fold/collapserange.js
runmode/runmode.js
mode/overlay.js
CodeMirror.overlayMode
, which is used to
create such a mode. See this
demo for a detailed example.mode/multiplex.js
CodeMirror.multiplexingMode
which, when
given as first argument a mode object, and as other arguments
any number of {open, close, mode [, delimStyle]}
objects, will return a mode object that starts parsing using the
mode passed as first argument, but will switch to another mode
as soon as it encounters a string that occurs in one of
the open
fields of the passed objects. When in a
sub-mode, it will go back to the top mode again when
the close
string is encountered.
Pass "\n"
for open
or close
if you want to switch on a blank line.
When delimStyle
is specified, it will be the token
style returned for the delimiter tokens. The outer mode will not
see the content between the delimiters.
See this demo for an
example.hint/show-hint.js
CodeMirror.showHint
, which takes a
CodeMirror instance and a hinting function, and pops up a widget
that allows the user to select a completion. Hinting functions
are function that take an editor instance, and return
a {list, from, to}
object, where list
is an array of strings (the completions), and from
and to
give the start and end of the token that is
being completed. Depends
on addon/hint/show-hint.css
. See the other files in
the addon/hint
for
hint sources for various languages. Check
out the demo for an
example.match-highlighter.js
highlightSelectionMatches
option that
can be enabled to highlight all instances of a currently
selected word.
Demo here.lint/lint.js
json-lint.js
and javascript-lint.js
in the same directory). Defines a lintWith
option
that can be set to a warning source (for
example CodeMirror.javascriptValidator
). Depends
on addon/lint/lint.css
. A demo can be
found here.selection/mark-selection.js
CodeMirror-selectedtext
when the styleSelectedText
option
is enabled. Useful to change the colour of the selection (in addition to the background),
like in this demo.selection/active-line.js
styleActiveLine
option that, when enabled,
gives the wrapper of the active line the class CodeMirror-activeline
,
and adds a background with the class CodeMirror-activeline-background
.
is enabled. See the demo.edit/closetag.js
mode/loadmode.js
CodeMirror.requireMode(modename,
callback)
function that will try to load a given mode and
call the callback when it succeeded. You'll have to
set CodeMirror.modeURL
to a string that mode paths
can be constructed from, for
example "mode/%N/%N.js"
—the %N
's will
be replaced with the mode name. Also
defines CodeMirror.autoLoadMode(instance, mode)
,
which will ensure the given mode is loaded and cause the given
editor instance to refresh its mode when the loading
succeeded. See the demo.edit/continuecomment.js
newlineAndIndentContinueComment
that you can
bind Enter
to in order to have the editor prefix
new lines inside C-like block comments with an asterisk.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.
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.
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
sol() → boolean
peek() → character
null
at the end of the
line.next() → character
null
when no more characters are
available.eat(match) → character
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) → boolean
eat
with the given argument,
until it fails. Returns true if any characters were eaten.eatSpace() → boolean
eatWhile
when matching
white-space.skipToEnd()
skipTo(ch) → boolean
match(pattern, consume, caseFold) → boolean
eat
—if consume
is true
or not given—or a look-ahead that doesn't update the stream
position—if it is false. pattern
can be either a
string or a regular expression starting with ^
.
When it is a string, caseFold
can be set to true to
make the match case-insensitive. When successfully matching a
regular expression, the returned value will be the array
returned by match
, in case you need to extract
matched groups.backUp(n)
n
characters. Backing it up
further than the start of the current token will cause things to
break, so be careful.column() → integer
indentation() → integer
current() → string
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.
Finally, a mode may define
an electricChars
property, which should hold a string
containing all the characters that should trigger the behaviour
described for
the electricChars
option.
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 methods, 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 autoformatter
and 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.
Sometimes, it is useful to add or override mode
object properties from external code.
The CodeMirror.extendMode
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
.