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"})})
document.body.appendChild(myView.dom)

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 behavior), or an instance of the Text class (which is what the state will use to represent the document).

selection⁠?: EditorSelection

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

extensions⁠?: any

State or view extensions to associate with this state. View extensions provided here only take effect when the state is put into an editor view.

class EditorState

The editor state class is a persistent (immutable) data structure. To update a state, you create and apply 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.

t(timestamp⁠?: number) → Transaction

Start a new transaction from this state. When not given, the timestamp defaults to Date.now().

joinLines(text: readonly string[]) → string

Join an array of lines using the state's line separator.

splitLines(textstring) → string[]

Split a string into lines using the state's line separator.

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

Get the value of a state behavior.

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

readonly indentUnit: number

The size of an indent unit in the document. Determined by the indentUnit facet.

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.

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(stateEditorState, posnumber) → number, readonly fn(stateEditorState, 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 behavior is used.

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<number, number>

Facet for overriding the unit (in columns) by which indentation happens. When not set, this defaults to 2.

static syntax: Facet<Syntax, readonly Syntax[]>

Facet that registers a parsing service for the state.

static foldable: Facet<fn(stateEditorState, lineStartnumber, lineEndnumber) → null | {from: number, to: number}, readonly 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, it'll return a range object when a foldable that starts on that line (but continues beyond it) can be found.

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(anchornumber, head⁠?: number = anchor)

Create a range. head defaults to anchor when not given.

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 from: number

The lower side of the range.

readonly to: number

The upper side of the range.

readonly empty: boolean

True when anchor and head are at the same position.

map(mappingMapping) → 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(mappingMapping) → 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 transaction methods like forEachRange.

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.

re-export Text

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.t().replace(6, 11, "editor")
console.log(transaction.doc.toString()) // "hello editor"
let newState = transaction.apply()

class ChangeDesc implements Mapping

A change description describes a document change. This is usually used as a superclass of Change, but can be used to store change data without storing the replacement string content.

new ChangeDesc(fromnumber, tonumber, lengthnumber)

Create a description that replaces the text between positions from and to with a new string of length length.

readonly from: number

The start position of the change.

readonly to: number

The end of the change (as a pre-change document position).

readonly length: number

The length of the replacing content.

readonly invertedDesc: ChangeDesc

Get the change description of the inverse of this change.

toJSON() → any

Return a JSON-serializeable object representing this value.

static fromJSON(jsonany) → ChangeDesc

Create a change description from its JSON representation.

class Change extends ChangeDesc

Change objects describe changes to the document.

new Change(fromnumber, tonumber, text: readonly string[])

Create a change that replaces from to to with text. The text is given as an array of lines. When it doesn't span lines, the array has a single element. When it does, a new element is added for every line. It should never have zero elements.

readonly text: readonly string[]

The replacement content.

invert(docText) → Change

Create the inverse of this change when applied to the given document. change.invert(doc).apply(change.apply(doc)) gets you the same document as the original doc.

apply(docText) → Text

Apply this change to the given content, returning an updated version of the document.

map(mappingMapping) → null | Change

Map this change through a mapping, producing a new change that can be applied to a post-mapping document. May return null if the mapping completely replaces the region this change would apply to.

readonly desc: ChangeDesc

A change description for this change.

toJSON() → any

Produce a JSON-serializable object representing this change.

static fromJSON(jsonany) → Change

Read a change instance from its JSON representation.

class ChangeSet<C extends ChangeDesc = Change> implements Mapping

A change set holds a sequence of changes or change descriptions.

readonly changes: readonly C[]

The changes in this set.

readonly length: number

The number of changes in the set.

getMirror(nnumber) → null | number

Change sets can track which changes are inverses of each other, to allow robust position mapping in situations where changes are undone and then redone again. This queries which change is the mirror image of a given change (by index).

append(changeC, mirror⁠?: number) → ChangeSet<C>

Append a change to this set, returning an extended set. mirror may be the index of a change already in the set, which mirrors the new change.

appendSet(changesChangeSet<C>) → ChangeSet<C>

Append another change set to this one.

touchesRange(fromnumber, tonumber) → 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.

partialMapping(fromnumber, to⁠?: number = this.length) → Mapping

Get a partial mapping covering part of this change set.

changedRanges() → readonly ChangedRange[]

Summarize this set of changes as a minimal sequence of changed ranges, sored by position. For example, if you have changes deleting between 1 and 4 and inserting a character at 1, the result would be a single range saying 1 to 4 in the old doc was replaced with range 1 to 2 in the new doc.

readonly desc: ChangeSet<ChangeDesc>

Convert a set of changes to a set of change descriptions.

toJSON() → any

Create a JSON-serializable representation of this change set.

static empty: ChangeSet<any>

The empty change set.

static fromJSON<C extends ChangeDesc>(ChangeType: {fromJSON: fn(jsonany) → C}, jsonany) → ChangeSet<C>

Read a change set from its JSON representation.

class Transaction

Changes to the editor state are grouped into transactions. Usually, a user action creates a single transaction, which may contain zero or more document changes. Create a transaction by calling EditorState.t.

Transactions are mutable, and usually built up piece by piece with updating methods and method chaining (most methods return the transaction itself). Once they are applied, they can't be updated anymore.

changes: ChangeSet<Change>

The document changes made by this transaction.

docs: Text[]

The document versions after each of the changes.

selection: EditorSelection

The selection at the end of the transaction.

readonly startState: EditorState

The state from which the transaction starts.

readonly doc: Text

The document at the end of the transaction.

annotate<T>(annotationAnnotation<T>, valueT) → Transaction

Add annotations to this transaction. Annotations can provide additional information about the transaction.

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

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

change(changeChange, mirror⁠?: number) → Transaction

Add a change to this transaction. If mirror is given, it should be the index (in this.changes.changes) at which the mirror image of this change sits.

readonly docChanged: boolean

Indicates whether the transaction changed the document.

replace(fromnumber, tonumber, textstring | readonly string[]) → Transaction

Add a change replacing the given document range with the given content.

replaceSelection(textstring | readonly string[]) → Transaction

Replace all selection ranges with the given content.

forEachRange(ffn(rangeSelectionRange, trTransaction) → SelectionRange) → Transaction

Run the given function for each selection range. The method will map the ranges to reflect deletions/insertions that happen before them. At the end, set the new selection to the ranges returned by the function (again, automatically mapped to for changes that happened after them).

setSelection(selectionEditorSelection) → Transaction

Update the selection.

readonly selectionSet: boolean

Tells you whether this transaction explicitly sets a new selection (as opposed to just mapping the selection through changes).

scrollIntoView() → Transaction

Set a flag on this transaction that indicates that the editor should scroll the selection into view after applying it.

readonly scrolledIntoView: boolean

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

replaceExtension(groupExtensionGroup, contentany) → Transaction

Provice new content for a given extension group in the current configuration. (If the group isn't present in the configuration, this will not have any effect.)

reconfigure(extensionany) → Transaction

Move to an entirely new state configuration.

readonly reconfigured: boolean

Indicates whether the transaction reconfigures the state.

apply() → EditorState

Apply this transaction, computing a new editor state. May be called multiple times (the result is cached). The transaction cannot be further modified after this has been called.

invertedChanges() → ChangeSet<Change>

Create a set of changes that undo the changes made by this transaction.

static time: Annotation<number>

Annotation used to store transaction timestamps.

static preserveGoalColumn: Annotation<boolean>

Annotation used to indicate that this transaction shouldn't clear the goal column, which is used during vertical cursor motion (so that moving over short lines doesn't reset the horizontal position to the end of the shortest line). Should generally only be set by commands that perform vertical motion.

static userEvent: Annotation<string>

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

  • "paste" when pasting content
  • "cut" when cutting
  • "drop" when content is inserted via drag-and-drop
  • "keyboard" when moving the selection via the keyboard
  • "pointer" when moving the selection through the pointing device
static addToHistory: Annotation<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.

static define<T>() → Annotation<T>

Define a new type of annotation.

enum MapMode

Distinguishes different ways in which positions can be mapped.

Simple

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

TrackDel

Return a negative number if a deletion happens across the position. This number will be -(newPos + 1), where newPos is the result you'd get with MapMode.Simple.

TrackBefore

Return a negative number if the character before the position is deleted. The result is encoded the same way as with MapMode.TrackDel.

TrackAfter

Return a negative number if the character after the position is deleted.

interface Mapping

Interface for things that support position mapping.

mapPos(posnumber, bias⁠?: number, mode⁠?: MapMode) → number

Map a given position through a set of changes.

bias indicates whether, when content is inserted at the position or the content around the position is replaced, the position at the end (positive) or start (negative or zero) of that change should be used. It defaults to -1.

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

class ChangedRange

A changed range represents a replacement as two absolute ranges, one pointing into the old document (the replaced content) and one pointing into the new document (the content that replaces it).

new ChangedRange(fromAnumber, toAnumber, fromBnumber, toBnumber)
readonly fromA: number

The start of the replaced range in the old document.

readonly toA: number

The end of the replaced range in the old document.

readonly fromB: number

The start of the replacing range in the new document.

readonly toB: number

The end of the replacing range in the new document.

readonly lenDiff: number

The difference in document length created by this change (positive when the document grew).

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 = any

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.

type StateFieldSpec<Value>

Parameters passed when creating a StateField. The Value type parameter refers to the content of the field. Since it will be stored in (immutable) state objects, it should be an immutable value itself.

create(stateEditorState) → Value

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

update(valueValue, transactionTransaction, newStateEditorState) → 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 ==.

class StateField<Value>

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

provide(facetFacet<Value, any>) → StateField<Value>
provide<T>(facetFacet<T, any>, getfn(valueValue) → T, prec⁠?: Precedence) → StateField<Value>

Extends the field to also provide a facet value. Returns a new StateField instance that, when used to extend a state, provides an input to the given facet that's derived from the field. When no get value is given, the entire value of the field is used as facet input.

provideN<T>(facetFacet<T, any>, getfn(valueValue) → readonly T[], prec⁠?: Precedence) → StateField<Value>

Extends the field to provide zero or more input values for the given facet.

[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>(configStateFieldSpec<Value>) → StateField<Value>

Define a state field.

type FacetConfig<Input, Output>

Config object passed to defineFacet.

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.

class Facet<Input, Output>

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) → any

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

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

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 StateField.provide instead.

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

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

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

Define a new facet.

class Precedence

By default extensions are registered in the order they are provided in a flattening of the nested arrays that were 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.

set(extensionany) → any

Tag an extension with this precedence.

static Fallback: Precedence

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.

static Default: Precedence

The regular default precedence.

static Extend: Precedence

A higher-than-default precedence.

static Override: Precedence

Precedence above the Default and Extend precedences.

class ExtensionGroup

Extension groups can be used to make a configuration dynamic. Wrapping an extension in a group allows you to later replace it with Transaction.replaceExtension. A given group may only occur once within a given configuration.

new ExtensionGroup(namestring)

Define a new group. The name is used only for debugging purposes.

readonly name: string
of(extensionany) → any

Tag the given extension with this group.

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.

docNodeType: NodeType

The node type at the root of trees produced by this syntax.

languageDataAt<Interface = any>(stateEditorState, posnumber) → Interface

Return the language data object for the given position. This'll usually be the be the data for the grammar's top node, but with nested grammars it may be the data of some nested grammar.

languageData: NodeProp<Object>

A node prop that can be stored on a grammar's top node to associate information with the language. Different extension might use different properties from this object (which they typically export as an interface).

Utilities

fillConfig<Config>(configConfig, defaultsPartial<Config>) → Required<Config>

Defaults the fields in a configuration object to values given in defaults if they are not already present.

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

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

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, text: readonly string[]) → Text

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

