/* User manual and reference guide */
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).
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" });
Instances created like this will have a
toTextArea()
method which removes them and restores
the text area they were based on, and a save()
method
which simply updates the textarea with the content of the
editor.
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 (see the compression API).
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. The set of active stylesheets can be changed in a
running editor with the setStylesheet
method, which
also takes a string or array of strings as argument.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.markParen
,unmarkParen
markParen
to a string, the name of the CSS
class that should be added to the bracket elements when they are
matched. Alternatively, you can provide an array of two strings,
where the first will be used for successful matches, and the
second for failing matches. You'll have to include some CSS file
(using the stylesheet
option) that defines these
classes. Alternatively, you can provide both
markParen
and unmarkParen
, and set
them to functions that will be called to style the bracket's
SPAN
elements. Both will get this element as their
first argument, and markParen
gets a second boolean
argument indicating whether a successful match was found. The
default behaviour, if these options are not supplied, is to make
the brackets bold and green (or red, if not matched).saveFunction
null
.undoDepth
setUndoDepth(depth)
method on CodeMirror
instances.onChange
undoDelay
width
, height
"600px"
or "100%"
). When
height
is set to dynamic
, the editor
will automatically resize to fit its contents. In this case, the
minHeight
option (an integer) is used to determine
the minimum height in pixels.disableSpellcheck
true
, since for most code spell-checking
is useless. Can be changed with the
setSpellCheck(on)
method.textWrapping
true
. Changeable with the
setTextWrapping(on)
method.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
. Changeable with the
setLineNumbers(on)
method.firstLineNumber
lineNumbers
is enabled, this determines the number
given to the first line. Default is 1
.lineNumberDelay
,
lineNumberTime
passDelay
and passTime
.onLineNumberClick
styleNumbers
(numberDIV,
lineNode, lineNum)
. It can then update the style of the
numberDIV
element based on either the BR node at
the start of the line (lineNode
, which is
null
for the first line), or the actual line number
(lineNum
). Note that it might get passed DIVs that
were already styled before (the DIVs are reused), so it has to
'reset' the style to the default for lines that don't need to be
styled.indentUnit
2
. Changeable in a running editor using
the setIndentUnit(spaces)
method.tabMode
"indent"
"default"
"shift"
indentUnit
deeper, pressing shift-tab, un-indents it."spaces"
"shift"
behaviour is used.setTabMode(mode)
method.enterMode
"indent"
"keep"
"flat"
setEnterMode
method can be used to change this
option in a running editor.electricChars
{
and
}
in C-like languages) on and off. Default is
on.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.domain
document.domain
should have inside of the iframe.
Used to prevent access issues in IE, where this value isn't
automatically inherited by iframes.noScriptCaching
true
to cause CodeMirror to add a changing dummy
parameter to the script URLs, which will force browsers to
reload them every time.onLoad
onCursorActivity
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
. Takes one
configuration option, json
, that can be set when
the editor content is JSON data. It causes every opening brace
to be treated as the start of an object, rather than a
block.parsecss.js
(demo)css/csscolors.css
parsehtmlmixed.js
(demo)parserfile
option looks something like ["parsexml.js", "parsecss.js",
"tokenizejavascript.js", "parsejavascript.js",
"parsehtmlmixed.js"]
. This parser accepts a configuration
object with a triggers
property to configure which
parser should be invoked for which tag. The default looks like
this (property names are tags, values are parser names):
{script: "JSParser", style: "CSSParser"}
parsesparql.js
(demo)css/sparqlcolors.css
parsedummy.js
contrib/php/js/parsephp.js
(demo)contrib/php/js/parsephphtmlmixed.js
,
which wraps this parser to allow mixed-mode HTML + PHP parsing.
This one takes a configuration parameter opening
,
which should contain an array of XML processing instruction
openings (<?php
, <?
etc) which
can be used to open a PHP block. Default is
["<?php"]
.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 and properties that make it possible to add
extra functionality around the editor. mirrorframe.js
provides
a basic example of their usage.
frame
win
wrapping
DIV
element
wrapped around the frame. This always has a CSS class of
CodeMirror-wrapping
.getCode()
→
string
setCode(string)
focus()
selection()
→
string
replaceSelection(string)
reindent()
reindentSelection()
getSearchCursor(pattern, startPos, caseFold)
→ cursor
false
(or left off) for the start of the
document, true
for the current cursor position, or
a {line, character}
object (as returned
by cursorPosition
, or created yourself using a line
handle and a number) to set a random position. The third
argument, a boolean, determines whether the search will be
case-sensitive. If it is not provided, the search will only be
case-sensitive if the search string contains uppercase
characters. Returns an object that provides an interface for
searching. Call its findNext()
and
findPrevious()
methods to search for an occurrence.
This returns true
if something is found, or
false
if the end or start of the document was
reached. When an occurrence has been found, you can call
select()
to select it, or
replace(string)
to replace it with a given string
(you can use \1 placeholders in this string if you matched a
regular expression). To find out where the match was found, call
the position()
method, which returns a {line,
character}
object. 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, parserConfig)
CSSParser
). The second argument is optional, and
can be used to pass a new parser configuration object.cursorCoords(start)
x
, y
, and yBot
(the
bottom of the cursor) properties. May return null
if the cursor position could not be determined (for example, if
the editor is not focused).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.cursorLine()
→
handle
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)
removeLine(handle)
lineNumber(handle)
→
number
jumpToLine(handle)
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
property 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
.