Reference Manual

For the time being, CodeMirror 6 is published as a single package, @codemirror/next, of which the modules listed here are subdirectories. So to, for example, load the text module, you'd import or require "@codemirror/next/text".

(In the future, these will be published as separate npm packages.)

Each package exposes both a CommonJS and an ECMAScript module. You'll have to use some kind of bundler to run them in the browser.

The most interesting modules are state, which contains the data structures that model the editor state, and view, which provides the UI component for an editor.

A minimal editor might look like this:

import {EditorView} from "@codemirror/next/view"
import {EditorState} from "@codemirror/next/state"

let myView = new EditorView({state: EditorState.create({doc: "hello"})})

But such an editor is too primitive for real use. To get functionality like key bindings, highlighting, a line number gutter, or an undo history, you need to add various extensions to such a basic editor.

state module

In its most basic form, the editor state is made up of a current document and a selection. Because there are a lot of extra pieces that an editor might need to keep in its state (such as an undo history or syntax tree), it is possible for extensions to add additional fields to the state object.

interface EditorStateConfig

Options passed when creating an editor state.

doc⁠?: string | Text

The initial document. Defaults to an empty document. Can be provided either as a plain string (which will be split into lines according to the value of the lineSeparator facet), or an instance of the Text class (which is what the state will use to represent the document).

selection⁠?: EditorSelection | {anchor: number, head⁠?: number}

The starting selection. Defaults to a cursor at the very start of the document.

extensions⁠?: Extension

Extension(s) to associate with this state.

class EditorState

The editor state class is a persistent (immutable) data structure. To update a state, you create a transaction, which produces a new state instance, without modifying the original object.

As such, never mutate properties of a state directly. That'll just break things.

readonly doc: Text

The current document.

readonly selection: EditorSelection

The current selection.

field<T>(fieldStateField<T>) → T

Retrieve the value of a state field. Throws an error when the state doesn't have that field, unless you pass false as second parameter.

update(...specs: readonly TransactionSpec[]) → Transaction

Create a transaction that updates this state. Any number of transaction specs can be passed. The changes (if any) of each spec are assumed to start in the current document (not the document produced by previous specs), and its selection and effects are assumed to refer to the document created by its own changes. The resulting transaction contains the combined effect of all the different specs. For things like selection or reconfiguration, later specs take precedence over earlier ones.

replaceSelection(textstring | Text) → StrictTransactionSpec

Create a transaction spec that replaces every selection range with the given content.

changeByRange(ffn(rangeSelectionRange) → {changes⁠?: ChangeSpec, range: SelectionRange}) → StrictTransactionSpec