sliceLines(fromnumber, to⁠?: number = this.length) → readonly string[]

Retrieve the lines between the given points.

slice(fromnumber, to⁠?: number, lineSeparator⁠?: string = "\n") → string

Retrieve the text between the given points.

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

toString() → string

Flattens the document into a single string, using "\n" as line separator.

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 start: number

The position of the start of the line.

readonly end: 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.

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.

Character Types

isExtendingChar(codenumber) → boolean

Test whether a given code unit (as in, the thing that charCodeAt returns) extends the character before it.

isWordChar(chstring, wordChars⁠?: RegExp) → boolean

Test whether the given character is a word character.

enum CharType

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

Word
Space
Other
charType(chstring, wordChars⁠?: RegExp) → CharType

Determine the character type for a given character.

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.

minPairCodePoint: 65536

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.

interface EditorConfig

Configuration parameters passed when creating an editor view.

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.

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⁠?: EditorConfig = {})

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.

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 dispatch(trTransaction)

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

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.

update(transactionsTransaction[])

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.

updatePlugins(updateViewUpdate)
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.

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

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

Find information for the line 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.

lineAt(posnumber, editorTop⁠?: number) → BlockInfo

Find the height information for the given line.

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.

movePos(startnumber, direction"forward" | "backward" | "left" | "right", granularity⁠?: "character" | "word" | "line" | "lineboundary" = "character", action⁠?: "move" | "extend" = "move") → number

