{ } CodeMirror

/* User manual and
   reference guide */

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).

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
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 (see the compression API).

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, or style-sheets, that should be used to colour the code in the editor frame. Can be a string or an array of strings. See 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
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.
iframeClass
Set this to a string to give the IFRAME node created for the editor a custom CSS class. Defaults to null.
passDelay
Gives the amount of milliseconds between colouring passes. Defaults to 200.
passTime
Specifies the maximum amount of time that the highlighter will spend in one shot. Setting this too high will cause the editor to 'freeze' the browser for noticeable intervals. Defaults to 50.
continuousScanning
Configure continuous scanning of the document. When 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
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.
markParen,unmarkParen
Can be used to customise the way brackets are marked (and unmarked) when matched. The simplest way to do this is to simply set 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
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. This setting is changeable with the setUndoDepth(depth) method on CodeMirror instances.
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%"). 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
Should the editor disable spell-checking on browsers that support it (Firefox 2+). Default is true, since for most code spell-checking is useless. Can be changed with the setSpellCheck(on) method.
textWrapping
Can be used to disable or enable text-wrapping in the editor frame. Default is true. Changeable with the setTextWrapping(on) method.
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. Changeable with the setLineNumbers(on) method.
firstLineNumber
When lineNumbers is enabled, this determines the number given to the first line. Default is 1.
lineNumberDelay, lineNumberTime
When both line numbers are and text wrapping are turned on, updating line numbers can be expensive. These settings can be used to control how fast the updating happens ― they work in the same way as passDelay and passTime.
onLineNumberClick
If given a function value, this function will be called when the user clicks a line number, with the number of the line and the DIV used to display that number as its arguments.
styleNumbers
A (somewhat awkward) hook that allows your code to change the style of the line numbers for certain lines (to, for example, highlight them). Whenever the line numbers are updated, the function value given through this option is called with three arguments: (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
An integer that specifies the amount of spaces one 'level' of indentation should add. Default is 2. Changeable in a running editor using the setIndentUnit(spaces) method.
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.
"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, un-indents it.
"spaces"
Pressing tab simply inserts four spaces, except when something is selected, in which case the "shift" behaviour is used.
This option can be changed at run-time using the setTabMode(mode) method.
enterMode
Determines how a new line created by pressing enter is indented. Supported modes are:
"indent"
The default. Causes the new line to be intented by the rules of the parser.
"keep"
Keeps the indentation of the previous line.
"flat"
Never indents new lines.
The setEnterMode method can be used to change this option in a running editor.
electricChars
A boolean that can be used to turn "electric chars" (characters that cause the current line to be reindented when typed, such as { and } in C-like languages) on and off. Default is on.
reindentOnLoad
When true, this causes the content of the editor to be reindented immediately when the editor loads. Defaults to false.
readOnly
When set to true, the document is not editable.
domain
Can be set to the value 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
The scripts loaded inside the editor frame are not affected by, for example, ctrl-F5 on Firefox, and will often be cached even though you don't want them to. During development, you can set this option to true to cause CodeMirror to add a changing dummy parameter to the script URLs, which will force browsers to reload them every time.
onLoad
If set to a function, this will be called (with the editor object as its argument) after the editor has finished initialising.
onCursorActivity
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

(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)
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 (demo)
The JavaScript parser. Example colours in 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)
A CSS parser. Styles in css/csscolors.css
parsehtmlmixed.js (demo)
A mixed-mode HTML parser. By default, 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"]. 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)
Parses the SPARQL query language. Example styles in css/sparqlcolors.css
parsedummy.js
A 'dummy' parser to make it possible to edit plain text, or documents for which no suitable parser exists.
contrib/php/js/parsephp.js (demo)
PHP parser. There is also 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)
Python parser.
contrib/lua/js/parselua.js (demo)
Lua parser.

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 and properties that make it possible to add extra functionality around the editor. mirrorframe.js provides a basic example of their usage.

Properties

frame
The editable frame.
win
The window of the editable frame. Mostly useful for attaching event handlers.
wrapping
The DIV element wrapped around the frame. This always has a CSS class of CodeMirror-wrapping.

Methods

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.
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.
reindentSelection()
Automatically re-indent the selected lines.
getSearchCursor(pattern, startPos, caseFold)cursor
The first argument provides the pattern that should be searched for. It can be a string or a regular expression (with the caveat that regexps won't match across line boundaries, whereas strings will). The second determines where to start searching. It can be 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()
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.
clearHistory()
Drop all history information.
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.
setParser(name, parserConfig)
Change the active parser. To use this you'll have to load more than one parser (put the one you want to use as default at the end of the list). Then call this function with a string containing the name of the parser you want to switch to (see the parser script file to find the name, it'll be something like CSSParser). The second argument is optional, and can be used to pass a new parser configuration object.
cursorCoords(start)
Get the coordinates of the cursor in the editor, relative to the top-left corner of the outer document. Normally returns an object with 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).

Line Manipulation

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.
cursorLine()handle
Returns the line on which the cursor is currently sitting.
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.
removeLine(handle)
Remove the given line from the editor. The handle will stay valid after this operation, and now refers to the next line.
lineNumber(handle)number
Ask which line of the document (1-based) the given line is.
jumpToLine(handle)
Moves the cursor to the start of the given line.
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 property 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.

Contents

Site