Inside the editor, the tab key is used to re-indent the current selection (or the current line when nothing is selected), and pressing enter will, apart from inserting a line break, automatically indent the new line. Pressing control-enter will cause the whole buffer to be re-coloured, which can be helpful when some colouring has become out-of-date without the editor noticing it.
The editor sports an undo/redo system, accessible with control-z (undo) and control-y (redo). Safari will not allow client scripts to capture control-z presses, but you can use control-backspace instead on that browser.
The key-combination control-[ triggers a paren-blink: If the cursor is directly after a '(', ')', '[', ']', '{', or '}', the editor looks for the matching character, and highlights these characters for a moment. There is an option to enable this to happen any time the user types something or moves the cursor.
To use CodeMirror in a document, you should add a script tag to
load codemirror.js
. This
adds two objects to your environment, CodeMirror
and
CodeMirrorConfig
. The first is the interface to the
editor, the second can be used to configure it. (Note that this is
the only name-space pollution you can expect from CodeMirror --
all other cruft is kept inside the IFRAMEs that it creates when
you open an editor.)
To add an editor to a document, you must choose a place, a parser, and a style-sheet for it. For example, to append an XML editor to the body of the document, you do:
var editor = new CodeMirror(document.body, { parserfile: "parsexml.js", stylesheet: "xmlcolors.css" });
The first argument to the CodeMirror
constructor
can be a DOM node, in which case the editor gets appended to that
node, or a function, which will be called with the IFRAME node as
argument, and which is expected to place that node somewhere in
the document.
The second (optional) argument is an object that specifies
options. A set of default options (see below) is present in the
CodeMirrorConfig
object, but each instance of the
editor can be given a set of specific options to override these
defaults. In this case, we specified that the parser should be
loaded from the "parsexml.js"
file, and
that "xmlcolors.css"
should be used to specify the colours of the code.
Another example:
var editor = new CodeMirror(CodeMirror.replace("inputfield"), { parserfile: ["tokenizejavascript.js", "parsejavascript.js"], path: "lib/codemirror/js/", stylesheet: "lib/codemirror/css/jscolors.css", content: document.getElementById("inputfield").value });
Here we use the utility function
CodeMirror.replace
to create a function that will
replace a node in the current document (given either directly or
by ID) with the editor. We also select the JavaScript parser this
time, and give a path
option to tell the editor that
its files are not located in the same directory as the current
HTML page, but in "lib/codemirror/"
.
There is a function
CodeMirror.isProbablySupported()
that causes some
1998-style browser detection to happen, returning
false
if CodeMirror is probably not supported on the
browser, true
if it probably is, and
null
if it has no idea. As the name suggests, this is
not something you can rely on, but it's usually better than
nothing.
Another utility function, CodeMirror.fromTextArea
,
will, given a textarea node or the id of such a node, hide the
textarea and replace it with a CodeMirror frame. If the textarea
was part of a form, an onsubmit
handler will be
registered with this form, which will load the content of the
editor into the textarea, so that it can be submitted as normal.
This function optionally takes a configuration object as second
argument.
var editor = CodeMirror.fromTextArea("inputfield", { parserfile: ["tokenizejavascript.js", "parsejavascript.js"], path: "lib/codemirror/js/", stylesheet: "lib/codemirror/css/jscolors.css" });
The reason that the script path has to be configured is that CodeMirror will load in a bunch of extra files when an editor is created (the parser script, among others). To be able to do this, it has to know where to find them. These are all the JavaScript files that are part of CodeMirror itself:
codemirror.js
editor.js
util.js
undo.js
stringstream.js
select.js
tokenize.js
Most of these are rather full of comments, which can be useful
when you are trying to figure out how they work, but wastes a lot
of bandwidth in a production system. Take a look at the
description of the basefiles
option below if you want
to concatenate and minimise the library.
Apart from these, there are files that implement the various
parsers. These all start with either parse
or
tokenize
.
There are three ways to configure CodeMirror:
CodeMirrorConfig
object
before loading codemirror.js
, the
configuration options in that object will override the
defaults.CodeMirrorConfig
object, configuration defaults can
be overridden after loading codemirror.js
.CodeMirror
constructor can be given a second
argument, an object, which will override some options for just
that editor. Options not mentioned in this object will default to
the values in the CodeMirrorConfig
object.The options that can be specified are these (most have sensible
defaults specified in codemirror.js
):
stylesheet
jscolors.css
for an
example.path
parserfile
basefiles
["util.js", "stringstream.js", "select.js", "undo.js",
"editor.js", "tokenize.js"]
, but if you put them all into
a single file to reduce latency, or add some functionality, you
might have to adjust that.iframeClass
null
.passDelay
passTime
continuousScanning
false
, scanning is
disabled. When set to a number, say N
, a
'background' process will scan the document for
passTime
(see above) milliseconds every
N
milliseconds, regardless of whether anything
changed. This makes sure non-local changes propagate through the
document, and will help keep everything consistent. It does add
extra processing cost, even for an idle editor. Default value is
false
.autoMatchParens
true
,
will cause parens to be matched every time a key is pressed or
the user clicks on the document. Defaults to false
.
Might be expensive for big documents.saveFunction
null
.undoDepth
onChange
undoDelay
width
, height
"600px"
or "100%"
).disableSpellcheck
true
, since for most code spell-checking
is useless.textWrapping
true
.lineNumbers
CodeMirror-line-numbers
CSS class (in the outer
document) to configure the width, font, colors, etcetera for the
line-number DIV. You have to make sure that lines in the
numbering element have the same height as lines in the editor.
This is most easily done by giving them both the same font and
an absolute ('pt' or 'px') font size. This option defaults to
false
. When enabling this, you have to disable
textWrapping
, since the line numbers don't take
wrapped lines into account.indentUnit
2
.tabMode
"indent"
"spaces"
"default"
"shift"
indentUnit
deeper, pressing shift-tab or ctrl-tab (whichever your browser
does not interfere with), un-indents it.reindentOnLoad
true
,
this causes the content of the editor to be reindented
immediately when the editor loads. Defaults to
false
.readOnly
true
,
the document is not editable.initCallback
cursorActivity
activeTokens
(spanNode, tokenObject,
editor)
arguments whenever a new token node is being
added to the document. Can be used to do things like add event
handlers to nodes. Should not change the DOM structure
of the node (so no turning the span into a link), since this
will greatly confuse the editor.parserConfig
content
options
object passed to
individual editors as they are created.(If you want to use a CodeMirror parser to highlight a piece of
text, without creating an editor, see this example, and the highlight.js
script.)
The following parsers come with the distribution of CodeMirror:
parsexml.js
(demo)useHTMLKludges
configuration option (see the
parserConfig
option
above), which specifies whether the content of the editor is
HTML or XML, and things like self-closing tags (br
,
img
) exist. This defaults to true
.
Example colours for the styles that this parser uses are defined
in css/xmlcolors.css
.tokenizejavascript.js
,
parseejavascript.js
(demo)css/jscolors.css
parsecss.js
(demo)css/csscolors.css
parsehtmlmixed.js
(demo)parserfile
option looks something
like ["parsexml.js", "parsecss.js",
"tokenizejavascript.js", "parsejavascript.js",
"parsehtmlmixed.js"]
.parsesparql.js
(demo)css/sparqlcolors.css
parsedummy.js
contrib/php/js/parsephp.js
(demo)contrib/python/js/parsepython.js
(demo)contrib/lua/js/parselua.js
(demo)To be as flexible as possible, CodeMirror implements a very
plain editable field, without any accompanying buttons, bells, and
whistles. CodeMirror
objects do, however, provide a
number of methods that make it possible to add extra functionality
around the editor. mirrorframe.js
provides a
basic example of their usage.
getCode()
→
string
setCode(string)
focus()
currentLine()
→
number
jumpToLine(number)
selection()
→
string
replaceSelection(string)
reindent()
reindentSelection()
getSearchCursor(string, atCursor)
→
cursor
true
)
or at the start of the document (false
). Returns an
object that provides an interface for searching. Call its
findNext()
method to search for an occurrence of
the given string. This returns true
if something is
found, or false
if the end of document is reached.
When an occurrence has been found, you can call
select()
to select it, or
replace(string)
to replace it with a given string.
Note that letting the user change the document, or
programmatically changing it in any way except for calling
replace
on the cursor itself, might cause a cursor
object to skip back to the beginning of the document.undo()
redo()
historySize() → object
{undo, redo}
object holding the sizes of the undo
and redo histories.clearHistory()
grabKeys(callback, filter)
normalizeEvent
in util.js
) keydown
event object. If a second argument is given, this will be used
to determine which events to apply the callback to. It should
take a key code (as in event.keyCode
), and return a
boolean, where true
means the event should be
routed to the callback, and false
leaves the key to
perform its normal behaviour.ungrabKeys()
grabKeys
.setParser(name)
CSSParser
).For detailed interaction with the content of the editor,
CodeMirror exposes a line-oriented interface, which allows you to
inspect and manipulate the document line by line. Line handles
should be considered opaque (they are in fact the BR
nodes at the start of the line), except that the value
false
(but not null
) always
denotes an invalid value. Since changing the document might cause
some line handles to become invalid, every function that takes
them as argument can throw
CodeMirror.InvalidLineHandle
. These are the relevant
methods:
cursorPosition(start)
→
object
{line,
character}
object representing the cursor position.
start
defaults to true
and determines
if the startpoint or the endpoint of the selection is used.firstLine()
→
handle
lastLine()
→
handle
nextLine(handle)
→
handle
false
if that was the last line.prevLine(handle)
→
handle
false
if that was the first line.nthLine(number)
→
handle
false
if there is no such line.lineContent(handle)
→
string
setLineContent(handle, string)
lineNumber(handle)
→
number
selectLines(startHandle, startOffset,
endHandle, endOffset)
endHandle
and
endOffset
can be omitted to just place the cursor
somewhere without selecting any text.insertIntoLine(handle, position,
text)
position
can be an integer, specifying the position
in the line where the text should be inserted, or the string
"end"
, for the end of the line.A parser is implemented by one or more files (see
parserfile
above) which, when loaded, add a
Parser
object to the Editor
object
defined by editor.js
. This
object must support the following interface:
make(stream)
stringstream.js
),
creates a parser. The behaviour of this parser is described
below.electricChars
"{}"
for c-like languages).configure(object)
parserConfig
option, it will be
called with the value of that option.firstIndentation(chars, current,
direction)
0
is used.When the make
method is called with a string
stream, it should return a MochiKit-style iterator: an object with
a next
method, which will raise
StopIteration
when it is at its end (see this
for details). This iterator, when called, will consume input from
the string stream, and produce a token object.
Token objects represent a single significant piece of the text
that is being edited. A token object must have a
value
property holding the text it stands for, and a
style
property with the CSS class that should be used
to colour this element. This can be anything, except that any
whitespace at the start of a line should always have
class "whitespace"
: The editor must be able to
recognize these when it indents lines. Furthermore, each newline
character must have its own separate token, which has an
indentation
property holding a function that can be
used to determine the proper indentation level for the next line.
This function optionally takes the text in the first token of the
next line, the current indentation of the line, and the
'direction' of the indentation as arguments, which it can use to
adjust the indentation level. The direction argument is only
useful for modes in which lines do not have a fixed indentation,
and can be modified by multiple tab presses. It is
null
for 'default' indentations (like what happens
when the user presses enter), true
for regular tab
presses, and false
for control-tab or shift-tab.
So far this should be pretty easy. The hard part is that this
iterator must also have a copy
method. This method,
called without arguments, returns a function representing the
current state of the parser. When this state function is later
called with a string stream as its argument, it returns a parser
object that resumes parsing using the old state and the new input
stream. It may assume that only one parser is active at a time,
and can clobber the state of the old parser if it wants.
For examples, see parsejavascript.js
,
parsexml.js
, and parsecss.js
.