Compute cursor motion from the given position, in the given direction, by the given unit. Since this might involve temporarily mutating the DOM selection, you can pass the action type this will be used for to, in case the editor selection is set to the new position right away, avoid an extra DOM selection change.

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) → 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: "ltr" | "rtl"

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

startMouseSelection(eventMouseEvent, updatefn(viewEditorView, startSelectionEditorSelection, startPosnumber, startBias-1 | 1, curPosnumber, curBias-1 | 1, extendboolean, multipleboolean) → EditorSelection)

Start a custom mouse selection event.

readonly hasFocus: boolean

Check whether the editor has focus.

focus()

Put focus on the editor.

destroy()

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 plugin: Facet<ViewPlugin<any>, readonly ViewPlugin<any>[]>

Facet that registers view plugins. Usually, it is more convenient to use ViewPlugin.register.

static styleModule: Facet<StyleModule<Object>, readonly 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: Facet<Object<fn(viewEditorView, eventany) → boolean>, readonly Object<fn(viewEditorView, eventany) → boolean>[]>

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 dragMovesSelection: Facet<fn(eventMouseEvent) → boolean, readonly 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, readonly 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 decorations: Facet<RangeSet<Decoration>, readonly RangeSet<Decoration>[]>

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>) → any

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.

static baseTheme(specObject<Style>) → any

