UNPKG

catalogue

Version:
946 lines (809 loc) 146 kB
<!doctype html> <title>CodeMirror: User Manual</title> <meta charset="utf-8"/> <link rel=stylesheet href="docs.css"> <script src="activebookmark.js"></script> <script src="../lib/codemirror.js"></script> <link rel="stylesheet" href="../lib/codemirror.css"> <script src="../addon/runmode/runmode.js"></script> <script src="../addon/runmode/colorize.js"></script> <script src="../mode/javascript/javascript.js"></script> <script src="../mode/xml/xml.js"></script> <script src="../mode/css/css.js"></script> <script src="../mode/htmlmixed/htmlmixed.js"></script> <style> dt { text-indent: -2em; padding-left: 2em; margin-top: 1em; } dd { margin-left: 1.5em; margin-bottom: 1em; } dt {margin-top: 1em;} dd dl, dd dt, dd dd, dd ul { margin-top: 0; margin-bottom: 0; } </style> <div id=nav> <a href="http://codemirror.net"><img id=logo src="logo.png"></a> <ul> <li><a href="../index.html">Home</a> <li><a href="#overview" class=active data-default="true">Manual</a> <li><a href="https://github.com/marijnh/codemirror">Code</a> </ul> <ul> <li><a href="#usage">Basic Usage</a></li> <li><a href="#config">Configuration</a></li> <li><a href="#events">Events</a></li> <li><a href="#keymaps">Keymaps</a></li> <li><a href="#styling">Customized Styling</a></li> <li><a href="#api">Programming API</a> <ul> <li><a href="#api_constructor">Constructor</a></li> <li><a href="#api_content">Content manipulation</a></li> <li><a href="#api_selection">Selection</a></li> <li><a href="#api_configuration">Configuration</a></li> <li><a href="#api_doc">Document management</a></li> <li><a href="#api_history">History</a></li> <li><a href="#api_marker">Text-marking</a></li> <li><a href="#api_decoration">Widget, gutter, and decoration</a></li> <li><a href="#api_sizing">Sizing, scrolling, and positioning</a></li> <li><a href="#api_mode">Mode, state, and tokens</a></li> <li><a href="#api_misc">Miscellaneous methods</a></li> <li><a href="#api_static">Static properties</a></li> </ul> </li> <li><a href="#addons">Addons</a></li> <li><a href="#modeapi">Writing CodeMirror Modes</a></li> </ul> </div> <article> <section class=first id=overview> <h2>User manual and reference guide</h2> <p>CodeMirror is a code-editor component that can be embedded in Web pages. The core library provides <em>only</em> 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 <a href="#addons">addons</a> included in the distribution, and the <a href="https://github.com/marijnh/CodeMirror/wiki/CodeMirror-addons">list of externally hosted addons</a>, for reusable implementations of extra features.</p> <p>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 <a href="../mode/"><code>mode/</code></a> directory), and it isn't hard to <a href="#modeapi">write new ones</a> for other languages.</p> </section> <section id=usage> <h2>Basic Usage</h2> <p>The easiest way to use CodeMirror is to simply load the script and style sheet found under <code>lib/</code> in the distribution, plus a mode script from one of the <code>mode/</code> directories. (See <a href="compress.html">the compression helper</a> for an easy way to combine scripts.) For example:</p> <pre data-lang="text/html">&lt;script src="lib/codemirror.js">&lt;/script> &lt;link rel="stylesheet" href="../lib/codemirror.css"> &lt;script src="mode/javascript/javascript.js">&lt;/script></pre> <p>Having done this, an editor instance can be created like this:</p> <pre data-lang="javascript">var myCodeMirror = CodeMirror(document.body);</pre> <p>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 <a href="#CodeMirror"><code>CodeMirror</code></a> as a second argument:</p> <pre data-lang="javascript">var myCodeMirror = CodeMirror(document.body, { value: "function myScript(){return 100;}\n", mode: "javascript" });</pre> <p>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 <a href="#config">below</a> for a full discussion of the configuration options that CodeMirror accepts.</p> <p>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 <code>CodeMirror</code> 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:</p> <pre data-lang="javascript">var myCodeMirror = CodeMirror(function(elt) { myTextArea.parentNode.replaceChild(elt, myTextArea); }, {value: myTextArea.value});</pre> <p>However, for this use case, which is a common way to use CodeMirror, the library provides a much more powerful shortcut:</p> <pre data-lang="javascript">var myCodeMirror = CodeMirror.fromTextArea(myTextArea);</pre> <p>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 <a href="#fromTextArea">API reference</a> for a full description of this method.</p> </section> <section id=config> <h2>Configuration</h2> <p>Both the <a href="#CodeMirror"><code>CodeMirror</code></a> function and its <code>fromTextArea</code> method take as second (optional) argument an object containing configuration options. Any option not supplied like this will be taken from <a href="#defaults"><code>CodeMirror.defaults</code></a>, an object containing the default options. You can update this object to change the defaults on your page.</p> <p>Options are not checked in any way, so setting bogus option values is bound to lead to odd errors.</p> <p>These are the supported options:</p> <dl> <dt id="option_value"><code><strong>value</strong>: string|CodeMirror.Doc</code></dt> <dd>The starting value of the editor. Can be a string, or a <a href="#api_doc">document object</a>.</dd> <dt id="option_mode"><code><strong>mode</strong>: string|object</code></dt> <dd>The mode to use. When not given, this will default to the first mode that was loaded. It may be a string, which either simply names the mode or is a <a href="http://en.wikipedia.org/wiki/MIME">MIME</a> type associated with the mode. Alternatively, it may be an object containing configuration options for the mode, with a <code>name</code> property that names the mode (for example <code>{name: "javascript", json: true}</code>). 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 <code>CodeMirror.modes</code> and <code>CodeMirror.mimeModes</code> objects. The first maps mode names to their constructors, and the second maps MIME types to mode specs.</dd> <dt id="option_theme"><code><strong>theme</strong>: string</code></dt> <dd>The theme to style the editor with. You must make sure the CSS file defining the corresponding <code>.cm-s-[name]</code> styles is loaded (see the <a href="../theme/"><code>theme</code></a> directory in the distribution). The default is <code>"default"</code>, for which colors are included in <code>codemirror.css</code>. It is possible to use multiple theming classes at once—for example <code>"foo bar"</code> will assign both the <code>cm-s-foo</code> and the <code>cm-s-bar</code> classes to the editor.</dd> <dt id="option_indentUnit"><code><strong>indentUnit</strong>: integer</code></dt> <dd>How many spaces a block (whatever that means in the edited language) should be indented. The default is 2.</dd> <dt id="option_smartIndent"><code><strong>smartIndent</strong>: boolean</code></dt> <dd>Whether to use the context-sensitive indentation that the mode provides (or just indent the same as the line before). Defaults to true.</dd> <dt id="option_tabSize"><code><strong>tabSize</strong>: integer</code></dt> <dd>The width of a tab character. Defaults to 4.</dd> <dt id="option_indentWithTabs"><code><strong>indentWithTabs</strong>: boolean</code></dt> <dd>Whether, when indenting, the first N*<code>tabSize</code> spaces should be replaced by N tabs. Default is false.</dd> <dt id="option_electricChars"><code><strong>electricChars</strong>: boolean</code></dt> <dd>Configures whether the editor should re-indent the current line when a character is typed that might change its proper indentation (only works if the mode supports indentation). Default is true.</dd> <dt id="option_specialChars"><code><strong>specialChars</strong>: RegExp</code></dt> <dd>A regular expression used to determine which characters should be replaced by a special <a href="#option_specialCharPlaceholder">placeholder</a>. Mostly useful for non-printing special characters. The default is <code>/[\u0000-\u0019\u00ad\u200b\u2028\u2029\ufeff]/</code>.</dd> <dt id="option_specialCharPlaceholder"><code><strong>specialCharPlaceholder</strong>: function(char) → Element</code></dt> <dd>A function that, given a special character identified by the <a href="#option_specialChars"><code>specialChars</code></a> option, produces a DOM node that is used to represent the character. By default, a red dot (<span style="color: red">•</span>) is shown, with a title tooltip to indicate the character code.</dd> <dt id="option_rtlMoveVisually"><code><strong>rtlMoveVisually</strong>: boolean</code></dt> <dd>Determines whether horizontal cursor movement through right-to-left (Arabic, Hebrew) text is visual (pressing the left arrow moves the cursor left) or logical (pressing the left arrow moves to the next lower index in the string, which is visually right in right-to-left text). The default is <code>false</code> on Windows, and <code>true</code> on other platforms.</dd> <dt id="option_keyMap"><code><strong>keyMap</strong>: string</code></dt> <dd>Configures the keymap to use. The default is <code>"default"</code>, which is the only keymap defined in <code>codemirror.js</code> itself. Extra keymaps are found in the <a href="../keymap/"><code>keymap</code></a> directory. See the <a href="#keymaps">section on keymaps</a> for more information.</dd> <dt id="option_extraKeys"><code><strong>extraKeys</strong>: object</code></dt> <dd>Can be used to specify extra keybindings for the editor, alongside the ones defined by <a href="#option_keyMap"><code>keyMap</code></a>. Should be either null, or a valid <a href="#keymaps">keymap</a> value.</dd> <dt id="option_lineWrapping"><code><strong>lineWrapping</strong>: boolean</code></dt> <dd>Whether CodeMirror should scroll or wrap for long lines. Defaults to <code>false</code> (scroll).</dd> <dt id="option_lineNumbers"><code><strong>lineNumbers</strong>: boolean</code></dt> <dd>Whether to show line numbers to the left of the editor.</dd> <dt id="option_firstLineNumber"><code><strong>firstLineNumber</strong>: integer</code></dt> <dd>At which number to start counting lines. Default is 1.</dd> <dt id="option_lineNumberFormatter"><code><strong>lineNumberFormatter</strong>: function(line: integer) → string</code></dt> <dd>A function used to format line numbers. The function is passed the line number, and should return a string that will be shown in the gutter.</dd> <dt id="option_gutters"><code><strong>gutters</strong>: array&lt;string&gt;</code></dt> <dd>Can be used to add extra gutters (beyond or instead of the line number gutter). Should be an array of CSS class names, each of which defines a <code>width</code> (and optionally a background), and which will be used to draw the background of the gutters. <em>May</em> include the <code>CodeMirror-linenumbers</code> 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 <a href="#setGutterMarker"><code>setGutterMarker</code></a>.</dd> <dt id="option_fixedGutter"><code><strong>fixedGutter</strong>: boolean</code></dt> <dd>Determines whether the gutter scrolls along with the content horizontally (false) or whether it stays fixed during horizontal scrolling (true, the default).</dd> <dt id="option_coverGutterNextToScrollbar"><code><strong>coverGutterNextToScrollbar</strong>: boolean</code></dt> <dd>When <a href="#option_fixedGutter"><code>fixedGutter</code></a> is on, and there is a horizontal scrollbar, by default the gutter will be visible to the left of this scrollbar. If this option is set to true, it will be covered by an element with class <code>CodeMirror-gutter-filler</code>.</dd> <dt id="option_readOnly"><code><strong>readOnly</strong>: boolean|string</code></dt> <dd>This disables editing of the editor content by the user. If the special value <code>"nocursor"</code> is given (instead of simply <code>true</code>), focusing of the editor is also disallowed.</dd> <dt id="option_showCursorWhenSelecting"><code><strong>showCursorWhenSelecting</strong>: boolean</code></dt> <dd>Whether the cursor should be drawn when a selection is active. Defaults to false.</dd> <dt id="option_undoDepth"><code><strong>undoDepth</strong>: integer</code></dt> <dd>The maximum number of undo levels that the editor stores. Defaults to 40.</dd> <dt id="option_historyEventDelay"><code><strong>historyEventDelay</strong>: integer</code></dt> <dd>The period of inactivity (in milliseconds) that will cause a new history event to be started when typing or deleting. Defaults to 500.</dd> <dt id="option_tabindex"><code><strong>tabindex</strong>: integer</code></dt> <dd>The <a href="http://www.w3.org/TR/html401/interact/forms.html#adef-tabindex">tab index</a> to assign to the editor. If not given, no tab index will be assigned.</dd> <dt id="option_autofocus"><code><strong>autofocus</strong>: boolean</code></dt> <dd>Can be used to make CodeMirror focus itself on initialization. Defaults to off. When <a href="#fromTextArea"><code>fromTextArea</code></a> 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 <code>autofocus</code> attribute and no other element is focused.</dd> </dl> <p>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.</p> <dl> <dt id="option_dragDrop"><code><strong>dragDrop</strong>: boolean</code></dt> <dd>Controls whether drag-and-drop is enabled. On by default.</dd> <dt id="option_onDragEvent"><code><strong>onDragEvent</strong>: function(instance: CodeMirror, event: Event) → boolean</code></dt> <dd><em>Deprecated! See <a href="#event_dom">these</a> event handlers for the current recommended approach.</em><br>When given, this will be called when the editor is handling a <code>dragenter</code>, <code>dragover</code>, or <code>drop</code> 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 <code>true</code> to indicate that CodeMirror should not do anything further.</dd> <dt id="option_onKeyEvent"><code><strong>onKeyEvent</strong>: function(instance: CodeMirror, event: Event) → boolean</code></dt> <dd><em>Deprecated! See <a href="#event_dom">these</a> event handlers for the current recommended approach.</em><br>This provides a rather low-level hook into CodeMirror's key handling. If provided, this function will be called on every <code>keydown</code>, <code>keyup</code>, and <code>keypress</code> 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 <code>stop()</code> method is always added to it. You could feed it to, for example, <code>jQuery.Event</code> to further normalize it.<br>This function can inspect the key event, and handle it if it wants to. It may return true to tell CodeMirror to ignore the event. Be wary that, on some browsers, stopping a <code>keydown</code> does not stop the <code>keypress</code> from firing, whereas on others it does. If you respond to an event, you should probably inspect its <code>type</code> property and only do something when it is <code>keydown</code> (or <code>keypress</code> for actions that need character data).</dd> <dt id="option_cursorBlinkRate"><code><strong>cursorBlinkRate</strong>: number</code></dt> <dd>Half-period in milliseconds used for cursor blinking. The default blink rate is 530ms. By setting this to zero, blinking can be disabled.</dd> <dt id="option_cursorScrollMargin"><code><strong>cursorScrollMargin</strong>: number</code></dt> <dd>How much extra space to always keep above and below the cursor when approaching the top or bottom of the visible view in a scrollable document. Default is 0.</dd> <dt id="option_cursorHeight"><code><strong>cursorHeight</strong>: number</code></dt> <dd>Determines the height of the cursor. Default is 1, meaning it spans the whole height of the line. For some fonts (and by some tastes) a smaller height (for example <code>0.85</code>), which causes the cursor to not reach all the way to the bottom of the line, looks better</dd> <dt id="option_resetSelectionOnContextMenu"><code><strong>resetSelectionOnContextMenu</strong>: boolean</code></dt> <dd>Controls whether, when the context menu is opened with a click outside of the current selection, the cursor is moved to the point of the click. Defaults to <code>true</code>.</dd> <dt id="option_workTime"><code><strong>workTime</strong>, <strong>workDelay</strong>: number</code></dt> <dd>Highlighting is done by a pseudo background-thread that will work for <code>workTime</code> milliseconds, and then use timeout to sleep for <code>workDelay</code> milliseconds. The defaults are 200 and 300, you can change these options to make the highlighting more or less aggressive.</dd> <dt id="option_workDelay"><code><strong>workDelay</strong>: number</code></dt> <dd>See <a href="#option_workTime"><code>workTime</code></a>.</dd> <dt id="option_pollInterval"><code><strong>pollInterval</strong>: number</code></dt> <dd>Indicates how quickly CodeMirror should poll its input textarea for changes (when focused). Most input is captured by events, but some things, like IME input on some browsers, don't generate events that allow CodeMirror to properly detect it. Thus, it polls. Default is 100 milliseconds.</dd> <dt id="option_flattenSpans"><code><strong>flattenSpans</strong>: boolean</code></dt> <dd>By default, CodeMirror will combine adjacent tokens into a single span if they have the same class. This will result in a simpler DOM tree, and thus perform better. With some kinds of styling (such as rounded corners), this will change the way the document looks. You can set this option to false to disable this behavior.</dd> <dt id="option_addModeClass"><code><strong>addModeClass</strong>: boolean</code></dt> <dd>When enabled (off by default), an extra CSS class will be added to each token, indicating the (<a href="#innerMode">inner</a>) mode that produced it, prefixed with <code>"cm-m-"</code>. For example, tokens from the XML mode will get the <code>cm-m-xml</code> class.</dd> <dt id="option_maxHighlightLength"><code><strong>maxHighlightLength</strong>: number</code></dt> <dd>When highlighting long lines, in order to stay responsive, the editor will give up and simply style the rest of the line as plain text when it reaches a certain position. The default is 10 000. You can set this to <code>Infinity</code> to turn off this behavior.</dd> <dt id="option_crudeMeasuringFrom"><code><strong>crudeMeasuringFrom</strong>: number</code></dt> <dd>When measuring the character positions in long lines, any line longer than this number (default is 10 000), when <a href="#option_lineWrapping">line wrapping</a> is <strong>off</strong>, will simply be assumed to consist of same-sized characters. This means that, on the one hand, measuring will be inaccurate when characters of varying size, right-to-left text, markers, or other irregular elements are present. On the other hand, it means that having such a line won't freeze the user interface because of the expensiveness of the measurements.</dd> <dt id="option_viewportMargin"><code><strong>viewportMargin</strong>: integer</code></dt> <dd>Specifies the amount of lines that are rendered above and below the part of the document that's currently scrolled into view. This affects the amount of updates needed when scrolling, and the amount of work that such an update does. You should usually leave it at its default, 10. Can be set to <code>Infinity</code> to make sure the whole document is always rendered, and thus the browser's text search works on it. This <em>will</em> have bad effects on performance of big documents.</dd> </dl> </section> <section id=events> <h2>Events</h2> <p>Various CodeMirror-related objects emit events, which allow client code to react to various situations. Handlers for such events can be registed with the <a href="#on"><code>on</code></a> and <a href="#off"><code>off</code></a> methods on the objects that the event fires on. To fire your own events, use <code>CodeMirror.signal(target, name, args...)</code>, where <code>target</code> is a non-DOM-node object.</p> <p>An editor instance fires the following events. The <code>instance</code> argument always refers to the editor itself.</p> <dl> <dt id="event_change"><code><strong>"change"</strong> (instance: CodeMirror, changeObj: object)</code></dt> <dd>Fires every time the content of the editor is changed. The <code>changeObj</code> is a <code>{from, to, text, removed, next}</code> object containing information about the changes that occurred as second argument. <code>from</code> and <code>to</code> are the positions (in the pre-change coordinate system) where the change started and ended (for example, it might be <code>{ch:0, line:18}</code> if the position is at the beginning of line #19). <code>text</code> is an array of strings representing the text that replaced the changed range (split by line). <code>removed</code> is the text that used to be between <code>from</code> and <code>to</code>, which is overwritten by this change. If multiple changes happened during a single operation, the object will have a <code>next</code> property pointing to another change object (which may point to another, etc).</dd> <dt id="event_beforeChange"><code><strong>"beforeChange"</strong> (instance: CodeMirror, changeObj: object)</code></dt> <dd>This event is fired before a change is applied, and its handler may choose to modify or cancel the change. The <code>changeObj</code> object has <code>from</code>, <code>to</code>, and <code>text</code> properties, as with the <a href="#event_change"><code>"change"</code></a> event, but never a <code>next</code> property, since this is fired for each individual change, and not batched per operation. It also has a <code>cancel()</code> method, which can be called to cancel the change, and, <strong>if</strong> the change isn't coming from an undo or redo event, an <code>update(from, to, text)</code> method, which may be used to modify the change. Undo or redo changes can't be modified, because they hold some metainformation for restoring old marked ranges that is only valid for that specific change. All three arguments to <code>update</code> are optional, and can be left off to leave the existing value for that field intact. <strong>Note:</strong> you may not do anything from a <code>"beforeChange"</code> 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.</dd> <dt id="event_cursorActivity"><code><strong>"cursorActivity"</strong> (instance: CodeMirror)</code></dt> <dd>Will be fired when the cursor or selection moves, or any change is made to the editor content.</dd> <dt id="event_keyHandled"><code><strong>"keyHandled"</strong> (instance: CodeMirror, name: string, event: Event)</code></dt> <dd>Fired after a key is handled through a keymap. <code>name</code> is the name of the handled key (for example <code>"Ctrl-X"</code> or <code>"'q'"</code>), and <code>event</code> is the DOM <code>keydown</code> or <code>keypress</code> event.</dd> <dt id="event_inputRead"><code><strong>"inputRead"</strong> (instance: CodeMirror, changeObj: object)</code></dt> <dd>Fired whenever new input is read from the hidden textarea (typed or pasted by the user).</dd> <dt id="event_beforeSelectionChange"><code><strong>"beforeSelectionChange"</strong> (instance: CodeMirror, selection: {head, anchor})</code></dt> <dd>This event is fired before the selection is moved. Its handler may modify the resulting selection head and anchor. The <code>selection</code> parameter is an object with <code>head</code> and <code>anchor</code> properties holding <code>{line, ch}</code> objects, which the handler can read and update. Handlers for this event have the same restriction as <a href="#event_beforeChange"><code>"beforeChange"</code></a> handlers — they should not do anything to directly update the state of the editor.</dd> <dt id="event_viewportChange"><code><strong>"viewportChange"</strong> (instance: CodeMirror, from: number, to: number)</code></dt> <dd>Fires whenever the <a href="#getViewport">view port</a> of the editor changes (due to scrolling, editing, or any other factor). The <code>from</code> and <code>to</code> arguments give the new start and end of the viewport.</dd> <dt id="event_swapDoc"><code><strong>"swapDoc"</strong> (instance: CodeMirror, oldDoc: Doc)</code></dt> <dd>This is signalled when the editor's document is replaced using the <a href="#swapDoc"><code>swapDoc</code></a> method.</dd> <dt id="event_gutterClick"><code><strong>"gutterClick"</strong> (instance: CodeMirror, line: integer, gutter: string, clickEvent: Event)</code></dt> <dd>Fires when the editor gutter (the line-number area) is clicked. Will pass the editor instance as first argument, the (zero-based) number of the line that was clicked as second argument, the CSS class of the gutter that was clicked as third argument, and the raw <code>mousedown</code> event object as fourth argument.</dd> <dt id="event_gutterContextMenu"><code><strong>"gutterContextMenu"</strong> (instance: CodeMirror, line: integer, gutter: string, contextMenu: Event: Event)</code></dt> <dd>Fires when the editor gutter (the line-number area) receives a <code>contextmenu</code> event. Will pass the editor instance as first argument, the (zero-based) number of the line that was clicked as second argument, the CSS class of the gutter that was clicked as third argument, and the raw <code>contextmenu</code> mouse event object as fourth argument. You can <code>preventDefault</code> the event, to signal that CodeMirror should do no further handling.</dd> <dt id="event_focus"><code><strong>"focus"</strong> (instance: CodeMirror)</code></dt> <dd>Fires whenever the editor is focused.</dd> <dt id="event_blur"><code><strong>"blur"</strong> (instance: CodeMirror)</code></dt> <dd>Fires whenever the editor is unfocused.</dd> <dt id="event_scroll"><code><strong>"scroll"</strong> (instance: CodeMirror)</code></dt> <dd>Fires when the editor is scrolled.</dd> <dt id="event_update"><code><strong>"update"</strong> (instance: CodeMirror)</code></dt> <dd>Will be fired whenever CodeMirror updates its DOM display.</dd> <dt id="event_renderLine"><code><strong>"renderLine"</strong> (instance: CodeMirror, line: LineHandle, element: Element)</code></dt> <dd>Fired whenever a line is (re-)rendered to the DOM. Fired right after the DOM element is built, <em>before</em> it is added to the document. The handler may mess with the style of the resulting element, or add event handlers, but should <em>not</em> try to change the state of the editor.</dd> <dt id="event_dom"><code><strong>"mousedown"</strong>, <strong>"dblclick"</strong>, <strong>"contextmenu"</strong>, <strong>"keydown"</strong>, <strong>"keypress"</strong>, <strong>"keyup"</strong>, <strong>"dragstart"</strong>, <strong>"dragenter"</strong>, <strong>"dragover"</strong>, <strong>"drop"</strong> (instance: CodeMirror, event: Event)</code></dt> <dd>Fired when CodeMirror is handling a DOM event of this type. You can <code>preventDefault</code> the event, or give it a truthy <code>codemirrorIgnore</code> property, to signal that CodeMirror should do no further handling.</dd> </dl> <p>Document objects (instances of <a href="#Doc"><code>CodeMirror.Doc</code></a>) emit the following events:</p> <dl> <dt id="event_doc_change"><code><strong>"change"</strong> (doc: CodeMirror.Doc, changeObj: object)</code></dt> <dd>Fired whenever a change occurs to the document. <code>changeObj</code> has a similar type as the object passed to the editor's <a href="#event_change"><code>"change"</code></a> event, but it never has a <code>next</code> property, because document change events are not batched (whereas editor change events are).</dd> <dt id="event_doc_beforeChange"><code><strong>"beforeChange"</strong> (doc: CodeMirror.Doc, change: object)</code></dt> <dd>See the <a href="#event_beforeChange">description of the same event</a> on editor instances.</dd> <dt id="event_doc_cursorActivity"><code><strong>"cursorActivity"</strong> (doc: CodeMirror.Doc)</code></dt> <dd>Fired whenever the cursor or selection in this document changes.</dd> <dt id="event_doc_beforeSelectionChange"><code><strong>"beforeSelectionChange"</strong> (doc: CodeMirror.Doc, selection: {head, anchor})</code></dt> <dd>Equivalent to the <a href="#event_beforeSelectionChange">event by the same name</a> as fired on editor instances.</dd> </dl> <p>Line handles (as returned by, for example, <a href="#getLineHandle"><code>getLineHandle</code></a>) support these events:</p> <dl> <dt id="event_delete"><code><strong>"delete"</strong> ()</code></dt> <dd>Will be fired when the line object is deleted. A line object is associated with the <em>start</em> of the line. Mostly useful when you need to find out when your <a href="#setGutterMarker">gutter markers</a> on a given line are removed.</dd> <dt id="event_line_change"><code><strong>"change"</strong> (line: LineHandle, changeObj: object)</code></dt> <dd>Fires when the line's text content is changed in any way (but the line is not deleted outright). The <code>change</code> object is similar to the one passed to <a href="#event_change">change event</a> on the editor object.</dd> </dl> <p>Marked range handles (<code>CodeMirror.TextMarker</code>), as returned by <a href="#markText"><code>markText</code></a> and <a href="#setBookmark"><code>setBookmark</code></a>, emit the following events:</p> <dl> <dt id="event_beforeCursorEnter"><code><strong>"beforeCursorEnter"</strong> ()</code></dt> <dd>Fired when the cursor enters the marked range. From this event handler, the editor state may be inspected but <em>not</em> modified, with the exception that the range on which the event fires may be cleared.</dd> <dt id="event_clear"><code><strong>"clear"</strong> (from: {line, ch}, to: {line, ch})</code></dt> <dd>Fired when the range is cleared, either through cursor movement in combination with <a href="#mark_clearOnEnter"><code>clearOnEnter</code></a> or through a call to its <code>clear()</code> 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. <code>from</code> and <code>to</code> give the part of the document that the range spanned when it was cleared.</dd> <dt id="event_hide"><code><strong>"hide"</strong> ()</code></dt> <dd>Fired when the last part of the marker is removed from the document by editing operations.</dd> <dt id="event_unhide"><code><strong>"unhide"</strong> ()</code></dt> <dd>Fired when, after the marker was removed by editing, a undo operation brought the marker back.</dd> </dl> <p>Line widgets (<code>CodeMirror.LineWidget</code>), returned by <a href="#addLineWidget"><code>addLineWidget</code></a>, fire these events:</p> <dl> <dt id="event_redraw"><code><strong>"redraw"</strong> ()</code></dt> <dd>Fired whenever the editor re-adds the widget to the DOM. This will happen once right after the widget is added (if it is scrolled into view), and then again whenever it is scrolled out of view and back in again, or when changes to the editor options or the line the widget is on require the widget to be redrawn.</dd> </dl> </section> <section id=keymaps> <h2>Keymaps</h2> <p>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.</p> <p>Keys are identified either by name or by character. The <code>CodeMirror.keyNames</code> object defines names for common keys and associates them with their key codes. Examples of names defined here are <code>Enter</code>, <code>F5</code>, and <code>Q</code>. These can be prefixed with <code>Shift-</code>, <code>Cmd-</code>, <code>Ctrl-</code>, and <code>Alt-</code> (in that order!) to specify a modifier. So for example, <code>Shift-Ctrl-Space</code> would be a valid key identifier.</p> <p>Common example: map the Tab key to insert spaces instead of a tab character.</p> <pre data-lang="javascript"> { Tab: function(cm) { var spaces = Array(cm.getOption("indentUnit") + 1).join(" "); cm.replaceSelection(spaces, "end", "+input"); } }</pre> <p>Alternatively, a character can be specified directly by surrounding it in single quotes, for example <code>'$'</code> or <code>'q'</code>. Due to limitations in the way browsers fire key events, these may not be prefixed with modifiers.</p> <p>The <code>CodeMirror.keyMap</code> 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 <code>"default"</code> keymap holding the default bindings.</p> <p id="commands">The values of properties in keymaps can be either functions of a single argument (the CodeMirror instance), strings, or <code>false</code>. Such strings refer to properties of the <code>CodeMirror.commands</code> 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 <code>false</code>, CodeMirror leaves handling of the key up to the browser. A key handler function may return <code>CodeMirror.Pass</code> to indicate that it has decided not to handle the key, and other handlers (or the default behavior) should be given a turn.</p> <p>Keys mapped to command names that start with the characters <code>"go"</code> (which should be used for cursor-movement actions) will be fired even when an extra <code>Shift</code> modifier is present (i.e. <code>"Up": "goLineUp"</code> matches both up and shift-up). This is used to easily implement shift-selection.</p> <p>Keymaps can defer to each other by defining a <code>fallthrough</code> 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.</p> <p>When a keymap contains a <code>nofallthrough</code> property set to <code>true</code>, 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). When the <code>disableInput</code> property is set to <code>true</code>, the default effect of inserting a character will be suppressed when the keymap is active as the top-level map.</p> </section> <section id=styling> <h2>Customized Styling</h2> <p>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 <a href="../lib/codemirror.css"><code>codemirror.css</code></a>.</p> <p>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:</p> <dl> <dt id="class_CodeMirror"><code><strong>CodeMirror</strong></code></dt> <dd>The outer element of the editor. This should be used for the editor width, height, borders and positioning. Can also be used to set styles that should hold for everything inside the editor (such as font and font size), or to set a background.</dd> <dt id="class_CodeMirror_scroll"><code><strong>CodeMirror-scroll</strong></code></dt> <dd>Whether the editor scrolls (<code>overflow: auto</code> + fixed height). By default, it does. Setting the <code>CodeMirror</code> class to have <code>height: auto</code> and giving this class <code>overflow-x: auto; overflow-y: hidden;</code> will cause the editor to <a href="../demo/resize.html">resize to fit its content</a>.</dd> <dt id="class_CodeMirror_focused"><code><strong>CodeMirror-focused</strong></code></dt> <dd>Whenever the editor is focused, the top element gets this class. This is used to hide the cursor and give the selection a different color when the editor is not focused.</dd> <dt id="class_CodeMirror_gutters"><code><strong>CodeMirror-gutters</strong></code></dt> <dd>This is the backdrop for all gutters. Use it to set the default gutter background color, and optionally add a border on the right of the gutters.</dd> <dt id="class_CodeMirror_linenumbers"><code><strong>CodeMirror-linenumbers</strong></code></dt> <dd>Use this for giving a background or width to the line number gutter.</dd> <dt id="class_CodeMirror_linenumber"><code><strong>CodeMirror-linenumber</strong></code></dt> <dd>Used to style the actual individual line numbers. These won't be children of the <code>CodeMirror-linenumbers</code> (plural) element, but rather will be absolutely positioned to overlay it. Use this to set alignment and text properties for the line numbers.</dd> <dt id="class_CodeMirror_lines"><code><strong>CodeMirror-lines</strong></code></dt> <dd>The visible lines. This is where you specify vertical padding for the editor content.</dd> <dt id="class_CodeMirror_cursor"><code><strong>CodeMirror-cursor</strong></code></dt> <dd>The cursor is a block element that is absolutely positioned. You can make it look whichever way you want.</dd> <dt id="class_CodeMirror_selected"><code><strong>CodeMirror-selected</strong></code></dt> <dd>The selection is represented by <code>span</code> elements with this class.</dd> <dt id="class_CodeMirror_matchingbracket"><code><strong>CodeMirror-matchingbracket</strong></code>, <code><strong>CodeMirror-nonmatchingbracket</strong></code></dt> <dd>These are used to style matched (or unmatched) brackets.</dd> </dl> <p>If your page's style sheets do funky things to all <code>div</code> or <code>pre</code> elements (you probably shouldn't do that), you'll have to define rules to cancel these effects out again for elements under the <code>CodeMirror</code> class.</p> <p>Themes are also simply CSS files, which define colors for various syntactic elements. See the files in the <a href="../theme/"><code>theme</code></a> directory.</p> </section> <section id=api> <h2>Programming API</h2> <p>A lot of CodeMirror features are only available through its API. Thus, you need to write code (or use <a href="#addons">addons</a>) if you want to expose them to your users.</p> <p>Whenever points in the document are represented, the API uses objects with <code>line</code> and <code>ch</code> 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 <code>ch</code> a value of <code>null</code>, or don't specify it, it will be replaced with the length of the specified line.</p> <p>Methods prefixed with <code>doc.</code> can, unless otherwise specified, be called both on <code>CodeMirror</code> (editor) instances and <code>CodeMirror.Doc</code> instances. Methods prefixed with <code>cm.</code> are <em>only</em> available on <code>CodeMirror</code> instances.</p> <h3 id="api_constructor">Constructor</h3> <p id="CodeMirror">Constructing an editor instance is done with the <code><strong>CodeMirror</strong>(place: Element|fn(Element), ?option: object)</code> constructor. If the <code>place</code> argument is a DOM element, the editor will be appended to it. If it is a function, it will be called, and is expected to place the editor into the document. <code>options</code> may be an element mapping <a href="#config">option names</a> to values. The options that it doesn't explicitly specify (or all options, if it is not passed) will be taken from <a href="#defaults"><code>CodeMirror.defaults</code></a>.</p> <p>Note that the options object passed to the constructor will be mutated when the instance's options are <a href="#setOption">changed</a>, so you shouldn't share such objects between instances.</p> <p>See <a href="#fromTextArea"><code>CodeMirror.fromTextArea</code></a> for another way to construct an editor instance.</p> <h3 id="api_content">Content manipulation methods</h3> <dl> <dt id="getValue"><code><strong>doc.getValue</strong>(?separator: string) → string</code></dt> <dd>Get the current editor content. You can pass it an optional argument to specify the string to be used to separate lines (defaults to <code>"\n"</code>).</dd> <dt id="setValue"><code><strong>doc.setValue</strong>(content: string)</code></dt> <dd>Set the editor content.</dd> <dt id="getRange"><code><strong>doc.getRange</strong>(from: {line, ch}, to: {line, ch}, ?separator: string) → string</code></dt> <dd>Get the text between the given points in the editor, which should be <code>{line, ch}</code> objects. An optional third argument can be given to indicate the line separator string to use (defaults to <code>"\n"</code>).</dd> <dt id="replaceRange"><code><strong>doc.replaceRange</strong>(replacement: string, from: {line, ch}, to: {line, ch})</code></dt> <dd>Replace the part of the document between <code>from</code> and <code>to</code> with the given string. <code>from</code> and <code>to</code> must be <code>{line, ch}</code> objects. <code>to</code> can be left off to simply insert the string at position <code>from</code>.</dd> <dt id="getLine"><code><strong>doc.getLine</strong>(n: integer) → string</code></dt> <dd>Get the content of line <code>n</code>.</dd> <dt id="setLine"><code><strong>doc.setLine</strong>(n: integer, text: string)</code></dt> <dd>Set the content of line <code>n</code>.</dd> <dt id="removeLine"><code><strong>doc.removeLine</strong>(n: integer)</code></dt> <dd>Remove the given line from the document.</dd> <dt id="lineCount"><code><strong>doc.lineCount</strong>() → integer</code></dt> <dd>Get the number of lines in the editor.</dd> <dt id="firstLine"><code><strong>doc.firstLine</strong>() → integer</code></dt> <dd>Get the first line of the editor. This will usually be zero but for <a href="#linkedDoc_from">linked sub-views</a>, or <a href="#api_doc">documents</a> instantiated with a non-zero first line, it might return other values.</dd> <dt id="lastLine"><code><strong>doc.lastLine</strong>() → integer</code></dt> <dd>Get the last line of the editor. This will usually be <code>doc.lineCount() - 1</code>, but for <a href="#linkedDoc_from">linked sub-views</a>, it might return other values.</dd> <dt id="getLineHandle"><code><strong>doc.getLineHandle</strong>(num: integer) → LineHandle</code></dt> <dd>Fetches the line handle for the given line number.</dd> <dt id="getLineNumber"><code><strong>doc.getLineNumber</strong>(handle: LineHandle) → integer</code></dt> <dd>Given a line handle, returns the current position of that line (or <code>null</code> when it is no longer in the document).</dd> <dt id="eachLine"><code><strong>doc.eachLine</strong>(f: (line: LineHandle))</code></dt> <dt><code><strong>doc.eachLine</strong>(start: integer, end: integer, f: (line: LineHandle))</code></dt> <dd>Iterate over the whole document, or if <code>start</code> and <code>end</code> line numbers are given, the range from <code>start</code> up to (not including) <code>end</code>, and call <code>f</code> for each line, passing the line handle. This is a faster way to visit a range of line handlers than calling <a href="#getLineHandle"><code>getLineHandle</code></a> for each of them. Note that line handles have a <code>text</code> property containing the line's content (as a string).</dd> <dt id="markClean"><code><strong>doc.markClean</strong>()</code></dt> <dd>Set the editor content as 'clean', a flag that it will retain until it is edited, and which will be set again when such an edit is undone again. Useful to track whether the content needs to be saved. This function is deprecated in favor of <a href="#changeGeneration"><code>changeGeneration</code></a>, which allows multiple subsystems to track different notions of cleanness without interfering.</dd> <dt id="changeGeneration"><code><strong>doc.changeGeneration</strong>(?closeEvent: boolean) → integer</code></dt> <dd>Returns a number that can l