Create a set of changes and a new selection by running the given function for each range in the active selection. The function can return an optional set of changes (in the coordinate space of the start document), plus an updated range (in the coordinate space of the document produced by the call's own changes). This method will merge all the changes and ranges into a single changeset and selection, and return it as a transaction spec, which can be passed to update.

changes(spec⁠?: ChangeSpec = []) → ChangeSet

Create a change set from the given change description, taking the state's document length and line separator into account.

toText(stringstring) → Text

Using the state's line separator, create a Text instance from the given string.

sliceDoc(from⁠?: number = 0, to⁠?: number = this.doc.length) → string

Return the given range of the document as a string.

facet<Output>(facetFacet<any, Output>) → Output

Get the value of a state facet.

toJSON() → any

Convert this state to a JSON-serializable object.

readonly tabSize: number

The size (in columns) of a tab in the document, determined by the tabSize facet.

readonly lineBreak: string

Get the proper line-break string for this state.

readonly indentUnit: number

The column width of an indent unit in the document. Determined by the indentUnit facet, and tabSize when that contains tabs.

readonly indentWithTabs: boolean

Whether indentation should use tabs. Will be true when the indentUnit facet contains tabs.

phrase(phrasestring) → string

Look up a translation for the given phrase (via the phrases facet), or return the original string if no translation is found.

charCategorizer(atnumber) → fn(charstring) → CharCategory

Return a function that can categorize strings (expected to represent a single grapheme cluster) into one of:

  • Word (contains an alphanumeric character or a character explicitly listed in the local language's "wordChars" language data, which should be a string)
  • Space (contains only whitespace)
  • Other (anything else)
readonly tree: Tree

Get the syntax tree for this state, which is the current (possibly incomplete) parse tree of the syntax with the highest precedence, or the empty tree if there is no syntax available.

languageDataAt<T>(namestring, posnumber) → readonly T[]

Find the values for a given language data field, either provided by the syntax or through the addLanguageData facet, for the document type at the given position. Values provided by the facet, in precedence order, will appear before those provided by the syntax.

static fromJSON(jsonany, config⁠?: EditorStateConfig = {}) → EditorState

Deserialize a state from its JSON representation.

static create(config⁠?: EditorStateConfig = {}) → EditorState

Create a new state. You'll usually only need this when initializing an editor—updated states are created by applying transactions.

static allowMultipleSelections: Facet<boolean, boolean>

A facet that, when enabled, causes the editor to allow multiple ranges to be selected. You should probably not use this directly, but let a plugin like multiple-selections handle it (which also makes sure the selections are visible in the view).

static indentation: Facet<fn(contextIndentContext, posnumber) → number>

Facet that defines a way to query for automatic indentation depth at the start of a given line.

static tabSize: Facet<number, number>

Configures the tab size to use in this state. The first (highest-precedence) value of the facet is used. If no value is given, this defaults to 4.

static lineSeparator: Facet<string, undefined | string>

The line separator to use. By default, any of "\n", "\r\n" and "\r" is treated as a separator when splitting lines, and lines are joined with "\n".

When you configure a value here, only that precise separator will be used, allowing you to round-trip documents through the editor without normalizing line separators.

static indentUnit: Facet<string, string>

Facet for overriding the unit by which indentation happens. Should be a string consisting either entirely of spaces or entirely of tabs. When not set, this defaults to 2 spaces.

static phrases: Facet<Object<string>, readonly Object[]>

Registers translation phrases. The phrase method will look through all objects registered with this facet to find translations for its argument.

static syntax: Facet<Syntax>

Facet that registers a parsing service for the state.

static globalLanguageData: Facet<Object<any>, readonly Object[]>

A facet used to register language data that should apply throughout the document, regardless of language.

static foldable: Facet<fn(stateEditorState, lineStartnumber, lineEndnumber) → null | {from: number, to: number}>

A facet that registers a code folding service. When called with the extent of a line, such a function should return a range object when a foldable that starts on that line (but continues beyond it), if one can be found.

static changeFilter: Facet<fn(trStrictTransactionSpec, stateEditorState) → false | true | readonly number[]>

Facet used to register change filters, which are called for each transaction (unless explicitly disabled), and can suppress part of the transaction's changes.

Such a function can return true to indicate that it doesn't want to do anything, false to completely stop the changes in the transaction, or a set of ranges in which changes should be suppressed. Such ranges are represented as an array of numbers, with each pair of two number indicating the start and end of a range. So for example [10, 20, 100, 110] suppresses changes between 10 and 20, and between 100 and 110.

static transactionFilter: Facet<fn(trStrictTransactionSpec, oldStateEditorState, finishfn() → Transaction) → TransactionSpec | readonly TransactionSpec[]>

Facet used to register a hook that gets a chance to update or replace transaction specs before they are applied. This will only be applied for transactions that don't have filter set to false. You can either return a single spec (possibly the input spec), or an array of specs (which will be combined in the same way as the arguments to EditorState.update).

The function passed to the filter as third argument can be used to force computation of the full transaction for the current spec (which is only done on demand for efficiency reasons).

(This functionality should be used with care. Indiscriminately modifying transaction is likely to break something or degrade the user experience.)

class SelectionRange

A single selection range. When allowMultipleSelections is enabled, a selection may hold multiple ranges. By default, selections hold exactly one range.

new SelectionRange(fromnumber, tonumber, flagsnumber)
readonly from: number

The lower side of the range.

readonly to: number

The upper side of the range.

readonly anchor: number

The anchor of the range—the side that doesn't move when you extend it.

readonly head: number

The head of the range, which is moved when the range is extended.

readonly empty: boolean

True when anchor and head are at the same position.

readonly assoc: -1 | 0 | 1

If this is a cursor that is explicitly associated with the character on one of its sides, this returns the side. -1 means the character before its position, 1 the character after, and 0 means no association.

readonly bidiLevel: number | null

The bidirectional text level associated with this cursor.

readonly goalColumn: undefined | number
map(mappingChangeDesc) → SelectionRange

Map this range through a mapping.

extend(fromnumber, to⁠?: number = from) → SelectionRange

Extend this range to cover at least from to to.

eq(otherSelectionRange) → boolean

Compare this range to another range.

toJSON() → any

Return a JSON-serializable object representing the range.

static fromJSON(jsonany) → SelectionRange

Convert a JSON representation of a range to a SelectionRange instance.

class EditorSelection

An editor selection holds one or more selection ranges.

readonly ranges: readonly SelectionRange[]

The ranges in the selection, sorted by position. Ranges cannot overlap (but they may touch, if they aren't empty).

readonly primaryIndex: number

The index of the primary range in the selection (which is usually the range that was added last).

map(mappingChangeDesc) → EditorSelection

Map a selection through a mapping. Mostly used to adjust the selection position for changes.

eq(otherEditorSelection) → boolean

Compare this selection to another selection.

readonly primary: SelectionRange

Get the primary selection range. Usually, you should make sure your code applies to all ranges, by using methods like changeByRange.

asSingle() → EditorSelection

Make sure the selection only has one range. Returns a selection holding only the primary range from this selection.

addRange(rangeSelectionRange, primary⁠?: boolean = true) → EditorSelection

Extend this selection with an extra range.

replaceRange(rangeSelectionRange, which⁠?: number = this.primaryIndex) → EditorSelection

Replace a given range with another range, and then normalize the selection to merge and sort ranges if necessary.

toJSON() → any

Convert this selection to an object that can be serialized to JSON.

static fromJSON(jsonany) → EditorSelection

Create a selection from a JSON representation.

static single(anchornumber, head⁠?: number = anchor) → EditorSelection

Create a selection holding a single range.

static create(ranges: readonly SelectionRange[], primaryIndex⁠?: number = 0) → EditorSelection

Sort and merge the given set of ranges, creating a valid selection.

static cursor(posnumber, assoc⁠?: number = 0, bidiLevel⁠?: number, goalColumn⁠?: number) → SelectionRange

Create a cursor selection range at the given position. You can probably ignore association and bidi level in most situations.

static range(anchornumber, headnumber, goalColumn⁠?: number) → SelectionRange

Create a selection range.

re-export Text
enum CharCategory

This is used to categorize characters into three categories—word characters, whitespace, and anything else. It is used do things like selecting by word.


Changes and Transactions

CodeMirror treats changes to the document as objects, which are usually part of a transaction.

This is how you'd make a change to a document (replacing “world” with “editor”) and create a new state with the updated document:

let state = EditorState.create({doc: "hello world"})
let transaction = state.update({changes: {from: 6, to: 11, insert: "editor"}})
console.log(transaction.state.doc.toString()) // "hello editor"
type ChangeSpec = {from: number, to⁠?: number, insert⁠?: string | Text} | ChangeSet | readonly ChangeSpec[]

This type is used as argument to EditorState.changes and in the changes field of transaction specs to succinctly describe document changes. It may either be a plain object describing a change (a deletion, insertion, or replacement, depending on which fields are present), a change set, or an array of change specs.

class ChangeDesc

A change description is a variant of change set that doesn't store the inserted text. As such, it can't be applied, but is cheaper to store and manipulate.

readonly sections: readonly number[]
readonly length: number

The length of the document before the change.

readonly newLength: number

The length of the document after the change.

readonly empty: boolean

False when there are actual changes in this set.

iterGaps(ffn(posAnumber, posBnumber, lengthnumber))

Iterate over the unchanged parts left by these changes.

iterChangedRanges(ffn(fromAnumber, toAnumber, fromBnumber, toBnumber), individual⁠?: boolean = false)

Iterate over the ranges changed by these changes. (See ChangeSet.iterChanges for a variant that also provides you with the inserted text.)

When individual is true, adjacent changes (which are kept separate for position mapping) are reported separately.

readonly invertedDesc: ChangeDesc

Get a description of the inverted form of these changes.

composeDesc(otherChangeDesc) → ChangeDesc

Compute the combined effect of applying another set of changes after this one. The length of the document after this set should match the length before other.

mapDesc(otherChangeDesc, before⁠?: boolean = false) → ChangeDesc

Map this description, which should start with the same document as other, over another set of changes, so that it can be applied after it.

mapPos(posnumber, assoc⁠?: number = -1, mode⁠?: MapMode = MapMode.Simple) → number

Map a given position through these changes.

assoc indicates which side the position should be associated with. When it is negative or zero, the mapping will try to keep the position close to the character before it (if any), and will move it before insertions at that point or replacements across that point. When it is positive, the position is associated with the character after it, and will be moved forward for insertions at or replacements across the position. Defaults to -1.

mode determines whether deletions should be reported. It defaults to MapMode.Simple (don't report deletions).

mapPosStable(posnumber, side⁠?: number = -1) → number

Map a position in a way that reliably produces the same position for a sequence of changes, regardless of the order in which they were mapped and applied. This will map a position to the start (or end) through all adjacent changes next to it, and often produces more surprising results than mapPos. But it can be useful in cases where it is important that all clients in a collaborative setting end up doing the precise same mapping.

touchesRange(fromnumber, to⁠?: number = from) → false | true | "cover"

Check whether these changes touch a given range. When one of the changes entirely covers the range, the string "cover" is returned.

class ChangeSet extends ChangeDesc

A change set represents a group of modifications to a document. It stores the document length, and can only be applied to documents with exactly that length.

apply(docText) → Text

Apply the changes to a document, returning the modified document.

mapDesc(otherChangeDesc, before⁠?: boolean = false) → ChangeDesc

Map this set, which should start with the same document as other, over another set of changes, so that it can be applied after it. When before is true, map as if the changes in other happened before the ones in this.

invert(docText) → ChangeSet

Given the document as it existed before the changes, return a change set that represents the inverse of this set, which could be used to go from the document created by the changes back to the document as it existed before the changes.

compose(otherChangeSet) → ChangeSet

Combine two subsequent change sets into a single set. other must start in the document produced by this. If this goes docAdocB and other represents docBdocC, the returned value will represent the change docAdocC.

map(otherChangeDesc, before⁠?: boolean = false) → ChangeSet

Given another change set starting in the same document, maps this change set over the other, producing a new change set that can be applied to the document produced by applying other. When before is true, order changes as if this comes before other, otherwise (the default) treat other as coming first.

Given two changes A and B, A.compose( and B.compose(, true)) will produce the same document. This provides a basic form of operational transformation, and can be used for collaborative editing.

iterChanges(ffn(fromAnumber, toAnumber, fromBnumber, toBnumber, insertedText), individual⁠?: boolean = false)

Iterate over the changed ranges in the document, calling f for each.

readonly desc: ChangeDesc

Get a change description for this change set.

static of(changesChangeSpec, lengthnumber, lineSep⁠?: string) → ChangeSet

Create a change set for the given changes, for a document of the given length, using lineSep as line separator.

static empty(lengthnumber) → ChangeSet

Create an empty changeset of the given length.

type TransactionSpec

Describes a transaction when calling the EditorState.update method.

changes⁠?: ChangeSpec

The changes to the document made by this transaction.

selection⁠?: EditorSelection | {anchor: number, head⁠?: number}

When set, this transaction explicitly updates the selection. Offsets in this selection should refer to the document as it is after the transaction.

effects⁠?: StateEffect<any> | readonly StateEffect<any>[]

Attach state effects to this transaction.

annotations⁠?: Annotation<any> | readonly Annotation<any>[]

Set annotations for this transaction.

scrollIntoView⁠?: boolean

When set to true, the transaction is marked as needing to scroll the current selection into view.

filter⁠?: boolean

By default, transactions can be modified by change filters and transaction filters. You can set this to false to disable that.

reconfigure⁠?: ReconfigurationSpec

Specifies that the state should be reconfigured.

type ReconfigurationSpec

Type used in transaction specs to indicate how the state should be reconfigured.

full⁠?: Extension

If given, this will replace the state's entire configuration with a new configuration derived from the given extension. Previously replaced extensions are reset.

append⁠?: Extension

When given, this extension is appended to the current configuration.

type StrictTransactionSpec

A transactions spec with most of its fields narrowed down to more predictable types. This type is used to pass something more usable than a raw transaction spec to, for example, change filters.

changes: ChangeSet
selection: EditorSelection | undefined
effects: readonly StateEffect<any>[]
annotations: readonly Annotation<any>[]
scrollIntoView: boolean
filter: boolean
reconfigure: ReconfigurationSpec | undefined

class Transaction

Changes to the editor state are grouped into transactions. Typically, a user action creates a single transaction, which may contain any number of document changes, may change the selection, or have other effects. Create a transaction by calling EditorState.update.

readonly state: EditorState

The new state created by the transaction.

readonly startState: EditorState

The state from which the transaction starts.

readonly changes: ChangeSet

The document changes made by this transaction.

readonly selection: EditorSelection | undefined

The selection set by this transaction, or undefined if it doesn't explicitly set a selection.

readonly effects: readonly StateEffect<any>[]

The effects added to the transaction.

readonly reconfigured: ReconfigurationSpec | undefined

Holds an object when this transaction reconfigures the state.

annotation<T>(typeAnnotationType<T>) → undefined | T

Get the value of the given annotation type, if any.

readonly docChanged: boolean

Indicates whether the transaction changed the document.

readonly scrolledIntoView: boolean

Query whether the selection should be scrolled into view after applying this transaction.

static time: AnnotationType<number>

Annotation used to store transaction timestamps.

static userEvent: AnnotationType<string>

Annotation used to associate a transaction with a user interface event. The view will set this to...

  • "input" when the user types text
  • "delete" when the user deletes the selection or text near the selection
  • "keyboardselection" when moving the selection via the keyboard
  • "pointerselection" when moving the selection through the pointing device
  • "paste" when pasting content
  • "cut" when cutting
  • "drop" when content is inserted via drag-and-drop
static addToHistory: AnnotationType<boolean>

Annotation indicating whether a transaction should be added to the undo history or not.

class Annotation<T>

Annotations are tagged values that are used to add metadata to transactions in an extensible way. They should be used to model things that effect the entire transaction (such as its time stamp or information about its origin). For effects that happen alongside the other changes made by the transaction, state effects are more appropriate.

readonly type: AnnotationType<T>
readonly value: T
static define<T>() → AnnotationType<T>

Define a new type of annotation.

class AnnotationType<T>

Marker that identifies a type of annotation.

of(valueT) → Annotation<T>

class StateEffect<Value>

State effects can be used to represent additional effects associated with a transaction. They are often useful to model changes to custom state fields, when those changes aren't implicit in document or selection changes.

readonly value: Value

The value of this effect.

map(mappingChangeDesc) → undefined | StateEffect<Value>

Map this effect through a position mapping. Will return undefined when that ends up deleting the effect.

is<T>(typeStateEffectType<T>) → boolean

Tells you whether this effect object is of a given type.

static define<Value = null>(spec⁠?: Object = {}) → StateEffectType<Value>

Define a new effect type. The type parameter indicates the type of values that his effect holds.

map⁠?: fn(valueValue, mappingChangeDesc) → undefined | Value

Provides a way to map an effect like this through a position mapping. When not given, the effects will simply not be mapped. When the function returns undefined, that means the mapping deletes the effect.

static mapEffects(effects: readonly StateEffect<any>[], mappingChangeDesc) → readonly StateEffect<any>[]

Map an array of effects through a change set.

class StateEffectType<Value>

Representation of a type of state effect. Defined with StateEffect.define.

of(valueValue) → StateEffect<Value>

Create a state effect instance of this type.

enum MapMode

Distinguishes different ways in which positions can be mapped.


Map a position to a valid new position, even when its context was deleted.


Return -1 if deletion happens across the position.


Return -1 if the character before the position is deleted.


Return -1 if the character after the position is deleted.

Extending Editor State

The following are some types and mechanisms used when writing extensions for the editor state.

type StateCommand = fn(target: {state: EditorState, dispatch: fn(transactionTransaction)}) → boolean

Subtype of Command that doesn't require access to the actual editor view. Mostly useful to define commands that can be run and tested outside of a browser environment.

type Extension = {[unique symbol]: true} | {extension: Extension} | readonly Extension[]

Extension values can be provided when creating a state to attach various kinds of configuration and behavior information. It may an extension object, such as a state field or facet provider, any object with an extension in its extension property, or an array of extension values.

class StateField<Value>

Fields can store additional information in an editor state, and keep it in sync with the rest of the state.

[unique symbol]: true

State field instances can be used as Extension values to enable the field in a given state. (This symbol is a TypeScript-related trick to mark it as an extension value.)

static define<Value>(configObject) → StateField<Value>

Define a state field.

create(stateEditorState) → Value

Creates the initial value for the field when a state is created.

update(valueValue, transactionTransaction) → Value

Compute a new value from the field's previous value and a transaction.

compare⁠?: fn(aValue, bValue) → boolean

Compare two values of the field, returning true when they are the same. This is used to avoid recomputing facets that depend on the field when its value did not change. Defaults to using ==.

provide⁠?: readonly (Facet<Value, any> | fn(fieldStateField<Value>) → Extension)[]

Provide values for facets based on the value of this field. You can pass facets that directly take the field value as input, or use facet's from and nFrom methods to provide a getter function.

class Facet<Input, Output = readonly Input[]>

A facet is a value that is assicated with a state and can be influenced by any number of extensions. Extensions can provide input values for the facet, and the facet combines those into an output value.

Examples of facets are the theme styles associated with an editor (which are all stored) or the tab size (which is reduced to a single value, using the input with the hightest precedence).

of(valueInput) → Extension

Returns an extension that adds the given value for this facet.

compute(deps: readonly ("doc" | "selection" | Facet<any, any> | StateField<any>)[], getfn(stateEditorState) → Input) → Extension

Create an extension that computes a value for the facet from a state. You must take care to declare the parts of the state that this value depends on, since your function is only called again for a new state when one of those parts changed.

In most cases, you'll want to use the provide option when defining a field instead.

computeN(deps: readonly ("doc" | "selection" | Facet<any, any> | StateField<any>)[], getfn(stateEditorState) → readonly Input[]) → Extension

Create an extension that computes zero or more values for this facet from a state.

from<T>(getfn(valueT) → Input, prec⁠?: Precedence) → fn(fieldStateField<T>) → Extension

Helper method for registering a facet source with a state field via its provide option. Returns a value that can be passed to that option to make the field automatically provide a value for this facet.

nFrom<T>(getfn(valueT) → readonly Input[], prec⁠?: Precedence) → fn(fieldStateField<T>) → Extension

Helper for providing a dynamic number of values for this facet from a state field.

static define<Input, Output = readonly Input[]>(config⁠?: Object = {}) → Facet<Input, Output>

Define a new facet.

combine⁠?: fn(value: readonly Input[]) → Output

How to combine the input values into a single output value. When not given, the array of input values becomes the output. This will immediately be called on creating the facet, with an empty array, to compute the facet's default value when no inputs are present.

compare⁠?: fn(aOutput, bOutput) → boolean

How to compare output values to determine whether the value of the facet changed. Defaults to comparing by === or, if no combine function was given, comparing each element of the array with ===.

compareInput⁠?: fn(aInput, bInput) → boolean

How to compare input values to avoid recomputing the output value when no inputs changed. Defaults to comparing with ===.

static⁠?: boolean

Static facets can not contain dynamic inputs.

precedence(extensionExtension, valuePrecedence) → {readonly e: Extension, readonly prec: number, [unique symbol]: true}

By default extensions are registered in the order they are found the flattened form of nested array that was provided. Individual extension values can be assigned a precedence to override this. Extensions that do not have a precedence set get the precedence of the nearest parent with a precedence, or "default" if there is no such parent. The final ordering of extensions is determined by first sorting by precedence and then by order within each precedence.

type Precedence = "fallback" | "default" | "extend" | "override"

Valid values of the second argument to precedence.

  • "fallback": A precedence below the default precedence, which will cause default-precedence extensions to override it even if they are specified later in the extension ordering.
  • "default": The regular default precedence.
  • "extend": A higher-than-default precedence.
  • "override": Precedence above the "default" and "extend" precedences.
tagExtension(tagstring | Symbol, extensionExtension) → {readonly tag: string | Symbol, readonly extension: Extension, [unique symbol]: true}

Tagged extensions can be used to make a configuration dynamic. Tagging an extension allows you to later replace it with another extension. A given tag may only occur once within a given configuration.

interface Syntax

Syntax parsing services must provide this interface.

getTree(stateEditorState) → Tree

Read the current syntax tree from a state. This may return an incomplete tree.

parsePos(stateEditorState) → number

Get the position up to which the current document has been parsed.

ensureTree(stateEditorState, uptonumber, timeout⁠?: number) → null | Tree

Get a tree that covers the document at least up to upto. If that involves more than timeout milliseconds of work, return null instead. Don't call this as a matter of course in, for example, state updates or decorating functions, since it'll make the editor unresponsive. Calling it in response to a specific user command can be appropriate.

languageData: Facet<Object<any>, readonly Object[]>

A facet through which to install language data for this language.

languageDataFacetAt(stateEditorState, posnumber) → Facet<Object<any>, readonly Object[]>

Return the facet that stores the language data for the given position. This'll usually be the be the grammar's own language data, but with nested grammars it may be the data facet from some inner language.

class IndentContext

Indentation contexts are used when calling EditorState.indentation. They provide helper utilities useful in indentation logic, and can selectively override the indentation reported for some lines.

new IndentContext(stateEditorState, overrideIndentation⁠?: fn(posnumber) → number, simulateBreak⁠?: number)

Create an indent context.

The optional second argument can be used to override line indentations provided to the indentation helper function, which is useful when implementing region indentation, where indentation for later lines needs to refer to previous lines, which may have been reindented compared to the original start state. If given, this function should return -1 for lines (given by start position) that didn't change, and an updated indentation otherwise.

The third argument can be used to make it look, to the indent logic, like a line break was added at the given position (which is mostly just useful for implementing insertNewlineAndIndent.

readonly state: EditorState

The editor state.

readonly unit: number

The indent unit (number of columns per indentation level).

textAfterPos(posnumber) → string

Get the text directly after pos, either the entire line or the next 100 characters, whichever is shorter.

countColumn(linestring, posnumber) → number

find the column position (taking tabs into account) of the given position in the given string.

lineIndent(lineLine) → number

Find the indentation column of the given document line.

column(posnumber) → number

Find the column for the given position.

languageDataProp: NodeProp<Facet<Object<any>, readonly Object[]>>

A node prop stored on a grammar's top node to indicate the facet used to store language data related to that language.


combineConfig<Config>(configs: readonly Partial<Config>[], defaultsPartial<Config>, combine⁠?: {[P in keyof Config]: fn(firstConfig[P], secondConfig[P]) → Config[P] = {}) → Config

Utility function for combining behaviors to fill in a config object from an array of provided configs. Will, by default, error when a field gets two values that aren't ===-equal, but you can provide combine functions per field to do something else.

text module

The Text type stores documents in an immutable tree-shaped representation that allows:

Line numbers start at 1. Character positions are counted from zero, and count each line break and UTF-16 code unit as one unit.

abstract class Text implements Iterable<string>

The document tree type.

abstract readonly length: number

The length of the string.

abstract readonly lines: number

The number of lines in the string (always >= 1).

[symbol iterator]() → Iterator<string>
lineAt(posnumber) → Line

Get the line description around the given position.

line(nnumber) → Line

Get the description for the given (1-based) line number.

replace(fromnumber, tonumber, textText) → Text

Replace a range of the text with the given lines. text should have a length of at least one.

append(textText) → Text

Append another document to this one.

slice(fromnumber, to⁠?: number = this.length) → Text

Retrieve the lines between the given points.

abstract sliceString(fromnumber, to⁠?: number, lineSep⁠?: string) → string

Retrive a part of the document as a string

eq(otherText) → boolean

Test whether this text is equal to another instance.

iter(dir⁠?: 1 | -1 = 1) → TextIterator

Iterate over the text. When dir is -1, iteration happens from end to start. This will return lines and the breaks between them as separate strings, and for long lines, might split lines themselves into multiple chunks as well.

iterRange(fromnumber, to⁠?: number = this.length) → TextIterator

Iterate over a range of the text. When from > to, the iterator will run in reverse.

iterLines(from⁠?: number = 0) → TextIterator

Iterate over lines in the text, starting at position (not line number) from. An iterator returned by this combines all text on a line into a single string (which may be expensive for very long lines), and skips line breaks (its lineBreak property is always false).

static of(text: readonly string[]) → Text

Create a Text instance for the given array of lines.

static empty: Text

The empty text.

class Line

This type describes a line in the document. It is created on-demand when lines are queried.

readonly from: number

The position of the start of the line.

readonly to: number

The position at the end of the line (before the line break, if this isn't the last line).

readonly number: number

This line's line number (1-based).

readonly length: number

The length of the line (not including any line break after it).

slice(from⁠?: number = 0, to⁠?: number = this.length) → string

Retrieve a part of the content of this line. This is a method, rather than, say, a string property, to avoid concatenating long lines whenever they are accessed. Try to write your code, if it is going to be doing a lot of line-reading, to read only the parts it needs.

findClusterBreak(startnumber, forwardboolean) → number

Find the next (or previous if forward is false) grapheme cluster break from the given start position (as an offset inside the line, not the document). Will return a position greater than (or less than if forward is false) start unless there is no such index in the string.

interface TextIterator implements Iterator<string>

A text iterator iterates over a sequence of strings.

next(skip⁠?: number) → TextIterator

Retrieve the next string. Optionally skip a given number of positions after the current position. Always returns the object itself.

value: string

The current string. Will be "" when the cursor is at its end or next hasn't been called on it yet.

done: boolean

Whether the end of the iteration has been reached. You should probably check this right after calling next.

lineBreak: boolean

Whether the current string represents a line break.

Column Utilities

countColumn(stringstring, nnumber, tabSizenumber) → number

Count the column position at the given offset into the string, taking extending characters and tab size into account.

findColumn(stringstring, nnumber, colnumber, tabSizenumber) → {offset: number, leftOver: number}

Find the offset that corresponds to the given column position in a string, taking extending characters and tab size into account.

Glyph Clusters

nextClusterBreak(strstring, posnumber) → number

Returns a grapheme cluster end after (not equal to) pos, if possible. Moves across surrogate pairs, extending characters, characters joined with zero-width joiners, and flag emoji.

prevClusterBreak(strstring, posnumber) → number

Returns a grapheme cluster end before pos, if possible.

Code Points

If you support environments that don't yet have String.fromCodePoint and codePointAt, this package provides portable replacements for them.

codePointAt(strstring, posnumber) → number

Find the code point at the given position in a string (as in the codePointAt string method).

fromCodePoint(codenumber) → string

Given a Unicode codepoint, return the JavaScript string that respresents it (as in String.fromCodePoint.

codePointSize(codenumber) → 1 | 2

The first character that takes up two positions in a JavaScript string. It is often useful to compare with this after calling codePointAt, to figure out whether your character takes up 1 or 2 index positions.

view module

The “view” is the part of the editor that the user sees—a DOM component that displays the editor state and allows text input.

class EditorView

An editor view represents the editor's user interface. It holds the editable DOM surface, and possibly other elements such as the line number gutter. It handles events and dispatches state transactions for editing actions.

new EditorView(config⁠?: Object = {})

Construct a new view. You'll usually want to put view.dom into your document after creating a view, so that the user can see it.


Configuration options.

state⁠?: EditorState

The view's initial state. Defaults to an extension-less state with an empty document.

root⁠?: Document | ShadowRoot

If the view is going to be mounted in a shadow root or document other than the one held by the global variable document (the default), you should pass it here.

dispatch⁠?: fn(trTransaction)

Override the transaction dispatch function for this editor view. Your implementation, if provided, should probably call the view's update method.

parent⁠?: Element

When given, the editor is immediately appended to the given element on creation. (Otherwise, you'll have to place the view's dom element in the document yourself.)

readonly state: EditorState

The current editor state.

readonly viewport: {from: number, to: number}

To be able to display large documents without consuming too much memory or overloading the browser, CodeMirror only draws the code that is visible (plus a margin around it) to the DOM. This property tells you the extent of the current drawn viewport, in document positions.

readonly visibleRanges: readonly {from: number, to: number}[]

When there are, for example, large collapsed ranges in the viewport, its size can be a lot bigger than the actual visible content. Thus, if you are doing something like styling the content in the viewport, it is preferable to only do so for these ranges, which are the subset of the viewport that is actually drawn.

readonly root: DocumentOrShadowRoot

The document or shadow root that the view lives in.

readonly dom: HTMLElement

The DOM element that wraps the entire editor view.

readonly scrollDOM: HTMLElement

The DOM element that can be made to scroll.

readonly contentDOM: HTMLElement

The editable DOM element holding the editor content. You should not, usually, interact with this content directly, though the DOM, since the editor will immediately undo most of the changes you make. Instead, use transactions to modify content, and decorations to style it.


All regular editor state updates should go through this. It takes a transaction or transaction spec and updates the view to show the new state produced by that transaction. Its implementation can be overridden with an option. Does not have to be called as a method.

update(transactions: readonly Transaction[])

Update the view for the given array of transactions. This will update the visible document and selection to match the state produced by the transactions, and notify view plugins of the change. You should usually call dispatch instead, which uses this as a primitive.


Reset the view to the given state. (This will cause the entire document to be redrawn and all view plugins to be reinitialized, so you should probably only use it when the new state isn't derived from the old state. Otherwise, use update instead.)

readonly themeClasses: string

Get the CSS classes for the currently active editor themes.

domAtPos(posnumber) → {node: Node, offset: number}

Find the DOM parent node and offset (child offset if node is an element, character offset when it is a text node) at the given document position.

posAtDOM(nodeNode, offset⁠?: number = 0) → number

Find the document position at the given DOM node. Can be useful for associating positions with DOM events. Will raise an error when node isn't part of the editor content.

requestMeasure<T>(request⁠?: {key⁠?: any, read: fn(viewEditorView) → T, write: fn(measureT, viewEditorView)})

Make sure plugins get a chance to measure the DOM before the next frame. Calling this is preferable to messing with the DOM directly from, for example, an even handler, because it'll make sure measuring and drawing done by other components is synchronized, avoiding unnecessary DOM layout computations.

pluginField<T>(fieldPluginField<T>) → readonly T[]

Collect all values provided by the active plugins for a given field.

plugin<T>(pluginViewPlugin<T>) → null | T

Get the value of a specific plugin, if present. Note that plugins that crash can be dropped from a view, so even when you know you registered a given plugin, it is recommended to check the return value of this method.

blockAtHeight(heightnumber, editorTop⁠?: number) → BlockInfo

Find the line or block widget at the given vertical position. editorTop, if given, provides the vertical position of the top of the editor. It defaults to the editor's screen position (which will force a DOM layout).

visualLineAtHeight(heightnumber, editorTop⁠?: number) → BlockInfo

Find information for the visual line (see visualLineAt) at the given vertical position. The resulting block info might hold another array of block info structs in its type field if this line consists of more than one block.

Heights are interpreted relative to the given editorTop position. When not given, the top position of the editor's content element is taken.

visualLineAt(posnumber, editorTop⁠?: number = 0) → BlockInfo

Find the extent and height of the visual line (the content shown in the editor as a line, which may be smaller than a document line when broken up by block widgets, or bigger than a document line when line breaks are covered by replaced decorations) at the given position.

Vertical positions are computed relative to the editorTop argument. You can pass view.dom.getBoundingClientRect().top here to get screen coordinates.

viewportLines(ffn(heightBlockInfo), editorTop⁠?: number)

Iterate over the height information of the lines in the viewport.

readonly contentHeight: number

The editor's total content height.

moveByChar(startSelectionRange, forwardboolean, by⁠?: fn(initialstring) → fn(nextstring) → boolean) → SelectionRange

Move a cursor position by grapheme cluster. forward determines whether the motion is away from the line start, or towards it. Motion in bidirectional text is in visual order, in the editor's text direction. When the start position was the last one on the line, the returned position will be across the line break. If there is no further line, the original position is returned.

moveByGroup(startSelectionRange, forwardboolean) → SelectionRange

Move a cursor position across the next group of either letters or non-letter non-whitespace characters.

moveToLineBoundary(startSelectionRange, forwardboolean, includeWrap⁠?: boolean = true) → SelectionRange

Move to the next line boundary in the given direction. If includeWrap is true, line wrapping is on, and there is a further wrap point on the current line, the wrap point will be returned. Otherwise this function will return the start or end of the line.

moveVertically(startSelectionRange, forwardboolean, distance⁠?: number) → SelectionRange

Move a cursor position vertically. When distance isn't given, it defaults to moving to the next line (including wrapped lines). Otherwise, distance should provide a positive distance in pixels.

When start has a goalColumn, the vertical motion will use that as a target horizontal position. Otherwise, the cursor's own horizontal position is used. The returned cursor will have its goal column set to whichever column was used.


Scroll the given document position into view.

posAtCoords(coords: {x: number, y: number}) → number

Get the document position at the given screen coordinates. Returns -1 if no valid position could be found.

coordsAtPos(posnumber, side⁠?: -1 | 1 = 1) → null | {left: number, right: number, top: number, bottom: number}

Get the screen coordinates at the given document position.

readonly defaultCharacterWidth: number

The default width of a character in the editor. May not accurately reflect the width of all characters.

readonly defaultLineHeight: number

The default height of a line in the editor.

readonly textDirection: Direction

The text direction (direction CSS property) of the editor.

readonly lineWrapping: boolean

Whether this editor wraps lines (as determined by the white-space CSS property of its content element).

bidiSpans(lineLine) → readonly BidiSpan[]

Returns the bidirectional text structure of the given line (which should be in the current document) as an array of span objects. The order of these spans matches the text direction—if that is left-to-right, the leftmost spans come first, otherwise the rightmost spans come first.

readonly hasFocus: boolean

Check whether the editor has focus.


Put focus on the editor.


Clean up this editor view, removing its element from the document, unregistering event handlers, and notifying plugins. The view instance can no longer be used after calling this.

static styleModule: Facet<StyleModule<Object>>

Facet to add a style module to an editor view. The view will ensure that the module is registered in its document root.

static domEventHandlers(handlers: {[Type in keyof HTMLElementEventMap]: fn(eventHTMLElementEventMap[Type], viewEditorView) → boolean) → Extension

Facet that can be used to add DOM event handlers. The value should be an object mapping event names to handler functions. The first such function to return true will be assumed to have handled that event, and no other handlers or built-in behavior will be activated for it.

static exceptionSink: Facet<fn(exceptionany)>

Allows you to provide a function that should be called when the library catches an exception from an extension (mostly from view plugins, but may be used by other extensions to route exceptions from user-code-provided callbacks). This is mostly useful for debugging and logging. See logException.

static updateListener: Facet<fn(updateViewUpdate)>

A facet that can be used to have a listener function be notified every time the view updates.

static editable: Facet<boolean, boolean>

Facet that controls whether the editor content is editable. When its the highest-precedence value is false, editing is disabled, and the content element will no longer have its contenteditable attribute set to true. (Note that this doesn't affect API calls that change the editor content, even when those are bound to keys or buttons.)

static dragMovesSelection: Facet<fn(eventMouseEvent) → boolean>

Facet used to configure whether a given selection drag event should move or copy the selection. The given predicate will be called with the mousedown event, and can return true when the drag should move the content.

static clickAddsSelectionRange: Facet<fn(eventMouseEvent) → boolean>

Facet used to configure whether a given selecting click adds a new range to the existing selection or replaces it entirely.

static mouseSelectionStyle: Facet<fn(viewEditorView, eventMouseEvent) → null | MouseSelectionStyle>

Allows you to influence the way mouse selection happens. The functions in this facet will be called for a mousedown event on the editor, and can return an object that overrides the way a selection is computed from that mouse click or drag.

static decorations: Facet<DecorationSet>

A facet that determines which decorations are shown in the view. See also view plugins, which have a separate mechanism for providing decorations.

static theme(specObject<Style>, options⁠?: {dark⁠?: boolean}) → Extension

Create a theme extension. The argument object should map theme selectors to styles, which are (potentially nested) style declarations providing the CSS styling for the selector.

When dark is set to true, the theme will be marked as dark, which causes the base theme rules marked with @dark to apply instead of those marked with @light.

static baseTheme(specObject<Style>) → Extension

Create an extension that adds styles to the base theme. The given object works much like the one passed to theme, but allows selectors to be marked by adding @dark to their end to only apply when there is a dark theme active, or by @light to only apply when there is no dark theme active.

static lineWrapping: Extension

An extension that enables line wrapping in the editor.

static contentAttributes: Facet<Object<string>, Object>

Facet that provides attributes for the editor's editable DOM element.

static editorAttributes: Facet<Object, Object>

Facet that provides editor DOM attributes for the editor's outer element.

themeClass(selectorstring) → string

Create a set of CSS class names for the given theme selector, which can be added to a DOM element within an editor to make themes able to style it. Theme selectors can be single words or words separated by dot characters. In the latter case, the returned classes combine those that match the full name and those that match some prefix—for example "" will match both the theme styles specified as "" and those with just "panel". More specific theme styles (with more dots) take precedence.

enum BlockType

The different types of blocks that can occur in an editor view.


A line of text.


A block widget associated with the position after it.


A block widget associated with the position before it.


A block widget replacing a range of content.

class BlockInfo

Record used to represent information about a block-level element in the editor view.

readonly from: number

The start of the element in the document.

readonly length: number

The length of the element.

readonly top: number

The top position of the element.

readonly height: number

Its height.

readonly type: BlockType | readonly BlockInfo[]

The type of element this is. When querying lines, this may be an array of all the blocks that make up the line.

readonly to: number

The end of the element as a document position.

readonly bottom: number

The bottom position of the element.

enum Direction

Used to indicate text direction.


class BidiSpan

new BidiSpan(fromnumber, tonumber, levelnumber)
readonly from: number
readonly to: number
readonly level: number
readonly dir: 0 | 1
side(endboolean, dirDirection) → number
static find(order: readonly BidiSpan[], indexnumber, levelnumber, assocnumber) → number

Extending the View

type Command = fn(targetEditorView) → boolean

Command functions are used in key bindings and other types of user actions. Given an editor view, they check whether their effect can apply to the editor, and if it can, perform it as a side effect (which usually means dispatching a transaction) and return true.

class ViewPlugin<T extends PluginValue>

View plugins associate stateful values with a view. They can influence the way the content is drawn, and are notified of things that happen in the view.

extension: Extension

Instances of this class act as extensions.

provide<V>(fieldPluginField<V>, getfn(pluginT) → V) → ViewPlugin<T>

Create a new version of this plugin that provides a given plugin field.

decorations<V extends {decorations: DecorationSet} & PluginValue>() → ViewPlugin<T>

Create a new version of this plugin that provides decorations. Decorations provided by plugins can observe the editor and base on, for example, the current viewport. On the other hand, they should not influence the viewport, for example through collapsed regions or large widgets.

When the plugin value type has a decorations property, that is used to provide the decorations when no explicit getter is provided.

eventHandlers(handlers: {[Type in keyof HTMLElementEventMap]: fn(eventHTMLElementEventMap[Type], viewEditorView) → boolean) → ViewPlugin<T>

Convenience method that extends a view plugin to automatically register DOM event handlers.

static define<T extends PluginValue>(createfn(viewEditorView) → T) → ViewPlugin<T>

Define a plugin from a constructor function that creates the plugin's value, given an editor view.

static fromClass<T extends PluginValue>(clsObject) → ViewPlugin<T>

Create a plugin for a class whose constructor takes a single editor view as argument.

interface PluginValue

This is the interface plugin objects conform to.

update⁠?: fn(_updateViewUpdate)

Notifies the plugin of an update that happened in the view. This is called before the view updates its DOM. It is responsible for updating the plugin's internal state (including any state that may be read by plugin fields). It should not change the DOM, or read the DOM in a way that triggers a layout recomputation.

destroy⁠?: fn()

Called when the plugin is no longer going to be used. Should revert any changes the plugin made to the DOM.

class PluginField<T>

Plugin fields are a mechanism for allowing plugins to provide values that can be retrieved through the pluginField view method.

static define<T>() → PluginField<T>
static scrollMargins: PluginField<null | Partial<{left: number, right: number, top: number, bottom: number}>>

Plugins can provide additional scroll margins (space around the sides of the scrolling element that should be considered invisible) through this field. This can be useful when the plugin introduces elements that cover part of that element (for example a horizontally fixed gutter).

class ViewUpdate

View plugins are given instances of this class, which describe what happened, whenever the view is updated.

readonly changes: ChangeSet

The changes made to the document by this update.

readonly prevState: EditorState

The previous editor state.

readonly view: EditorView

The editor view that the update is associated with.

readonly state: EditorState

The new editor state.

readonly transactions: readonly Transaction[]

The transactions involved in the update. May be empty.

readonly viewportChanged: boolean

Tells you whether the viewport changed in this update.

readonly heightChanged: boolean

Indicates whether the line height in the editor changed in this update.

readonly focusChanged: boolean

True when this update indicates a focus change.

readonly docChanged: boolean

Whether the document changed in this update.

readonly selectionSet: boolean

Whether the selection was explicitly set in this update.

logException(stateEditorState, exceptionany, context⁠?: string)

Log or report an unhandled exception in client code. Should probably only be used by extension code that allows client code to provide functions, and calls those functions in a context where an exception can't be propagated to calling code in a reasonable way (for example when in an event handler).

Either calls a handler registered with EditorView.exceptionSink, window.onerror, if defined, or console.error (in which case it'll pass context, when given, as first argument).

interface MouseSelectionStyle

Interface that objects registered with EditorView.mouseSelectionStyle must conform to.

get(curEventMouseEvent, extendboolean, multipleboolean) → EditorSelection

Return a new selection for the mouse gesture that starts with the event that was originally given to the constructor, and ends with the event passed here. In case of a plain click, those may both be the mousedown event, in case of a drag gesture, the latest mousemove event will be passed.

When extend is true, that means the new selection should, if possible, extend the start selection. If multiple is true, the new selection should be added to the original selection.


Called when the view is updated while the gesture is in progress. When the document changed, it may be necessary to map some data (like the original selection or start position) through the changes.

multipleSelections() → Extension

Returns an extension that enables multiple selections for the editor. Secondary cursors and selected ranges are drawn with simple decorations, and might not look the same as the primary native selection.

highlightSpecialChars(config⁠?: Object = {}) → Extension

Returns an extension that installs highlighting of special characters.


Configuration options.

render⁠?: fn(codenumber, descriptionstring | null, placeHolderstring) → HTMLElement

An optional function that renders the placeholder elements.

specialChars⁠?: RegExp

Regular expression that matches the special characters to highlight.

addSpecialChars⁠?: RegExp

Regular expression that can be used to add characters to the default set of characters to highlight.

Key bindings

type KeyBinding

Key bindings associate key names with command-style functions.

Key names may be strings like "Shift-Ctrl-Enter"—a key identifier prefixed with zero or more modifiers. Key identifiers are based on the strings that can appear in KeyEvent.key. Use lowercase letters to refer to letter keys (or uppercase letters if you want shift to be held). You may use "Space" as an alias for the " " name.

Modifiers can be given in any order. Shift- (or s-), Alt- (or a-), Ctrl- (or c- or Control-) and Cmd- (or m- or Meta-) are recognized.

When a key binding contains multiple key names separated by spaces, it represents a multi-stroke binding, which will fire when the user presses the given keys after each other order.

You can use Mod- as a shorthand for Cmd- on Mac and Ctrl- on other platforms. So Mod-b is Ctrl-b on Linux but Cmd-b on macOS.

key⁠?: string

The key name to use for this binding. If the platform-specific property (mac, win, or linux) for the current platform is used as well in the binding, that one takes precedence. If key isn't defined and the platform-specific binding isn't either, a binding is ignored.

mac⁠?: string

Key to use specifically on macOS.

win⁠?: string

Key to use specifically on Windows.

linux⁠?: string

Key to use specifically on Linux.

run: Command

The command to execute when this binding is triggered. When the command function returns false, further bindings will be tried for the key.

shift⁠?: Command

When given, this defines a second binding, using the (possibly platform-specific) key name prefixed with Shift- to activate this command. This is mostly useful for cursor-motion commands that also have a cursor-extending variant.

scope⁠?: string

By default, key bindings apply when focus is on the editor content (the "editor" scope). Some extensions, mostly those that define their own panels, might want to allow you to register bindings local to that panel. Such bindings should use a custom scope name. You may also set multiple scope names, separated by spaces.

preventDefault⁠?: boolean

When set to true (the default is false), this will always prevent the further handling for the bound key, even if the command(s) return false. This can be useful for cases where the native behavior of the key is annoying or irrelevant but the command doesn't always apply (such as, Mod-u for undo selection, which would cause the browser to view source instead when no selection can be undone).

keymap(bindings: readonly KeyBinding[], platform⁠?: "mac" | "win" | "linux") → Extension[]

Create a view extension that registers a keymap.

You can add multiple keymap extensions to an editor. Their priorities determine their precedence (the ones specified early or with high priority get checked first). When a handler has returned true for a given key, no further handlers are called.

When a key is bound multiple times (either in a single keymap or in separate maps), the bound commands all get a chance to handle the key stroke, in order of precedence, until one of them returns true.

runScopeHandlers(viewEditorView, eventKeyboardEvent, scopestring) → boolean

Run the key handlers registered for a given scope. Returns true if any of them handled the event.


Your code should never, never directly change the DOM structure CodeMirror creates for its content. Instead, the way to influence how things are drawn is by providing decorations, which can add styling or replace content with an alternative representation.

abstract class Decoration extends RangeValue

A decoration provides information on how to draw or style a piece of content. You'll usually use it wrapped in a Range, which adds a start and end position.

readonly spec: any

The config object used to create this decoration.

static mark(specObject) → Decoration

Create a mark decoration, which influences the styling of the text in its range.

inclusive⁠?: boolean

Whether the mark covers its start and end position or not. This influences whether content inserted at those positions becomes part of the mark. Defaults to false.

inclusiveStart⁠?: boolean

Specify whether the start position of the marked range should be inclusive. Overrides inclusive, when both are present.

inclusiveEnd⁠?: boolean

Whether the end should be inclusive.

attributes⁠?: Object<string>

Add attributes to the DOM elements that hold the text in the marked range.

class⁠?: string

Shorthand for {attributes: {class: value}}.

tagName⁠?: string

Add a wrapping element around the text in the marked range. Note that there will not be a single element covering the entire range—content is split on mark starts and ends, and each piece gets its own element.

static widget(specObject) → Decoration

Create a widget decoration, which adds an element at the given position.

widget: WidgetType

The type of widget to draw here.

side⁠?: number

Which side of the given position the widget is on. When this is positive, the widget will be drawn after the cursor if the cursor is on the same position. Otherwise, it'll be drawn before it. When multiple widgets sit at the same position, their side values will determine their ordering—those with a lower value come first. Defaults to 0.

block⁠?: boolean

Determines whether this is a block widgets, which will be drawn between lines, or an inline widget (the default) which is drawn between the surrounding text.

static replace(specObject) → Decoration

Create a replace decoration which replaces the given range with a widget, or simply hides it.

widget⁠?: WidgetType

An optional widget to drawn in the place of the replaced content.

inclusive⁠?: boolean

Whether this range covers the positions on its sides. This influences whether new content becomes part of the range and whether the cursor can be drawn on its sides. Defaults to false.

inclusiveStart⁠?: boolean

Set inclusivity at the start.

inclusiveEnd⁠?: boolean

Set inclusivity at the end.

block⁠?: boolean

Whether this is a block-level decoration. Defaults to false.

static line(specObject) → Decoration

Create a line decoration, which can add DOM attributes to the line starting at the given position.

attributes⁠?: Object<string>

DOM attributes to add to the element wrapping the line.

static set(ofRange<Decoration> | readonly Range<Decoration>[], sort⁠?: boolean = false) → DecorationSet

Build a DecorationSet from the given decorated range or ranges.

static none: DecorationSet

The empty set of decorations.

type DecorationSet = RangeSet<Decoration>

A decoration set represents a collection of decorated ranges, organized for efficient access and mapping. See RangeSet for its methods.

abstract class WidgetType<T = any>

Widgets added to the content are described by subclasses of this class. This makes it possible to delay creating of the DOM structure for a widget until it is needed, and to avoid redrawing widgets even when the decorations that define them are recreated. T can be a type of value passed to instances of the widget type.

new WidgetType(valueT)

Create an instance of this widget type.

abstract toDOM(viewEditorView) → HTMLElement

Build the DOM structure for this widget instance.

eq(valueT) → boolean

Compare this instance to another instance of the same class. By default, it'll compare the instances' parameters with ===.

updateDOM(_domHTMLElement) → boolean

Update a DOM element created by a widget of the same type but with a different value to reflect this widget. May return true to indicate that it could update, false to indicate it couldn't (in which case the widget will be redrawn). The default implementation just returns false.

readonly estimatedHeight: number

The estimated height this widget will have, to be used when estimating the height of content that hasn't been drawn. May return -1 to indicate you don't know. The default implementation returns -1.

ignoreEvent(_eventEvent) → boolean

Can be used to configure which kinds of events inside the widget should be ignored by the editor. The default is to ignore all events.

re-export Range

commands module

This package exports a collection of generic editing commands, along with key bindings for a lot of them.


standardKeymap: readonly KeyBinding[]

An array of key bindings closely sticking to platform-standard or widely used bindings. (This includes the bindings from emacsStyleKeymap, with their key property changed to mac.)

defaultKeymap: readonly KeyBinding[]

The default keymap. Includes all bindings from standardKeymap plus the following:

emacsStyleKeymap: readonly KeyBinding[]

Array of key bindings containing the Emacs-style bindings that are available on macOS by default.


simplifySelection: StateCommand

Simplify the current selection. When multiple ranges are selected, reduce it to its primary range. Otherwise, if the selection is non-empty, convert it to a cursor selection.

By character

cursorCharLeft: Command

Move the selection one character to the left (which is backward in left-to-right text, forward in right-to-left text).

selectCharLeft: Command

Move the selection head one character to the left, while leaving the anchor in place.

cursorCharRight: Command

Move the selection one character to the right.

selectCharRight: Command

Move the selection head one character to the right.

cursorCharForward: Command

Move the selection one character forward.

selectCharForward: Command

Move the selection head one character forward.

cursorCharBackward: Command

Move the selection one character backward.

selectCharBackward: Command

Move the selection head one character backward.

By group

cursorGroupLeft: Command

Move the selection across one group of word or non-word (but also non-space) characters.

selectGroupLeft: Command

Move the selection head one group to the left.

cursorGroupRight: Command

Move the selection one group to the right.

selectGroupRight: Command

Move the selection head one group to the right.

cursorGroupForward: Command

Move the selection one group forward.

selectGroupForward: Command

Move the selection head one group forward.

cursorGroupBackward: Command

Move the selection one group backward.

selectGroupBackward: Command

Move the selection head one group backward.

Vertical motion

cursorLineUp: Command

Move the selection one line up.

selectLineUp: Command

Move the selection head one line up.

cursorLineDown: Command

Move the selection one line down.

selectLineDown: Command

Move the selection head one line down.

cursorPageUp: Command

Move the selection one page up.

selectPageUp: Command

Move the selection head one page up.

cursorPageDown: Command

Move the selection one page down.

selectPageDown: Command

Move the selection head one page down.

By line boundary

cursorLineBoundaryForward: Command

Move the selection to the next line wrap point, or to the end of the line if there isn't one left on this line.

selectLineBoundaryForward: Command

Move the selection head to the next line boundary.

cursorLineBoundaryBackward: Command

Move the selection to previous line wrap point, or failing that to the start of the line.

selectLineBoundaryBackward: Command

Move the selection head to the previous line boundary.

cursorLineStart: Command

Move the selection to the start of the line.

selectLineStart: Command

Move the selection head to the start of the line.

cursorLineEnd: Command

Move the selection to the end of the line.

selectLineEnd: Command

Move the selection head to the end of the line.

selectLine: StateCommand

Expand the selection to cover entire lines.

By document boundary

cursorDocStart: StateCommand

Move the selection to the start of the document.

selectDocStart: StateCommand

Move the selection head to the start of the document.

cursorDocEnd: StateCommand

Move the selection to the end of the document.

selectDocEnd: StateCommand

Move the selection head to the end of the document.

selectAll: StateCommand

Select the entire document.

By syntax

cursorSyntaxLeft: Command

Move the cursor over the next syntactic element to the left.

selectSyntaxLeft: Command

Move the selection head over the next syntactic element to the left.

cursorSyntaxRight: Command

Move the cursor over the next syntactic element to the right.

selectSyntaxRight: Command

Move the selection head over the next syntactic element to the right.

selectParentSyntax: StateCommand

Select the next syntactic construct that is larger than the selection. Note that this will only work insofar as the language syntaxes you use builds up a full syntax tree.

cursorMatchingBracket: StateCommand

Move the selection to the bracket matching the one it is currently on, if any.

selectMatchingBracket: StateCommand

Extend the selection to the bracket matching the one the selection head is currently on, if any.


deleteCharBackward: Command

Delete the selection, or, for cursor selections, the character before the cursor.

deleteCharForward: Command

Delete the selection or the character after the cursor.

deleteGroupBackward: Command

Delete the selection or backward until the end of the next group.

deleteGroupForward: Command

Delete the selection or forward until the end of the next group.

deleteToLineEnd: Command

Delete the selection, or, if it is a cursor selection, delete to the end of the line. If the cursor is directly at the end of the line, delete the line break after it.

deleteTrailingWhitespace: StateCommand

Delete all whitespace directly before a line end from the document.

Line manipulation

splitLine: StateCommand

Replace each selection range with a line break, leaving the cursor on the line before the break.

moveLineUp: StateCommand

Move the selected lines up one line.

moveLineDown: StateCommand

Move the selected lines down one line.

copyLineUp: StateCommand

Create a copy of the selected lines. Keep the selection in the top copy.

copyLineDown: StateCommand

Create a copy of the selected lines. Keep the selection in the bottom copy.

deleteLine: Command

Delete selected lines.


indentSelection: StateCommand

Auto-indent the selected lines. This uses the indentation facet as source for auto-indent information.

indentMore: StateCommand

Add a unit of indentation to all selected lines.

indentLess: StateCommand

Remove a unit of indentation from all selected lines.

Character manipulation

transposeChars: StateCommand

Flip the characters before and after the cursor(s).

insertNewline: StateCommand

Replace the selection with a newline.

insertNewlineAndIndent: StateCommand

Replace the selection with a newline and indent the newly created line(s). If the current line consists only of whitespace, this will also delete that whitespace.

history module

history(config⁠?: Object = {}) → Extension

Create a history extension with the given configuration.

minDepth⁠?: number

The minimum depth (amount of events) to store. Defaults to 100.

newGroupDelay⁠?: number

The maximum time (in milliseconds) that adjacent events can be apart and still be grouped together. Defaults to 500.

historyKeymap: readonly KeyBinding[]

Default key bindings for the undo history.

undo: StateCommand

Undo a single group of history events. Returns false if no group was available.

redo: StateCommand

Redo a group of history events. Returns false if no group was available.

undoSelection: StateCommand

Undo a selection change.

redoSelection: StateCommand

Redo a selection change.

undoDepth(stateEditorState) → number

The amount of undoable change events available in a given state.

redoDepth(stateEditorState) → number

The amount of redoable change events available in a given state.

isolateHistory: AnnotationType<"before" | "after" | "full">

Transaction annotation that will prevent that annotation from being combined with other annotations in the undo history. Given "before", it'll prevent merging with previous transactions. With "after", subsequent transactions won't be combined with this one. With "full", the transaction is isolated on both sides.

invertedEffects: Facet<fn(trTransaction) → readonly StateEffect<any>[]>

This facet provides a way to register functions that, given a transaction, provide a set of effects that the history should store when inverting the transaction. This can be used to integrate some kinds of effects in the history, so that they can be undone (and redone again).

collab module

interface Update

An update is a set of changes and effects.

changes: ChangeSet

The changes made by this update.

effects⁠?: readonly StateEffect<any>[]

The effects in this update. There'll only ever be effects here when you configured your collab extension with a sharedEffects option.

collab(config⁠?: Object = {}) → Extension

Create an instance of the collaborative editing plugin.

startVersion⁠?: number

The starting document version. Will default to 0.

clientID⁠?: string

This client's identifying ID. Will be a randomly generated string if not provided.

sharedEffects⁠?: fn(trTransaction) → readonly StateEffect<any>[]

It is possible to share information other than document changes through this extension. If you provide this option, your function will be called on each transaction, and the effects it returns will be sent to the server, much like changes are. Such effects are automatically remapped when conflicting remote changes come in.

receiveUpdates(stateEditorState, updates: readonly Update[], ownUpdateCountnumber) → Transaction

Create a transaction that represents a set of new updates received from the authority. Applying this transaction moves the state forward to adjust to the authority's view of the document.

sendableUpdates(stateEditorState) → readonly (Update & {origin: Transaction})[]

Returns the set of locally made updates that still have to be sent to the authority. The returned objects will also have an origin property that points at the transaction that created them. This may be useful if you want to send along metadata like timestamps. (But note that the updates may have been mapped in the meantime, whereas the transaction is just the original transaction that created them.)

getSyncedVersion(stateEditorState) → number

Get the version up to which the collab plugin has synced with the central authority.

getClientID(stateEditorState) → string

Get this editor's collaborative editing client ID.

gutter module

lineNumbers(config⁠?: Object = {}) → Extension

Create a line number gutter extension. The order in which the gutters appear is determined by their extension priority.

formatNumber⁠?: fn(lineNonumber) → string

How to display line numbers. Defaults to simply converting them to string.

domEventHandlers⁠?: Object<fn(viewEditorView, lineBlockInfo, eventany) → boolean>

Supply event handlers for DOM events on this gutter.

gutter(configObject) → Extension

Define an editor gutter.

style⁠?: string

The theme selector for the gutter's wrapping DOM element. Will be prefixed with "gutter." for the gutter wrapper, and then suffixed with "Element" for the individual line elements.

renderEmptyElements⁠?: boolean

Controls whether empty gutter elements should be rendered. Defaults to false.

markers⁠?: fn(stateEditorState) → RangeSet<GutterMarker> | readonly RangeSet<GutterMarker>[]

Retrieve a set of markers to use in this gutter from the current editor state.

lineMarker⁠?: fn(viewEditorView, lineBlockInfo, markers: readonly GutterMarker[]) → null | GutterMarker

Can be used to optionally add a single marker to every line.

initialSpacer⁠?: fn(viewEditorView) → GutterMarker

Use a spacer element that gives the gutter its base width.

updateSpacer⁠?: fn(spacerGutterMarker, updateViewUpdate) → GutterMarker

Update the spacer element when the view is updated.

domEventHandlers⁠?: Object<fn(viewEditorView, lineBlockInfo, eventany) → boolean>

Supply event handlers for DOM events on this gutter.

gutters(config⁠?: {fixed⁠?: boolean}) → Extension

The gutter-drawing plugin is automatically enabled when you add a gutter, but you can use this function to explicitly configure it.

Unless fixed is explicitly set to false, the gutters are fixed, meaning they don't scroll along with the content horizontally.

abstract class GutterMarker extends RangeValue

A gutter marker represents a bit of information attached to a line in a specific gutter. Your own custom markers have to extend this class.

abstract eq(otherGutterMarker) → boolean

Compare this marker to another marker of the same type.

toDOM(_viewEditorView) → null | Node

Render the DOM node for this marker, if any.

at(posnumber) → Range<GutterMarker>

Create a range that places this marker at the given position.

elementClass: string

This property can be used to add CSS classes to the gutter element that contains this marker.

lineNumberMarkers: Facet<RangeSet<GutterMarker>>

Facet used to provide markers to the line number gutter.

rangeset module

Range sets provide a data structure that can hold a collection of tagged, possibly overlapping ranges in such a way that they can efficiently be mapped though document changes.

abstract class RangeValue

Each range is associated with a value, which must inherit from this class.

eq(otherRangeValue) → boolean

Compare this value with another value. The default implementation compares by identity.

startSide: number

The bias value at the start of the range. Determines how the range is positioned relative to other ranges starting at this position. Defaults to 0.

endSide: number

The bias value at the end of the range. Defaults to 0.

mapMode: MapMode

The mode with which the location of the range should be mapped when it's from and to are the same, to decide whether a change deletes the range. Defaults to MapMode.TrackDel.

point: boolean

Whether this value marks a point range, which shadows the ranges contained in it.

range(fromnumber, to⁠?: number = from) → Range<RangeValue>

Create a range with this value.

class Range<T extends RangeValue>

A range associates a value with a range of positions.

readonly from: number

The range's start position.

readonly to: number

Its end position.

readonly value: T

The value associated with this range.

class RangeSet<T extends RangeValue>

A range set stores a collection of ranges in a way that makes them efficient to map and update. This is an immutable data structure.

update(updateSpec: {filterFrom⁠?: number}) → RangeSet<T>

Update the range set, optionally adding new ranges or filtering out existing ones.

add⁠?: readonly Range<T>[]

An array of ranges to add. If given, this should be sorted by from position and startSide unless sort is given as true.

sort⁠?: boolean

Indicates whether the library should sort the ranges in add.

filter⁠?: fn(fromnumber, tonumber, valueT) → boolean

Filter the ranges already in the set. Only those for which this function returns true are kept.

filterTo⁠?: number

These can be used to limit the range on which the filter is applied. Filtering only a small range, as opposed to the entire set, can make updates cheaper.

map(changesChangeDesc) → RangeSet<T>

Map this range set through a set of changes, return the new set.

between(fromnumber, tonumber, ffn(fromnumber, tonumber, valueT) → false | undefined)

Iterate over the ranges that touch the region from to to, calling f for each. There is no guarantee that the ranges will be reported in any order. When the callback returns false, iteration stops.

iter(from⁠?: number = 0) → RangeCursor<T>

Iterate over the ranges in this set, in order, including all ranges that end at or after from.

static iter<T extends RangeValue>(sets: readonly RangeSet<T>[], from⁠?: number = 0) → RangeCursor<T>

Iterate over the given sets, starting from from.

static compare<T extends RangeValue>(oldSets: readonly RangeSet<T>[], newSets: readonly RangeSet<T>[], textDiffChangeDesc, comparatorRangeComparator<T>)

Iterate over two groups of sets, calling methods on comparator to notify it of possible differences. textDiff indicates how the underlying data changed between these ranges, and is needed to synchronize the iteration. from and to are coordinates in the new space, after these changes.

static spans<T extends RangeValue>(sets: readonly RangeSet<T>[], fromnumber, tonumber, iteratorSpanIterator<T>)

Iterate over a group of range sets at the same time, notifying the iterator about the ranges covering every given piece of content.

static of<T extends RangeValue>(ranges: readonly Range<T>[] | Range<T>, sort⁠?: boolean = false) → RangeSet<T>

Create a range set for the given range or array of ranges. By default, this expects the ranges to be sorted (by start position and, if two start at the same position, value.startSide). You can pass true as second argument to cause the method to sort them.

static empty: RangeSet<any>

The empty set of ranges.

type RangeCursor<T>

A range cursor is an object that moves to the next range every time you call next on it. Note that, unlike ES6 iterators, these start out pointing at the first element, so you should call next only after reading the first range (if any).


Move the iterator forward.

value: T | null

The next range's value. Holds null when the cursor has reached its end.

from: number

The next range's start position.

to: number

The next end position.

class RangeSetBuilder<T extends RangeValue>

A range set builder is a data structure that helps build up a range set directly, without first allocating an array of Range objects.

new RangeSetBuilder()

Create an empty builder.

add(fromnumber, tonumber, valueT)

Add a range. Ranges should be added in sorted (by from and value.startSide) order.

finish() → RangeSet<T>

Finish the range set. Returns the new set. The builder can't be used anymore after this has been called.

interface RangeComparator<T extends RangeValue>

Collection of methods used when comparing range sets.

compareRange(fromnumber, tonumber, activeAT[], activeBT[])

Notifies the comparator that the given range has the given set of values associated with it.

comparePoint(fromnumber, tonumber, byAT | null, byBT | null)

Notification for a point range.

minPointSize⁠?: number

Can be used to ignore all non-point ranges and points below a given size. Specify 0 to get all points.

interface SpanIterator<T extends RangeValue>

Methods used when iterating over the spans created by a set of ranges. The entire iterated range will be covered with either span or point calls.

span(fromnumber, tonumber, active: readonly T[])

Called for any ranges not covered by point decorations. active holds the values that the range is marked with (and may be empty).

point(fromnumber, tonumber, valueT, openStartboolean, openEndboolean)

Called when going over a point decoration. openStart and openEnd indicate whether the point decoration exceeded the range we're iterating over at its start and end.

minPointSize⁠?: number

When given and greater than -1, only points of at least this size are taken into account.

syntax module

class LezerSyntax implements Syntax

A syntax provider based on a Lezer parser.

new LezerSyntax(parserParser, config⁠?: {languageData⁠?: Object<any>} = {})

Create a syntax instance for the given parser. You'll usually want to use the withProps method to register CodeMirror-specific syntax node props in the parser, before passing it to this constructor.

When language data is given, it will be included in the syntax object's extension.

readonly parser: Parser

The Lezer parser used by this syntax.

readonly extension: Extension

The extension value to install this provider.

foldNodeProp: NodeProp<fn(subtreeSubtree, stateEditorState) → null | {from: number, to: number}>

This node prop is used to associate folding information with node types. Given a subtree, it should check whether that tree is foldable and return the range that can be collapsed when it is.


indentNodeProp: NodeProp<fn(contextTreeIndentContext) → number>

A syntax tree node prop used to associate indentation strategies with node types. Such a strategy is a function from an indentation context to a number. That number may be -1, to indicate that no definitive indentation can be determined, or a column number to which the given line should be indented.

class TreeIndentContext extends IndentContext

Objects of this type provide context information and helper methods to indentation functions.

readonly pos: number

The position at which indentation is being computed.

readonly node: Subtree

The syntax tree node for which the indentation strategy is registered.

readonly textAfter: string

Get the text directly after this.pos, either the entire line or the next 100 characters, whichever is shorter.

readonly baseIndent: number

Get the indentation at the reference line for this.node, which is the line on which it starts, unless there is a node that is not a parent of this node covering the start of that line. If so, the line at the start of that node is tried, again skipping on if it is covered by another such node.

delimitedIndent({closing: string, align⁠?: boolean, units⁠?: number}) → fn(contextTreeIndentContext) → number

An indentation strategy for delimited (usually bracketed) nodes. Will, by default, indent one unit more than the parent's base indent unless the line starts with a closing token. When align is true and there are non-skipped nodes on the node's opening line, the content of the node will be aligned with the end of the opening node, like this:

continuedIndent({except⁠?: RegExp, units⁠?: number} = {}) → fn(contextTreeIndentContext) → number

Creates an indentation strategy that, by default, indents continued lines one unit more than the node's base indentation. You can provide except to prevent indentation of lines that match a pattern (for example /^else\b/ in if/else constructs), and you can change the amount of units used with the units option.

flatIndent(contextTreeIndentContext) → number

An indentation strategy that aligns a node content to its base indentation.

fold module

foldCode: Command

Fold the lines that are selected, if possible.

unfoldCode: Command

Unfold folded ranges on selected lines.

foldAll: Command

Fold all top-level foldable ranges.

unfoldAll: Command

Unfold all folded code.

foldKeymap: readonly KeyBinding[]

Default fold-related key bindings.

codeFolding(config⁠?: Object) → Extension

Create an extension that configures code folding.

placeholderDOM⁠?: fn() → HTMLElement

A function that creates the DOM element used to indicate the position of folded code. When not given, the placeholderText option will be used instead.

placeholderText⁠?: string

Text to use as placeholder for folded text. Defaults to "…". Will be styled with the foldPlaceholder theme selector.

foldGutter(config⁠?: Object = {}) → Extension

Create an extension that registers a fold gutter, which shows a fold status indicator before lines which can be clicked to fold or unfold the line.

openText⁠?: string

Text used to indicate that a given line can be folded. Defaults to "⌄".

closedText⁠?: string

Text used to indicate that a given line is folded. Defaults to "›".

matchbrackets module

bracketMatching(config⁠?: Object = {}) → Extension

Create an extension that enables bracket matching. Whenever the cursor is next to a bracket, that bracket and the one it matches are highlighted. Or, when no matching bracket is found, another highlighting style is used to indicate this.

afterCursor⁠?: boolean

Whether the bracket matching should look at the character after the cursor when matching (if the one before isn't a bracket). Defaults to true.

brackets⁠?: string

The bracket characters to match, as a string of pairs. Defaults to "()[]{}". Note that these are only used as fallback when there is no matching information in the syntax tree.

maxScanDistance⁠?: number

The maximum distance to scan for matching brackets. This is only relevant for brackets not encoded in the syntax tree. Defaults to 10 000.

matchBrackets(stateEditorState, posnumber, dir-1 | 1, config⁠?: Object = {}) → null | MatchResult

Find the matching bracket for the token at pos, scanning direction dir. Only the brackets and maxScanDistance properties are used from config, if given. Returns null if no bracket was found at pos, or a match result otherwise.

afterCursor⁠?: boolean

Whether the bracket matching should look at the character after the cursor when matching (if the one before isn't a bracket). Defaults to true.

brackets⁠?: string

The bracket characters to match, as a string of pairs. Defaults to "()[]{}". Note that these are only used as fallback when there is no matching information in the syntax tree.

maxScanDistance⁠?: number

The maximum distance to scan for matching brackets. This is only relevant for brackets not encoded in the syntax tree. Defaults to 10 000.

interface MatchResult

The result returned from matchBrackets.

start: {from: number, to: number}

The extent of the bracket token found.

end⁠?: {from: number, to: number}

The extent of the matched token, if any was found.

matched: boolean

Whether the tokens match. This can be false even when end has a value, if that token doesn't match the opening token.

closebrackets module

interface CloseBracketConfig

Configures bracket closing behavior for a syntax (via languageData) using the "closeBrackets" identifier.

brackets⁠?: string[]

The opening brackets to close. Defaults to ["(", "[", "{", "'", '"']. Brackets may be single characters or a triple of quotes (as in "''''").

before⁠?: string

Characters in front of which newly opened brackets are automatically closed. Closing always happens in front of whitespace. Defaults to ")]}'\":;>".

closeBrackets() → Extension

Extension to enable bracket-closing behavior. When a closeable bracket is typed, its closing bracket is immediately inserted after the cursor. When closing a bracket directly in front of that closing bracket, the cursor moves over the existing bracket. When backspacing in between brackets, both are removed.

handleBackspace(stateEditorState) → null | Transaction

Function that implements the extension's backspace behavior. Exported mostly for testing purposes.

handleInsertion(stateEditorState, chstring) → null | Transaction

Implements the extension's behavior on text insertion. Again, exported mostly for testing.

panel module

Panels are UI elements positioned above or below the editor (things like a search dialog). They will take space from the editor when it has a fixed height, and will stay in view even when the editor is partially scrolled out of view.

panels(config⁠?: Object) → Extension

Enables the panel-managing extension.

topContainer⁠?: HTMLElement

By default, panels will be placed inside the editor's DOM structure. You can use this option to override where panels with top: true are placed.

bottomContainer⁠?: HTMLElement

Override where panels with top: false are placed.

interface Panel

Object that describes an active panel.

dom: HTMLElement

The element representing this panel.

mount⁠?: fn()

Optionally called after the panel has been added to the editor.

update⁠?: fn(updateViewUpdate)

Update the DOM for a given view update.

style⁠?: string

An optional theme selector. By default, panels are themed as "panel". If you pass "foo" here, your panel is themed as "".

top⁠?: boolean

Whether the panel should be at the top or bottom of the editor. Defaults to false.

pos⁠?: number

An optional number that is used to determine the ordering when there are multiple panels. Those with a lower pos value will come first. Defaults to 0.

showPanel: Facet<fn(viewEditorView) → Panel>

Opening a panel is done by providing an object describing the panel through this facet.

getPanel(viewEditorView, panelfn(viewEditorView) → Panel) → null | Panel

Get the active panel created by the given constructor, if any. This can be useful when you need access to your panels' DOM structure.

tooltip module

Tooltips are DOM elements overlaid on the editor near a given document position. This package helps manage and position such elements.

tooltips() → Extension

Supporting extension for displaying tooltips. Allows showTooltip to be used to define tooltips.

interface Tooltip

Describes a tooltip. Values of this type, when provided through the showTooltip facet, control the individual tooltips on the editor.

pos: number

The document position at which to show the tooltip.

end⁠?: number

The end of the range annotated by this tooltip, if different from pos.

create(viewEditorView) → TooltipView

A constructor function that creates the tooltip's DOM representation.

style⁠?: string

An extra theme selector to use for the tooltip. By default, it'll be themed as "tooltip", but you can pass a name, say "mine", to style it as "tooltip.mine" instead.

above⁠?: boolean

Whether the tooltip should be shown above or below the target position. Defaults to false.

strictSide⁠?: boolean

Whether the above option should be honored when there isn't enough space on that side to show the tooltip inside the viewport. Defaults to false.

interface TooltipView

Describes the way a tooltip is displayed.

dom: HTMLElement

The DOM element to position over the editor.

mount⁠?: fn(viewEditorView)

Called after the tooltip is added to the DOM for the first time.

update⁠?: fn(updateViewUpdate)

Update the DOM element for a change in the view's state.

showTooltip: Facet<Tooltip>

Behavior by which an extension can provide a tooltip to be shown.

hoverTooltip(sourcefn(viewEditorView, checkfn(fromnumber, tonumber) → boolean) → null | Tooltip, options⁠?: {hideOnChange⁠?: boolean} = {}) → Extension

Enable a hover tooltip, which shows up when the pointer hovers over ranges of text. The callback should, for each hoverable range, call its check argument to see if that range is being hovered over, and return a tooltip description when it is.

goto-line module

gotoLine: Command

Command that shows a dialog asking the user for a line number, and when a valid number is provided, moves the cursor to that line.

The dialog can be styled with the panel.gotoLine theme selector.

gotoLineKeymap: readonly KeyBinding[]

Keymap that binds Alt-g to gotoLine.

lint module

lintKeymap: readonly KeyBinding[]

A set of default key bindings for the lint functionality.

interface Diagnostic

Describes a problem or hint for a piece of code.

from: number

The start position of the relevant text.

to: number

The end position. May be equal to from, though actually covering text is preferable.

severity: "info" | "warning" | "error"

The severity of the problem. This will influence how it is displayed.

source⁠?: string

An optional source string indicating where the diagnostic is coming from. You can put the name of your linter here, if applicable.

message: string

The message associated with this diagnostic.

actions⁠?: readonly Action[]

An optional array of actions that can be taken on this diagnostic.

interface Action

An action associated with a diagnostic.

name: string

The label to show to the user. Should be relatively short.

apply(viewEditorView, fromnumber, tonumber)

The function to call when the user activates this action. Is given the diagnostic's current position, which may have changed since the creation of the diagnostic due to editing.

linter(sourcefn(viewEditorView) → readonly Diagnostic[] | Promise<readonly Diagnostic[]>) → Extension

Given a diagnostic source, this function returns an extension that enables linting with that source. It will be called whenever the editor is idle (after its content changed).

openLintPanel: Command

Command to open and focus the lint panel.

closeLintPanel: Command

Command to close the lint panel, when open.

nextDiagnostic: Command

Move the selection to the next diagnostic.

setDiagnostics(stateEditorState, diagnostics: readonly Diagnostic[]) → TransactionSpec

State effect that is used to update the current set of diagnostics.

highlight module

Syntax highlighting is done by a highlighter, which maps style tags associated with a syntax tree to CSS styles, making sure each syntactic element is styled appropriately.

Because syntax tree node types and highlighters have to be able to talk the same language, CodeMirror uses a closed vocabulary of syntax types. It is possible to define your own vocabulary, but the vocabulary used by the syntax and the highlighter have to agree, or no highlighting happens.

Each node can be assigned a tag. Tags have a type and one or more flags, which can be used to further refine them. Types may extend other types. When no style for a given tag is present in the highlighter, it will fall back first to styles for that type without one or more flags, and then, if that also fails, to its parent types. Elements for which no style matches at all are not styled.

These are the types in the default tagging system. Sublists indicate types that extend other types.

This collection is heavily biasted towards programming language, and necessarily incomplete. A full ontology of syntactic constructs would fill a stack of books, and be impractical to write themes for. So try to make do with this set, possibly encoding more information with flags. If all else fails, open an issue to propose a new type, or create a custom tag system for your use case.

Each type can be suffixed with a hash sign and a number from 1 to 7 to specify a subtype. This can be useful to distinguish elements not otherwise encodable. For example, if a language has multiple types of string literals, you can use string#2 or similar to allow highlighters to style them differently if they want to.

These flags can be added to every type:

Tags are specified with strings that contain zero or more type or flag names separated by spaces. A tag may contain at most one type name, and any number of flags. So "number meta invalid" indicates a tag that's of type number and has the meta and invalid flags set.

A tag string may start with the character + to indicate that it is additive. By default, the innermost syntax node active at a given point determines how a piece of text is styled. Additive tags add their style to all text, even that inside child nodes.

styleTags(tagsObject<string>) → NodePropSource

Used to add a set of tags to a language syntax via Parser.withProps. The argument object can use syntax node selectors (see NodeType.match) as property names, and tag names (in the default tag system) as values.

highlighter(specObject<Style>) → Extension

Create a highlighter theme that adds the given styles to the given tags. The spec's property names must be tag names or comma-separated lists of tag names. The values should be style-mod style objects that define the CSS for that tag.

defaultHighlighter: Extension

A default highlighter (works well with light themes).

class TagSystem

A tag system defines a set of node (token) tags used for highlighting. You'll usually want to use the default set, but it is possible to define your own custom system when that doesn't fit your use case.

new TagSystem(options: {flags: string[], types: string[], subtypes⁠?: number})

Define a tag system. Each tag identifies a type of syntactic element, which can have a single type and any number of flags. The flags argument should be an array of flag names, and the types argument an array of type names. Type names may have a "name=parentName" format to specify that this type is an instance of some other type, which means that, if no styling for the type itself is provided, it'll fall back to the parent type's styling.

You can specify a subtypes property to assign a given number of sub-types to each type. These are automatically generated types with the base type name suffixed with #1 to #N (where N is the number given in the subtypes field) that have the base type as parent type.

flags: readonly string[]

The flags argument given when creating this system.

types: readonly string[]

The types argument given when creating this system.

prop: NodeProp<number>

A node prop used to associate styling tag information with syntax tree nodes.

get(namestring) → number

Parse a tag name into a numeric ID. Only necessary if you are manually defining node properties for this system.

add(tagsObject<string>) → NodePropSource

Create a PropSource that adds node properties for this system. tags should map node type selectors to tag names.

highlighter(specObject<Style>) → Extension

Create a highlighter extension for this system, styling the given tags using the given CSS objects.

defaultTags: TagSystem

The set of highlighting tags used by regular language packages and themes.

stream-syntax module

type StreamParser<State>

A stream parser parses or tokenizes content from start to end, emitting tokens as it goes over it. It keeps a mutable (but copyable) object with state, in which it can store information about the current context.

token(streamStringStream, stateState, editorStateEditorState) → null | string

Read one token, advancing the stream past it, and returning a string with the token's style. It is okay to return an empty token, but only if that updates the state so that the next call will return a token again.

blankLine⁠?: fn(stateState, editorStateEditorState)

This notifies the parser of a blank line in the input. It can update its state here if it needs to.

startState⁠?: fn(editorStateEditorState) → State

Produce a start state for the parser.

copyState⁠?: fn(stateState) → State

Copy a given state. By default, a shallow object copy is done which also copies arrays held at the top level of the object.

indent⁠?: fn(stateState, textAfterstring, editorStateEditorState) → number

Compute automatic indentation for the line that starts with the given state and text.

docProps⁠?: readonly [NodeProp<any>, any][]

Syntax node props to be added to the wrapper node created around syntax 'trees' created by this syntax.

class StringStream

Encapsulates a single line of input. Given to stream syntax code, which uses it to tokenize the content.

pos: number

The current position on the line.

start: number

The start position of the current token.

string: string

The line.

tabSize: number

Current tab size.

eol() → boolean

True if we are at the end of the line.

sol() → boolean

True if we are at the start of the line.

peek() → undefined | string

Get the next code unit after the current position, or undefined if we're at the end of the line.

next() → string | undefined

Read the next code unit and advance this.pos.

eat(matchstring | RegExp | fn(chstring) → boolean) → string | undefined

Match the next character against the given string, regular expression, or predicate. Consume and return it if it matches.

eatWhile(matchstring | RegExp | fn(chstring) → boolean) → boolean

Continue matching characters that match the given string, regular expression, or predicate function. Return true if any characters were consumed.

eatSpace() → boolean

Consume whitespace ahead of this.pos. Return true if any was found.


Move to the end of the line.

skipTo(chstring) → false | true | undefined

Move to directly before the given character, if found on the current line.


Move back n characters.

column() → number

Get the column position at this.pos.

indentation() → number

Get the indentation column of the current line.

match(patternstring | RegExp, consume⁠?: boolean, caseInsensitive⁠?: boolean) → null | false | true | RegExpMatchArray

Match the input against the given string or regular expression (which should start with a ^). Return true or the regexp match if it matches.

Unless consume is set to false, this will move this.pos past the matched text.

When matching a string caseInsensitive can be set to true to make the match case-insensitive.

current() → string

Get the current token.

hideFirstChars(nnumber, innerfn())

Hide the first n characters of the stream while running inner. This can be useful for nesting modes.

class StreamSyntax implements Syntax

A syntax provider that uses a stream parser.

new StreamSyntax(parserStreamParser<any>)

Create a stream syntax.

extension: Extension

The extension that installs this syntax provider.

autocomplete module

enum FilterType

Denotes how to filter completions.


Only show completions that start with the currently typed text.


Show completions that have the typed text anywhere in their content.


Show completions that include each character of the typed text, in order (so gBCR could complete to getBoundingClientRect).

class AutocompleteContext

readonly state: EditorState

The editor state that the completion happens in.

readonly pos: number

The position at which the completion happens.

readonly explicit: boolean

Indicates whether completion was activated explicitly, or implicitly by typing. The usual way to respond to this is to only return completions when either there is part of a completable entity at the cursor, or explicit is true.

readonly filterType: FilterType

The configured completion filter. Ignoring this won't break anything, but supporting it is encouraged.

readonly caseSensitive: boolean

Indicates whether completion has been configured to be case-sensitive. Again, this should be taken as a hint, not a requirement.

filter(completionstring, textstring, caseSensitive⁠?: boolean = this.caseSensitive) → boolean

Filter a given completion string against the partial input in text. Will use this.filterType, returns true when the completion should be shown.

tokenBefore() → {from: number, to: number, text: string, type: null | NodeType}

Get the extent, content, and (if there is a token) type of the token before this.pos.

interface CompletionResult

Interface for objects returned by completion sources.

from: number

The start of the range that is being completed.

to: number

The end of the completed range.

options: readonly Completion[]

The completions

filterDownOn⁠?: RegExp

When given, further input that matches the regexp will cause the given options to be re-filtered with the extended string, rather than calling the completion source anew. This can help with responsiveness, since it allows the completion list to be updated synchronously.

interface Completion

Objects type used to represent individual completions.

label: string

The label to show in the completion picker.

apply⁠?: string | fn(viewEditorView, resultCompletionResult, completionCompletion)

How to apply the completion. When this holds a string, the completion range is replaced by that string. When it is a function, that function is called to perform the completion.

type Autocompleter = fn(contextAutocompleteContext) → null | CompletionResult | Promise<null | CompletionResult>

The function signature for a completion source. Such a function may return its result synchronously or as a promise. Returning null indicates no completions are available.

autocomplete(config⁠?: Object = {}) → Extension

Returns an extension that enables autocompletion.

activateOnTyping⁠?: boolean

When enabled (defaults to true), autocompletion will start whenever the user types something that can be completed.

override⁠?: Autocompleter

Override the completion source used.

filterType⁠?: FilterType

Configures how to filter completions.

caseSensitive⁠?: boolean

Configures whether completion is case-sensitive (defaults to false).

startCompletion: Command

Explicitly start autocompletion.

closeCompletion: Command

Close the currently active completion.

autocompleteKeymap: readonly KeyBinding[]

Basic keybindings for autocompletion.

completeFromList(list: readonly (string | Completion)[]) → Autocompleter

Given a a fixed array of options, return an autocompleter that compares those options to the current token and returns the matching ones.

snippet(templatestring) → fn(editor: {state: EditorState, dispatch: fn(trTransaction)}, range: {from: number, to⁠?: number})

Convert a snippet template to a function that can apply it. Snippets are written using syntax like this:

"for (let ${index} = 0; ${index} < ${end}; ${index}++) {\n\t${}\n}"

Each ${} placeholder (you may also use #{}) indicates a field that the user can fill in. Its name, if any, will be the default content for the field.

When the snippet is activated by calling the returned function, the code is inserted at the given position. Newlines in the template are indented by the indentation of the start line, plus one indent unit per tab character after the newline.

On activation, (all instances of) the first field are selected. The user can move between fields with Tab and Shift-Tab as long as the fields are active. Moving to the last field or moving the cursor out of the current field deactivates the fields.

The order of fields defaults to textual order, but you can add numbers to placeholders (${1} or ${1:defaultText}) to provide a custom order.

completeSnippets(snippets: readonly SnippetSpec[]) → Autocompleter

Create a completion source from an array of snippet specs.

type SnippetSpec

Languages can export arrays of snippets using this format. completeSnippets can be used to turn them into a completion source.

keyword: string

The word to match when completing.

name⁠?: string

The user-readable label for the completion. Defaults to keyword when not given.

snippet: string

The snippet template to use.

comment module

type CommentTokens

An object of this type can be provided as language data under a "commentTokens" property to configure comment syntax for a language.

block⁠?: {open: string, close: string}

The block comment syntax, if any. For example, for JavaScript you'd provide {open: "/*", close: "*/"}.

line⁠?: string

The line comment syntax. For example "//".

toggleLineComment: StateCommand

Comments or uncomments the current SelectionRange using line-comments. The line-comment token is defined on a language basis.

lineComment: StateCommand

Comments the current SelectionRange using line-comments. The line-comment token is defined on a language basis.

lineUncomment: StateCommand

Uncomments the current SelectionRange using line-comments. The line-comment token is defined on a language basis.

toggleBlockComment: StateCommand

Comments or uncomments the current SelectionRange using block-comments. The block-comment tokens are defined on a language basis.

blockComment: StateCommand

Comments the current SelectionRange using block-comments. The block-comment tokens are defined on a language basis.

blockUncomment: StateCommand

Uncomments the current SelectionRange using block-comments. The block-comment tokens are defined on a language basis.

commentKeymap: readonly KeyBinding[]

Default key bindings for this package.

rectangular-selection module

rectangularSelection(eventFilter⁠?: fn(eventMouseEvent) → boolean) → Extension

Create an extension that enables rectangular selections. By default, it will rect to left mouse drag with the alt key held down. When such a selection occurs, the text within the rectangle that was dragged over will be selected, as one selection range per line. You can pass a custom predicate function, which takes a mousedown event and returns true if it should be used for rectangular selection.

highlight-selection module

highlightActiveLine() → Extension

Mark lines that have a cursor on them with the `activeLine` theme selector.

highlightSelectionMatches(options⁠?: Object) → Extension

This extension highlights text that matches the selection. It uses the selectionMatch theme selector for the highlighting. When highlightWordAroundCursor is enabled, the word at the cursor itself will be highlighted with selectionMatch.main.

highlightWordAroundCursor⁠?: boolean

Determines whether, when nothing is selected, the word around the cursor is matched instead. Defaults to false.

minSelectionLength⁠?: number

The minimum length of the selection before it is highlighted. Defaults to 1 (always highlight non-cursor selections).

maxMatches⁠?: number

The amount of matches (in the viewport) at which to disable highlighting. Defaults to 100.

basic-setup module

basicSetup: Extension

This is an extension value that just pulls together a whole lot of extensions that you might want in a basic editor. It is meant as a convenient helper to quickly set up CodeMirror without installing and importing a lot of packages.

Specifically, it includes...

(You'll probably want to add some language package to your setup too.)

This package does not allow customization. The idea is that, once you decide you want to configure your editor more precisely, you take this package's source (which is just a bunch of imports and an array literal), copy it into your own code, and adjust it as desired.

re-export EditorView
re-export EditorState

lang-javascript module

javascriptSyntax: LezerSyntax

A syntax provider based on the Lezer JavaScript parser, extended with highlighting and indentation information.

javascriptSupport() → Extension

Returns an extension that installs JavaScript support features (completion of snippets).

javascript() → Extension

Returns an extension that installs the JavaScript syntax and support features.

esLint(eslintany, config⁠?: any) → fn(viewEditorView) → any

Connects an ESLint linter to CodeMirror's lint integration. eslint should be an instance of the Linter class, and config an optional ESLint configuration. The return value of this function can be passed to linter to create a JavaScript linting extension.

Note that ESLint targets node, and is tricky to run in the browser. The eslint4b and eslint4b-prebuilt packages may help with that.

snippets: readonly SnippetSpec[]

A collection of JavaScript-related snippets.

lang-python module

pythonSyntax: LezerSyntax

A syntax provider based on the Lezer Python parser, extended with highlighting and indentation information.

python() → Extension

Returns an extension that installs the Python syntax provider.

lang-css module

cssSyntax: LezerSyntax

A syntax provider based on the Lezer CSS parser, extended with highlighting and indentation information.

css() → Extension

Returns an extension that installs the CSS syntax provider.

lang-html module

htmlSyntax: LezerSyntax

A syntax provider based on the Lezer HTML parser, wired up with the JavaScript and CSS parsers to parse the content of <script> and <style> tags.

htmlCompletion: Extension

HTML tag completion. Opens and closes tags and attributes in a context-aware way.

htmlSupport() → Extension

An extension that installs HTML-related functionality (htmlCompletion and javascriptSupport).

html() → Extension

Returns an extension that installs the HTML syntax and support.

theme-one-dark module

oneDark: Extension

Extension to enable the One Dark theme.