Create an extension that adds styles to the base theme.

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

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

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

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

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

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

enum BlockType

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

Text

A line of text.

WidgetBefore

A block widget associated with the position after it.

WidgetAfter

A block widget associated with the position before it.

WidgetRange

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.

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 "panel.search" will match both the theme styles specified as "panel.search" and those with just "panel". More specific theme styles (with more dots) take precedence.

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: any

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: RangeSet<Decoration>} & 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.

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 behaviors). 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 pluginValues 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<Change>

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.

Decorations

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(specMarkDecorationSpec) → Decoration

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

static widget(specWidgetDecorationSpec) → Decoration

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

static replace(specReplaceDecorationSpec) → Decoration

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

static line(specLineDecorationSpec) → Decoration

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

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

Build a DecorationSet from the given decorated range or ranges.

static none: RangeSet<Decoration>

The empty set of decorations.

interface MarkDecorationSpec

Options passed when creating a mark decoration.

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.

interface WidgetDecorationSpec

Options passed when creating a widget decoration.

widget: WidgetType<any>

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.

interface LineDecorationSpec

Options passed when creating a line decoration.

attributes⁠?: Object<string>

DOM attributes to add to the element wrapping the line.

interface ReplaceDecorationSpec

Options passed when creating a replacing decoration.

widget⁠?: WidgetType<any>

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.

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

pcBaseKeymap: Object<Command>

The default keymap for Linux/Windows/non-Mac platforms. Binds the arrows for cursor motion, shift-arrow for selection extension, ctrl-arrows for by-word motion, home/end for line start/end, ctrl-home/end for document start/end, ctrl-a to select all, backspace/delete for deletion, and enter for newline-and-indent.

macBaseKeymap: Object<Command>

The default keymap for Mac platforms. Includes the bindings from the PC keymap (using Cmd instead of Ctrl), and adds Mac-specific default bindings.

baseKeymap: Object<Command>

The default keymap for the current platform.

Cursor Motion

moveCharLeft: Command

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

moveCharRight: Command

Move the selection one character to the right.

moveWordLeft: Command

