CodeMirror user manual

Contents

Basic Usage

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
Main interface, takes care of default configuration and the definition of editor frames. Include this in your HTML document.
editor.js
The code that takes care of reacting to user input, colouring text, and indenting lines.
util.js
A few generic utility functions.
undo.js
Implements the undo history for the editor.
stringstream.js
Objects for wrapping the textual input to the parser.
select.js
Some helper utilities for working with selected text and cursor positions.
tokenize.js
Helper framework for writing tokenisers.

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.

Configuration

There are three ways to configure CodeMirror:

The options that can be specified are these (most have sensible defaults specified in codemirror.js):

stylesheet
The file name of the style-sheet that should be used to colour the code in the editor frame. See jscolors.css for an example.
path
The path that is prefixed to script file names when they are loaded into an IFRAME. (Note that this is not applied to the style-sheet file name.)
parserfile
A file name string, or an array of strings that name the files containing the parser. See below for the interface that such a parser should implement.
basefiles
An array of strings naming the files containing the base CodeMirror functionality. Defaults to ["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.
linesPerPass
Specifies the maximum amount of lines that the highlighter tries to colour in one shot. Setting this too high will cause the code to 'freeze' the browser for noticeable intervals. Defaults to 30.
passDelay
Gives the amount of milliseconds between colouring passes. Defaults to 200.
continuousScanning
Configure continuous scanning of the document. When false, scanning is disabled. When set to a number, say N, a 'background' process will scan linesPerPass (see above) lines of the document 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
When 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
If given a function value, that function will be invoked when the user presses control-s. You should advise your Opera users to use control-shift-s instead, since plain control-s will bring up the 'save page' dialog. Defaults to null.
undoDepth
Maximum length of the undo history. Default is 50.
onChange
An optional function of zero arguments that gets called whenever the document is changed. Happens at undo-commit time, not instantaniously.
undoDelay
When nothing is done in the editor for this amount of milliseconds, pending changes get added to the undo history. Setting this lower will give the undo functionality a finer granularity. Defaults to 800.
width, height
The size of the editor frame, given as a style-sheet quantities (for example "600px" or "100%").
disableSpellcheck
Should the editor disable spell-checking on browsers that support it (Firefox 2+). Default is true, since for most code spell-checking is useless.
textWrapping
Can be used to disable or enable text-wrapping in the editor frame. Default is true.
lineNumbers
Show line numbers to the left of the editor. This requires you to specify a style for the 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
An integer that specifies the amount of spaces one 'level' of indentation should add. Default is 2.
tabMode
Determines what the effect of pressing tab is. Possibilities are:
"indent"
The default. Causes tab to adjust the indentation of the selection or current line using the parser's rules.
"spaces"
Pressing tab simply inserts four spaces.
"default"
CodeMirror does not interfere with the tab key, but leaves it to the browser to handle it. Binds shift-space to regular indentation behaviour.
"shift"
Pressing tab indents the current line (or selection) one indentUnit deeper, pressing shift-tab or ctrl-tab (whichever your browser does not interfere with), un-indents it.
readOnly
When set to true, the document is not editable.
initCallback
If set to a function, this will be called (with the editor object as its argument) after the editor has finished initialising.
cursorActivity
A function that is called every time the cursor moves, with the top-level node that the cursor is inside or next to as an argument. Can be used to have some controls react to the context of the cursor.
activeTokens
Can be set to a function that will be called with (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
An object value that is passed along to the parser to configure it. What this object should look like depends on the parser used.
content
The starting content of the editor. You'll probably not want to provide a global default for this, but add it to the options object passed to individual editors as they are created.

Parsers

The following parsers come with the distribution of CodeMirror:

parsexml.js
A HTML/XML parser. Takes a 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
The JavaScript parser. Example colours in css/jscolors.css
parsecss.js
A CSS parser. Styles in css/csscolors.css
parsehtmlmixed.js
A mixed-mode HTML parser. Requires the XML, JavaScript, and CSS parsers to also be loaded, so your parserfile option looks something like ["parsexml.js", "parsecss.js", "tokenizejavascript.js", "parsejavascript.js", "parsehtmlmixed.js"].
parsesparql.js
Parses the SPARQL query language. Example styles in css/sparqlcolors.css

Programming Interface

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
Returns the current content of the editor, as a string.
setCode(string)
Replaces the current content of the editor with the given value.
focus()
Gives focus to the editor frame.
currentLine()number
Returns the line on which the cursor is currently sitting. (Deprecated, see the line-based interface below)
jumpToLine(number)
Moves the cursor to the start of the given line. (Deprecated)
selection()string
Returns the text that is currently selected in the editor.
replaceSelection(string)
Replaces the currently selected text with the given string. Will also cause the editor frame to gain focus.
reindent()
Automatically re-indent the whole document.
getSearchCursor(string, atCursor)cursor
The first argument indicates the string that should be searched for, and the second indicates whether searching should start at the 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()
Undo one changeset, if available.
redo()
Redo one changeset, if available.
historySize() → object
Get a {undo, redo} object holding the sizes of the undo and redo histories.
grabKeys(callback, filter)
Route keyboard input in the editor to a callback function. This function is given a slightly normalised (see 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()
Revert the effect of grabKeys.

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
Retrieve a {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
Get the first line of the document.
lastLine()handle
The last line.
nextLine(handle)handle
Get the line after the given one, or false if that was the last line.
prevLine(handle)handle
Find the line before the given one, return false if that was the first line.
nthLine(number)handle
Find the Nth line of the document. Note that the first line counts as one, not zero. Returns false if there is no such line.
lineContent(handle)string
Retrieve the content of the line.
setLineContent(handle, string)
Replace the content of the line with the given string.
lineNumber(handle)number
Ask which line of the document (1-based) the given line is.
selectLines(startHandle, startOffset, endHandle, endOffset)
Move the selection to a specific point. endHandle and endOffset can be omitted to just place the cursor somewhere without selecting any text.
insertIntoLine(handle, position, text)
Insert a piece of text into a line. 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.

Writing a Parser

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)
A function that, given a string stream (see stringstream.js), creates a parser. The behaviour of this parser is described below.
electricChars
An optional string containing the characters that, when typed, should cause the indentation of the current line to be recomputed (for example "{}" for c-like languages).
configure(object)
An optional function that can be used to configure the parser. If it exists, and an editor is given a parserConfig option, it will be called with the value of that option.
firstIndentation(chars, current, direction)
An optional function that is used to determine the proper indentation of the first line of a document. When not provided, 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.