Move the selection one word to the left.

moveWordRight: Command

Move the selection one word to the right.

moveLineUp: Command

Move the selection one line up.

moveLineDown: Command

Move the selection one line down.

moveLineStart: Command

Move the selection to the start of the line.

moveLineEnd: Command

Move the selection to the end of the line.

selectDocStart: StateCommand

Move the selection to the start of the document.

selectDocEnd: StateCommand

Move the selection to the end of the document.

selectAll: StateCommand

Select the entire document.

Selection Extension

extendCharLeft: Command

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

extendCharRight: Command

Move the selection head one character to the right.

extendWordLeft: Command

Move the selection head one word to the left.

extendWordRight: Command

Move the selection head one word to the right.

extendLineUp: Command

Move the selection head one line up.

extendLineDown: Command

Move the selection head one line down.

extendLineStart: Command

Move the selection head to the start of the line.

extendLineEnd: Command

Move the selection head to the end of the line.

Deletion

deleteCharBackward: Command

Delete the character before the cursor (which is the one to left in left-to-right text, but the one to the right in right-to-left text).

deleteCharForward: Command

Delete the character after the cursor.

Indentation

insertNewlineAndIndent: StateCommand

Replace the selection with a newline and indent the newly created line(s).

indentSelection: StateCommand

Auto-indent the selected lines. This uses the indentation behavor as source.

history module

interface HistoryConfig

Options given when creating a history extension.

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.

history(config⁠?: HistoryConfig = {}) → any

Create a history extension with the given configuration.

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.

closeHistory(trTransaction) → Transaction

Set a flag on the given transaction that will prevent further steps from being appended to an existing history event (so that they require a separate undo command to undo).

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.

redoSelectionDepth(stateEditorState) → number

The amount of undoable events available in a given state.

undoSelectionDepth(stateEditorState) → number

The amount of redoable events available in a given state.

gutter module

interface LineNumberConfig

Configuration options when creating a line number gutter.

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.

lineNumbers(config⁠?: LineNumberConfig = {}) → any

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

interface GutterConfig

Configuration options when creating a generic 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.

initialMarkers⁠?: fn(viewEditorView) → RangeSet<GutterMarker>

A function that computes the initial set of markers for the gutter, if any. Defaults to the empty set.

updateMarkers⁠?: fn(markersRangeSet<GutterMarker>, updateViewUpdate) → RangeSet<GutterMarker>

A function that updates the set of markers when the view updates. This is where you could read transaction information to add or remove markers, depending on the kind of gutter you are implementing.

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.

gutter(configGutterConfig) → any

Define an editor gutter.

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

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: Annotation<LineNumberMarkerUpdate>

Used to insert markers into the line number gutter.

type LineNumberMarkerUpdate

add⁠?: Range<GutterMarker>[]

When given, adds these markers.

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

Filter the line number markers through this function.

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.

startMapMode: MapMode

The mode with which the start point of the range should be mapped. Determines when a side is counted as deleted. Defaults to MapMode.TrackDel.

endMapMode: MapMode

The mode with which the end point of the range should be mapped.

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.

type RangeSetUpdate<T extends RangeValue>

Arguments passed to RangeSet.update.

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.

filterFrom⁠?: number
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.

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(RangeSetUpdate<T>) → RangeSet<T>

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

map(changesChangeSet<Change>) → 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 the set that touch the area between from and to, ordered by their start position and side.

static compare<T extends RangeValue>(oldSets: readonly RangeSet<T>[], newSets: readonly RangeSet<T>[], textDiff: readonly ChangedRange[], lengthnumber, 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).

next()

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.

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.

special-chars module

interface SpecialCharConfig

Configure the special character highlighter.

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.

specialChars(config⁠?: SpecialCharConfig = {}) → any

Returns an extension that installs highlighting of special characters.

syntax module

class LezerSyntax implements Syntax

A syntax provider based on a Lezer parser.

new LezerSyntax(parserParser)

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.

readonly field: StateField<{updatedTree: Tree, parse: ParseContext | null, tree: Tree, upto: number, apply: fn(trTransaction, parserParser, annotationAnnotation<Object>) → Object, startParse: fn(parserParser, docText), stopParse: fn(tree⁠?: Tree, upto⁠?: number) → Tree}>
readonly extension: any

The extension value to install this provider.

readonly parser: Parser
openNodeProp: NodeProp<string[]>

A node prop that encodes information about which other nodes match this node as delimiters. Should hold a space-separated list of node names of the closing nodes that match this node.

closeNodeProp: NodeProp<string[]>

Like openNodeProp, but for closing nodes. Should hold a space-separated list of opening node names that match this closing delimiter.

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.

Indentation

indentNodeProp: NodeProp<fn(contextIndentContext) → 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 IndentContext

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

readonly state: EditorState

The editor state.

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 unit: number

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

readonly textAfter: string

Get the text directly after this.pos, either the entire line or the next 50 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.

readonly baseIndent: number

Get the indentation at the reference line for this.tree, 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.

column(posnumber) → number

Find the column for the given position.

delimitedIndent({closing: string, align⁠?: boolean, units⁠?: number}) → fn(contextIndentContext) → 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:

foo(bar,
    baz)
continuedIndent({except⁠?: RegExp, units⁠?: number} = {}) → fn(contextIndentContext) → 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(contextIndentContext) → number

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

matchbrackets module

interface Config

Configuration options

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.

bracketMatching(config⁠?: Config = {}) → any

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.

matchBrackets(stateEditorState, posnumber, dir-1 | 1, config⁠?: Config = {}) → 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.

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.

keymap module

type Keymap

A keymap associates 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.

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.

keymap(mapKeymap) → any

Create a view extension that registers a keymap.

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

class NormalizedKeymap<T>

Stores a set of keybindings in normalized form, and helps looking up the binding for a keyboard event. Only needed when binding keys in some custom way.

new NormalizedKeymap(mapObject<T>)

Create a normalized map.

get(eventKeyboardEvent) → undefined | T

Look up the binding for the given keyboard event, or undefined if none is found.

multiple-selections module

multipleSelections() → any

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.

lint module

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[]) → any

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

linting() → any

Returns an extension that enables the linting functionality. Implicitly enabled by the linter function.

openLintPanel: Command

Command to open and focus the lint panel.

closeLintPanel: Command

Command to close the lint panel, when open.

setDiagnostics: Annotation<readonly Diagnostic[]>

Transaction annotation that is used to update the current set of diagnostics.

autocomplete module

interface AutocompleteData

completeAt(stateEditorState, posnumber) → CompletionResult | Promise<CompletionResult>

interface CompletionResult

items: readonly Completion[]

interface Completion

label: string
start: number
end: number
apply⁠?: string | fn(viewEditorView)
completeFromSyntax(stateEditorState, posnumber) → CompletionResult | Promise<CompletionResult>
sortAndFilterCompletion(substrstring, items: readonly Completion[]) → Completion[]
autocomplete(config⁠?: Partial<AutocompleteData> = {}) → any
startCompletion(viewEditorView) → boolean

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() → any

Enables the panel-managing extension.

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 "panel.foo".

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, readonly fn(viewEditorView) → Panel[]>

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

tooltip module

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

tooltips() → any

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

interface Tooltip

Describes a tooltip.

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.

pos: number

The document position at which to show the tooltip.

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.

showTooltip: Facet<fn(viewEditorView) → Tooltip, readonly fn(viewEditorView) → Tooltip[]>

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

interface HoverTooltip

Hover tooltips are associated with a range, rather than a single position.

start: number

The start of the target range.

end: number

The end of the target range. The tooltip will be hidden when the pointer is no longer over this range.

tooltip(viewEditorView) → Tooltip

The tooltip constructor.

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

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.

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>) → any

Create a highlighter theme that adds the given styles to the given tags. The spec's property names must be tag names, and the values style-mod style objects that define the CSS for that tag.

defaultHighlighter: any

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>) → any

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.

skipToEnd()

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.

backUp(nnumber)

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: any

The extension that installs this syntax provider.

lang-javascript module

javascriptSyntax: LezerSyntax

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

javascript() → any

Returns an extension that installs the JavaScript syntax provider.

lang-css module

cssSyntax: LezerSyntax

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

css() → any

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.

html() → any

Returns an extension that installs the HTML syntax provider.