Reference manual

This is the reference manual for the ProseMirror rich text editor. It lists and describes the full public API exported by the library.

For more introductory material, please see the guides.

ProseMirror is structured as a number of separate modules. This reference manual describes the exported API per module. We'll usually use the abbreviated module name here, but on NPM they are prefixed with prosemirror-. So if you want to use something from the state module, you have to import it like this:

var EditorState = require("prosemirror-state").EditorState
var state = EditorState.create({schema: mySchema})

Or in ES6 syntax:

import {EditorState} from "prosemirror-state"
let state = EditorState.create({schema: mySchema})

module state

This module implements the state object of a ProseMirror editor, along with the representation of the selection and the plugin abstraction.

Editor State

ProseMirror keeps all editor state (the things, basically, that would be required to create an editor just like the current one) in a single object. That object is updated (creating a new state) by applying actions to it.

class EditorState

The state of a ProseMirror editor is represented by an object of this type. This is a persistent data structure—it isn't updated, but rather a new state value is computed from an old one with the applyAction method.

In addition to the built-in state fields, plugins can define additional pieces of state.

doc: Node

The current document.

selection: Selection

The selection.

storedMarks: ?[Mark]

A set of marks to apply to the next character that's typed. Will be null whenever no explicit marks have been set.

schema: Schema

The schema of the state's document.

plugins: [Plugin]

The plugins that are active in this state.

applyAction(action: Action) → EditorState

Apply the given action to produce a new state.

tr: EditorTransform

Create a selection-aware Transform object.

reconfigure(config: Object) → EditorState

Create a new state based on this one, but with an adjusted set of active plugins. State fields that exist in both sets of plugins are kept unchanged. Those that no longer exist are dropped, and those that are new are initialized using their init method, passing in the new configuration object..

toJSON(options: ?Object) → Object

Convert this state to a JSON-serializable object. When the ignore option is given, it is interpreted as an array of field names that should not be serialized.

static create(config: Object) → EditorState

Create a state. config must be an object containing at least a schema (the schema to use) or doc (the starting document) property. When it has a selection property, that should be a valid selection in the given document, to use as starting selection. Plugins, which are specified as an array in the plugins property, may read additional fields from the config object.

static fromJSON(config: Object, json: Object) → EditorState

Deserialize a JSON representation of a state. config should have at least a schema field, and should contain array of plugins to initialize the state with. It is also passed as starting configuration for fields that were not serialized.

interface Action

State updates are performed through actions, which are objects that describe the update.

type: string

The type of this action. This determines the way the action is interpreted, and which other fields it should have.

interface TransformAction

An action type that transforms the state's document. Applying this will create a state in which the document is the result of this transformation.

type: "transform"
transform: Transform
selection: ?Selection

If given, this selection will be used as the new selection. If not, the old selection is mapped through the transform.

scrollIntoView: ?bool

When true, the next display update will scroll the cursor into view.

interface SelectionAction

An action that updates the selection.

type: "selection"
selection: Selection

The new selection.

scrollIntoView: ?bool

When true, the next display update will scroll the cursor into view.

interface AddStoredMarkAction

An action type that adds a stored mark to the state.

type: "addStoredMark"
mark: Mark

interface RemoveStoredMarkAction

An action type that removes a stored mark from the state.

type: "removeStoredMark"
markType: MarkType

class EditorTransform extends Transform

A selection-aware extension of Transform. Use EditorState.tr to create an instance.

selection: Selection

The transform's current selection. This defaults to the editor selection mapped through the steps in this transform, but can be overwritten with setSelection.

setSelection(selection: Selection) → EditorTransform

Update the transform's current selection. This will determine the selection that the editor gets when the transform is applied.

replaceSelection(node: ?Node, inheritMarks: ?bool) → EditorTransform

Replace the selection with the given node, or delete it if node is null. When inheritMarks is true and the node is an inline node, it inherits the marks from the place where it is inserted.

deleteSelection() → EditorTransform

Delete the selection.

insertText(text: string, from: ?number, to: ?number = from) → EditorTransform

Replace the given range, or the selection if no range is given, with a text node containing the given string.

action(options: ?Object) → TransformAction

Create a transform action. options can be given to add extra properties to the action object.

scrollAction() → TransformAction

Create a transform action with the scrollIntoView property set to true (this is common enough to warrant a shortcut method).

Selection

A ProseMirror selection can be either a classical text selection (of which cursors are a special case), or a node selection, where a specific document node is selected.

class Selection

Superclass for editor selections.

from: number

The lower bound of the selection.

to: number

The upper bound of the selection.

$from: ResolvedPos

The resolved lower bound of the selection

$to: ResolvedPos

The resolved upper bound of the selection

empty: bool

True if the selection is an empty text selection (head an anchor are the same).

action(options: ?Object) → SelectionAction

Create an action that updates the selection to this one.

eq(other: Selection) → bool

Test whether the selection is the same as another selection.

map(doc: Node, mapping: Mappable) → Selection

Map this selection through a mappable thing. doc should be the new document, to which we are mapping.

toJSON() → Object

Convert the selection to a JSON representation.

static findFrom($pos: ResolvedPos, dir: number, textOnly: ?bool) → ?Selection

Find a valid cursor or leaf node selection starting at the given position and searching back if dir is negative, and forward if negative. When textOnly is true, only consider cursor selections.

static near($pos: ResolvedPos, bias: ?number = 1, ?bool) → Selection

Find a valid cursor or leaf node selection near the given position. Searches forward first by default, but if bias is negative, it will search backwards first.

static atStart(doc: Node, textOnly: ?bool) → ?Selection

Find the cursor or leaf node selection closest to the start of the given document. When textOnly is true, only consider cursor selections.

static atEnd(doc: Node, textOnly: ?bool) → ?Selection

Find the cursor or leaf node selection closest to the end of the given document. When textOnly is true, only consider cursor selections.

static between($anchor: ResolvedPos, $head: ResolvedPos, bias: ?number) → Selection

Find a selection that spans the given positions, if both are text positions. If not, return some other selection nearby, where bias determines whether the method searches forward (default) or backwards (negative number) first.

static fromJSON(doc: Node, json: Object) → Selection

Deserialize a JSON representation of a selection.

class TextSelection extends Selection

A text selection represents a classical editor selection, with a head (the moving side) and anchor (immobile side), both of which point into textblock nodes. It can be empty (a regular cursor position).

new TextSelection($anchor: ResolvedPos, $head: ?ResolvedPos = $anchor)

Construct a text selection.

anchor: number

The selection's immobile side (does not move when pressing shift-arrow).

head: number

The selection's mobile side (the side that moves when pressing shift-arrow).

$anchor: ResolvedPos

The resolved anchor of the selection.

$head: ResolvedPos

The resolved head of the selection.

class NodeSelection extends Selection

A node selection is a selection that points at a single node. All nodes marked selectable can be the target of a node selection. In such an object, from and to point directly before and after the selected node.

new NodeSelection($from: ResolvedPos)

Create a node selection. Does not verify the validity of its argument. Use ProseMirror.setNodeSelection for an easier, error-checking way to create a node selection.

node: Node

The selected node.

Plugin System

To make distributing and using extra editor functionality easier, ProseMirror has a plugin system.

class Plugin

Plugins wrap extra functionality that can be added to an editor. They can define new state fields, and add view props.

There are two ways to use plugins. The easiest way is to have a factory function that simply creates instances of this class. This creates a non-unique plugin, of which multiple instances can be added to a single editor.

The alternative is to have a single plugin instance, and optionally derive different configurations from it using configure. This creates a unique plugin, which means that an error is raised when multiple instances are added to a single editor. This is appropriate if your plugin defines state fields, for example. You can find the instance of such a plugin in a state by calling its find method.

new Plugin(options: Object)

Create a plugin.

options: Object
props: ?EditorProps

The view props added by this plugin.

stateFields: ?Object<StateField>

Extra state fields defined by this plugin.

config: ?Object

A set of plugin-specific configuration parameters used by this plugin.

dependencies: ?[Plugin]

A set of plugins that should automatically be added to the plugin set when this plugin is added.

props: EditorProps

The props exported by this plugin.

config: Object

The plugin's configuration object.

configure(config: Object) → Plugin

Create a reconfigured instance of this plugin. Any config fields not listed in the given object are inherited from the original configuration.

find(state: EditorState) → ?Plugin

Find the instance of this plugin in a given editor state, if it exists. Note that this only works if the plugin in the state is either this exact plugin, or they both share a common ancestor through configure calls.

interface StateField

A plugin may provide a set of state fields, as an object (under its stateFields property) mapping field names to description objects of this type.

init(config: Object, instance: EditorState) → T

Initialize the value of this field. config will be the object passed to EditorState.create. Note that instance is a half-initialized state instance, and will not have values for any fields initialzed after this one.

applyAction(state: EditorState, action: Action) → T

Apply the given action to this state field, producing a new field value. Note that the state argument is the old state, before the action was applied.

toJSON(value: T) → any

Convert this field to JSON. Optional, can be left off to disable JSON serialization for the field.

fromJSON(config: Object, value: any, state: EditorState) → T

Deserialize the JSON representation of this field. Note that the state argument is again a half-initialized state.

module view

ProseMirror's view displays a given editor state in the DOM, and handles user events.

Make sure you load style/prosemirror.css as a stylesheet if you want to instantiate a ProseMirror editor.

class EditorView

An editor view manages the DOM structure that represents an editor. Its state and behavior are determined by its props.

new EditorView(place: ?dom.Node | fn(dom.Node), props: EditorProps)

Create a view. place may be a DOM node that the editor should be appended to, or a function that will place it into the document. If it is null, the editor will not be added to the document.

props: EditorProps

The view's current props.

state: EditorState

The view's current state.

content: dom.Node

The editable DOM node containing the document. (You probably should not be directly interfering with its child nodes.)

update(props: EditorProps)

Update the view's props. Will immediately cause an update to the view's DOM.

updateState(state: EditorState)

Update the editor's state prop, without touching any of the other props.

hasFocus() → bool

Query whether the view has focus.

someProp(propName: string, f: fn(prop: any) → any) → any

Goes over the values of a prop, first those provided directly, then those from plugins (in order), and calls f every time a non-undefined value is found. When f returns a truthy value, that is immediately returned. When f isn't provided, it is treated as the identity function (the prop value is returned directly).

focus()

Focus the editor.

root: dom.Document | dom.DocumentFragment

Get the document root in which the editor exists. This will usually be the top-level document, but might be a shadow DOM root if the editor is inside a shadow DOM.

posAtCoords(coords: {left: number, top: number}) → ?number

Given a pair of coordinates, return the document position that corresponds to them. May return null if the given coordinates aren't inside of the visible editor.

coordsAtPos(pos: number) → {left: number, right: number, top: number, bottom: number}

Returns the screen rectangle at a given document position. left and right will be the same number, as this returns a flat cursor-ish rectangle.

interface EditorProps

The configuration object that can be passed to an editor view. It supports the following properties (only state and onAction are required).

The various event-handling functions may all return true to indicate that they handled the given event. The view will then take care to call preventDefault on the event, except with `handleDOMEvent, where the handler itself is responsible for that.

Except for state and onAction, these may also be present on the props property of plugins. How a prop is resolved depends on the prop. Handler functions are called one at a time, starting with the plugins (in order of appearance), and finally looking at the base props, until one of them returns true. For some props, the first plugin that yields a value gets precedence. For class, all the classes returned are combined.

state: EditorState

The state of the editor.

onAction(action: Action)

The callback over which to send actions (state updates) produced by the view. You'll usually want to make sure this ends up calling the view's update method with a new state that has the action applied.

handleDOMEvent(view: EditorView, event: dom.Event) → bool

Called before the view handles a DOM event. This is a kind of catch-all override hook. Contrary to the other event handling props, when returning true from this one, you are responsible for calling preventDefault yourself (or not, if you want to allow the default behavior).

handleKeyDown(view: EditorView, event: dom.KeyboardEvent) → bool

Called when the editor receives a keydown event.

handleKeyPress(view: EditorView, event: dom.KeyboardEvent) → bool

Handler for keypress events.

handleTextInput(view: EditorView, from: number, to: number, text: string) → bool

Whenever the user directly input text, this handler is called before the input is applied. If it returns true, the default effect of actually inserting the text is suppressed.

handleClickOn(view: EditorView, pos: number, node: Node, nodePos: number, event: dom.MouseEvent) → bool

Called for each node around a click, from the inside out.

handleClick(view: EditorView, pos: number, event: dom.MouseEvent) → bool

Called when the editor is clicked, after handleClickOn handlers have been called.

handleDoubleClickOn(view: EditorView, pos: number, node: Node, nodePos: number, event: dom.MouseEvent) → bool

Called for each node around a double click.

handleDoubleClick(view: EditorView, pos: number, event: dom.MouseEvent) → bool

Called when the editor is double-clicked, after handleDoubleClickOn.

handleTripleClickOn(view: EditorView, pos: number, node: Node, nodePos: number, event: dom.MouseEvent) → bool

Called for each node around a triple click.

handleTripleClick(view: EditorView, pos: number, event: dom.MouseEvent) → bool

Called when the editor is triple-clicked, after handleTripleClickOn.

handleContextMenu(view: EditorView, pos: number, event: dom.MouseEvent) → bool

Called when a context menu event is fired in the editor.

onFocus(view: EditorView, event: dom.Event)

Called when the editor is focused.

onBlur(view: EditorView, event: dom.Event)

Called when the editor loses focus.

onUnmountDOM(view: EditorView, dom.Node)

Called when a display update throws away a DOM node that was part of the previous document view. Can be useful when your node representations need to be cleaned up somehow. Note that this is only called with the top of the unmounted tree, not with every node in it.

domParser: ?DOMParser

The parser to use when reading editor changes from the DOM. Defaults to calling DOMParser.fromSchema on the editor's schema.

clipboardParser: ?DOMParser

The parser to use when reading content from the clipboard. When not given, the value of the domParser prop is used.

transformPasted(Slice) → Slice

Can be used to transform pasted content before it is applied to the document.

domSerializer: ?DOMSerializer

The serializer to use when drawing the document to the display. If not given, the result of DOMSerializer.fromSchema will be used.

clipboardSerializer: ?DOMSerializer

The DOM serializer to use when putting content onto the clipboard. When not given, the value of the domSerializer prop is used.

spellcheck: ?bool

Controls whether the DOM spellcheck attribute is enabled on the editable content. Defaults to false.

class(state: EditorState) → ?string

Controls the CSS class name of the editor DOM node. Any classes returned from this will be added to the default ProseMirror class.

label(state: EditorState) → ?string

Can be used to set an aria-label attribute on the editable content node.

scrollThreshold: ?number

Determines the distance (in pixels) between the cursor and the end of the visible viewport at which point, when scrolling the cursor into view, scrolling takes place. Defaults to 0.

scrollMargin: ?number

Determines the extra space (in pixels) that is left above or below the cursor when it is scrolled into view. Defaults to 5.

module model

This module defines ProseMirror's content model, the data structures used to represent and manipulate documents.

Document Structure

A ProseMirror document is a tree. At each level, a node tags the type of content that's there, and holds a fragment containing its children.

class Node

This class represents a node in the tree that makes up a ProseMirror document. So a document is an instance of Node, with children that are also instances of Node.

Nodes are persistent data structures. Instead of changing them, you create new ones with the content you want. Old ones keep pointing at the old document shape. This is made cheaper by sharing structure between the old and new data as much as possible, which a tree shape like this (without back pointers) makes easy.

Never directly mutate the properties of a Node object. See this guide for more information.

type: NodeType

The type of node that this is.

attrs: Object

An object mapping attribute names to values. The kind of attributes allowed and required are determined by the node type.

content: Fragment

A container holding the node's children.

marks: [Mark]

The marks (things like whether it is emphasized or part of a link) associated with this node.

text: ?string

For text nodes, this contains the node's text content.

nodeSize: number

The size of this node, as defined by the integer-based indexing scheme. For text nodes, this is the amount of characters. For other leaf nodes, it is one. And for non-leaf nodes, it is the size of the content plus two (the start and end token).

childCount: number

The number of children that the node has.

child(index: number) → Node

Get the child node at the given index. Raises an error when the index is out of range.

maybeChild(index: number) → ?Node

Get the child node at the given index, if it exists.

forEach(f: fn(node: Node, offset: number, index: number))

Call f for every child node, passing the node, its offset into this parent node, and its index.

nodesBetween(from: ?number, to: ?number, f: fn(node: Node, pos: number, parent: Node, index: number))

Iterate over all nodes between the given two positions, calling the callback with the node, its position, its parent node, and its index in that node.

descendants(f: fn(node: Node, pos: number, parent: Node))

Call the given callback for every descendant node.

textContent: string

Concatenates all the text nodes found in this fragment and its children.

textBetween(from: number, to: number, blockSeparator: ?string, leafText: ?string) → string

Get all text between positions from and to. When blockSeparator is given, it will be inserted whenever a new block node is started. When leafText is given, it'll be inserted for every non-text leaf node encountered.

firstChild: ?Node

Returns this node's first child, or null if there are no children.

lastChild: ?Node

Returns this node's last child, or null if there are no children.

eq(other: Node) → bool

Test whether two nodes represent the same content.

sameMarkup(other: Node) → bool

Compare the markup (type, attributes, and marks) of this node to those of another. Returns true if both have the same markup.

hasMarkup(type: NodeType, attrs: ?Object, marks: ?[Mark]) → bool

Check whether this node's markup correspond to the given type, attributes, and marks.

copy(content: ?Fragment = null) → Node

Create a new node with the same markup as this node, containing the given content (or empty, if no content is given).

mark(marks: [Mark]) → Node

Create a copy of this node, with the given set of marks instead of the node's own marks.

cut(from: number, to: ?number) → Node

Create a copy of this node with only the content between the given offsets. If to is not given, it defaults to the end of the node.

slice(from: number, to: ?number = this.content.size) → Slice

Cut out the part of the document between the given positions, and return it as a Slice object.

replace(from: number, to: number, slice: Slice) → Node

Replace the part of the document between the given positions with the given slice. The slice must 'fit', meaning its open sides must be able to connect to the surrounding content, and its content nodes must be valid children for the node they are placed into. If any of this is violated, an error of type ReplaceError is thrown.

nodeAt(pos: number) → ?Node

Find the node after the given position.

childAfter(pos: number) → {node: ?Node, index: number, offset: number}

Find the (direct) child node after the given offset, if any, and return it along with its index and offset relative to this node.

childBefore(pos: number) → {node: ?Node, index: number, offset: number}

Find the (direct) child node before the given offset, if any, and return it along with its index and offset relative to this node.

resolve(pos: number) → ResolvedPos

Resolve the given position in the document, returning an object describing its path through the document.

marksAt(pos: number, useAfter: ?bool) → [Mark]

Get the marks at the given position factoring in the surrounding marks' inclusiveRight property. If the position is at the start of a non-empty node, or useAfter is true, the marks of the node after it are returned.

rangeHasMark(from: ?number, to: ?number, type: MarkType) → bool

Test whether a mark of the given type occurs in this document between the two given positions.

isBlock: bool

True when this is a block (non-inline node)

isTextblock: bool

True when this is a textblock node, a block node with inline content.

isInline: bool

True when this is an inline node (a text node or a node that can appear among text).

isText: bool

True when this is a text node.

isLeaf: bool

True when this is a leaf node.

toString() → string

Return a string representation of this node for debugging purposes.

contentMatchAt(index: number) → ContentMatch

Get the content match in this node at the given index.

canReplace(from: number, to: number, replacement: ?Fragment, start: ?number, end: ?number) → bool

Test whether replacing the range from to to (by index) with the given replacement fragment (which defaults to the empty fragment) would leave the node's content valid. You can optionally pass start and end indices into the replacement fragment.

canReplaceWith(from: number, to: number, type: NodeType, attrs: ?[Mark]) → bool

Test whether replacing the range from to to (by index) with a node of the given type with the given attributes and marks would be valid.

canAppend(other: Node) → bool

Test whether the given node's content could be appended to this node. If that node is empty, this will only return true if there is at least one node type that can appear in both nodes (to avoid merging completely incompatible nodes).

toJSON() → Object

Return a JSON-serializeable representation of this node.

static fromJSON(schema: Schema, json: Object) → Node

Deserialize a node from its JSON representation.

class Fragment

Fragment is the type used to represent a node's collection of child nodes.

Fragments are persistent data structures. That means you should not mutate them or their content, but create new instances whenever needed. The API tries to make this easy.

append(other: Fragment) → Fragment

Create a new fragment containing the content of this fragment and other.

cut(from: number, to: ?number) → Fragment

Cut out the sub-fragment between the two given positions.

replaceChild(index: number, node: Node) → Fragment

Create a new fragment in which the node at the given index is replaced by the given node.

eq(other: Fragment) → bool

Compare this fragment to another one.

firstChild: ?Node

The first child of the fragment, or null if it is empty.

lastChild: ?Node

The last child of the fragment, or null if it is empty.

childCount: number

The number of child nodes in this fragment.

child(index: number) → Node

Get the child node at the given index. Raise an error when the index is out of range.

offsetAt(index: number) → number

Get the offset at (size of children before) the given index.

maybeChild(index: number) → ?Node

Get the child node at the given index, if it exists.

forEach(f: fn(node: Node, offset: number, index: number))

Call f for every child node, passing the node, its offset into this parent node, and its index.

findDiffStart(other: Fragment) → ?number

Find the first position at which this fragment and another fragment differ, or null if they are the same.

findDiffEnd(other: Node) → ?{a: number, b: number}

Find the first position, searching from the end, at which this fragment and the given fragment differ, or null if they are the same. Since this position will not be the same in both nodes, an object with two separate positions is returned.

toString() → string

Return a debugging string that describes this fragment.

toJSON() → ?Object

Create a JSON-serializeable representation of this fragment.

static fromJSON(schema: Schema, value: ?Object) → Fragment

Deserialize a fragment from its JSON representation.

static fromArray(array: [Node]) → Fragment

Build a fragment from an array of nodes. Ensures that adjacent text nodes with the same style are joined together.

static from(nodes: ?Fragment | Node | [Node]) → Fragment

Create a fragment from something that can be interpreted as a set of nodes. For null, it returns the empty fragment. For a fragment, the fragment itself. For a node or array of nodes, a fragment containing those nodes.

static empty: Fragment

An empty fragment. Intended to be reused whenever a node doesn't contain anything (rather than allocating a new empty fragment for each leaf node).

class Mark

A mark is a piece of information that can be attached to a node, such as it being emphasized, in code font, or a link. It has a type and optionally a set of attributes that provide further information (such as the target of the link). Marks are created through a Schema, which controls which types exist and which attributes they have.

type: MarkType

The type of this mark.

attrs: Object

The attributes associated with this mark.

addToSet(set: [Mark]) → [Mark]

Given a set of marks, create a new set which contains this one as well, in the right position. If this mark is already in the set, the set itself is returned. If a mark of this type with different attributes is already in the set, a set in which it is replaced by this one is returned.

removeFromSet(set: [Mark]) → [Mark]

Remove this mark from the given set, returning a new set. If this mark is not in the set, the set itself is returned.

isInSet(set: [Mark]) → bool

Test whether this mark is in the given set of marks.

eq(other: Mark) → bool

Test whether this mark has the same type and attributes as another mark.

toJSON() → Object

Convert this mark to a JSON-serializeable representation.

static fromJSON(schema: Schema, json: Object) → Mark
static sameSet(a: [Mark], b: [Mark]) → bool

Test whether two sets of marks are identical.

static setFrom(marks: ?Mark | [Mark]) → [Mark]

Create a properly sorted mark set from null, a single mark, or an unsorted array of marks.

static none: [Mark]

The empty set of marks.

class Slice

A slice represents a piece cut out of a larger document. It stores not only a fragment, but also the depth up to which nodes on both side are 'open' / cut through.

new Slice(content: Fragment, openLeft: number, openRight: number)
content: Fragment

The slice's content nodes.

openLeft: number

The open depth at the start.

openRight: number

The open depth at the end.

size: number

The size this slice would add when inserted into a document.

toJSON() → ?Object

Convert a slice to a JSON-serializable representation.

static fromJSON(schema: Schema, json: ?Object) → Slice

Deserialize a slice from its JSON representation.

static empty: Slice

The empty slice.

class ReplaceError extends Error

Error type raised by Node.replace when given an invalid replacement.

Resolved Positions

Positions in a document can be represented as integer offsets. But you'll often want to use a more convenient representation.

class ResolvedPos

You'll often have to 'resolve' a position to get the context you need. Objects of this class represent such a resolved position, providing various pieces of context information and helper methods.

Throughout this interface, methods that take an optional depth parameter will interpret undefined as this.depth and negative numbers as this.depth + value.

pos: number

The position that was resolved.

depth: number

The number of levels the parent node is from the root. If this position points directly into the root, it is 0. If it points into a top-level paragraph, 1, and so on.

parentOffset: number

The offset this position has into its parent node.

parent: Node

The parent node that the position points into. Note that even if a position points into a text node, that node is not considered the parent—text nodes are 'flat' in this model.

node(depth: ?number) → Node

The ancestor node at the given level. p.node(p.depth) is the same as p.parent.

index(depth: ?number) → number

The index into the ancestor at the given level. If this points at the 3rd node in the 2nd paragraph on the top level, for example, p.index(0) is 2 and p.index(1) is 3.

indexAfter(depth: ?number) → number

The index pointing after this position into the ancestor at the given level.

start(depth: ?number) → number

The (absolute) position at the start of the node at the given level.

end(depth: ?number) → number

The (absolute) position at the end of the node at the given level.

before(depth: ?number) → number

The (absolute) position directly before the node at the given level, or, when level is this.level + 1, the original position.

after(depth: ?number) → number

The (absolute) position directly after the node at the given level, or, when level is this.level + 1, the original position.

atNodeBoundary: bool

True if this position points at a node boundary, false if it points into a text node.

nodeAfter: ?Node

Get the node directly after the position, if any. If the position points into a text node, only the part of that node after the position is returned.

nodeBefore: ?Node

Get the node directly before the position, if any. If the position points into a text node, only the part of that node before the position is returned.

sameDepth(other: ResolvedPos) → number

The depth up to which this position and the other share the same parent nodes.

blockRange(other: ?ResolvedPos = this, pred: ?fn(Node) → bool) → ?NodeRange

Returns a range based on the place where this position and the given position diverge around block content. If both point into the same textblock, for example, a range around that textblock will be returned. If they point into different blocks, the range around those blocks or their ancestors in their common ancestor is returned. You can pass in an optional predicate that will be called with a parent node to see if a range into that parent is acceptable.

sameParent(other: ResolvedPos) → bool

Query whether the given position shares the same parent node.

class NodeRange

Represents a flat range of content.

$from: ResolvedPos

A resolved position along the start of the content. May have a depth greater than this object's depth property, since these are the positions that were used to compute the range, not re-resolved positions directly at its boundaries.

$to: ResolvedPos

A position along the end of the content. See caveat for $from.

depth: number

The depth of the node that this range points into.

start: number

The position at the start of the range.

end: number

The position at the end of the range.

parent: Node

The parent node that the range points into.

startIndex: number

The start index of the range in the parent node.

endIndex: number

The end index of the range in the parent node.

Document Schema

The schema to which a document must conform is another data structure. It describes the nodes and marks that may appear in a document, and the places at which they may appear.

class Schema

A document schema.

new Schema(spec: SchemaSpec)

Construct a schema from a specification.

nodeSpec: OrderedMap<NodeSpec>

The node specs that the schema is based on.

markSpec: OrderedMap<constructor<MarkType>>

The mark spec that the schema is based on.

nodes: Object<NodeType>

An object mapping the schema's node names to node type objects.

marks: Object<MarkType>

A map from mark names to mark type objects.

cached: Object

An object for storing whatever values modules may want to compute and cache per schema. (If you want to store something in it, try to use property names unlikely to clash.)

node(type: string | NodeType, attrs: ?Object, content: ?Fragment | Node | [Node], marks: ?[Mark]) → Node

Create a node in this schema. The type may be a string or a NodeType instance. Attributes will be extended with defaults, content may be a Fragment, null, a Node, or an array of nodes.

text(text: string, marks: ?[Mark]) → Node

Create a text node in the schema. Empty text nodes are not allowed.

mark(type: string | MarkType, attrs: ?Object) → Mark

Create a mark with the given type and attributes.

nodeFromJSON(json: Object) → Node

Deserialize a node from its JSON representation. This method is bound.

markFromJSON(json: Object) → Mark

Deserialize a mark from its JSON representation. This method is bound.

interface SchemaSpec

An object describing a schema, as passed to the Schema constructor.

nodes: Object<NodeSpec> | OrderedMap<NodeSpec>

The node types in this schema. Maps names to NodeSpec objects describing the node to be associated with that name. Their order is significant

marks: ?Object<MarkSpec> | OrderedMap<MarkSpec>

The mark types that exist in this schema.

interface NodeSpec

content: ?string

The content expression for this node, as described in the schema guide. When not given, the node does not allow any content.

group: ?string

The group or space-separated groups to which this node belongs, as referred to in the content expressions for the schema.

inline: ?bool

Should be set to a truthy value for inline nodes. (Implied for text nodes.)

attrs: ?Object<AttributeSpec>

The attributes that nodes of this type get.

selectable: ?bool

Controls whether nodes of this type can be selected (as a node selection). Defaults to true for non-text nodes.

draggable: ?bool

Determines whether nodes of this type can be dragged. Enabling it causes ProseMirror to set a draggable attribute on its DOM representation, and to put its HTML serialization into the drag event's data transfer when dragged. Defaults to false.

code: ?bool

Can be used to indicate that this node contains code, which causes some commands to behave differently.

toDOM(Node) → DOMOutputSpec

Defines the default way a node of this type should be serialized to DOM/HTML (as used by DOMSerializer.fromSchema. Should return an array structure that describes the resulting DOM structure, with an optional number zero (“hole”) in it to indicate where the node's content should be inserted.

parseDOM: ?[ParseRule]

Associates DOM parser information with this node, which an be used by DOMParser.fromSchema to automatically derive a parser. The node field in the rules is implied (the name of this node will be filled in automatically). If you supply your own parser, you do not need to also specify parsing rules in your schema.

interface MarkSpec

attrs: ?Object<AttributeSpec>

The attributes that marks of this type get.

inclusiveRight: ?bool

Whether this mark should be active when the cursor is positioned at the end of the mark. Defaults to true.

toDOM(mark: Mark) → DOMOutputSpec

Defines the default way marks of this type should be serialized to DOM/HTML.

parseDOM: ?[ParseRule]

Associates DOM parser information with this mark (see the corresponding node spec field. The mark field in the rules is implied.

interface AttributeSpec

Used to define attributes. Attributes that have no default or compute property must be provided whenever a node or mark of a type that has them is created.

The following fields are supported:

default: ?any

The default value for this attribute, to choose when no explicit value is provided.

compute() → any

A function that computes a default value for the attribute.

class NodeType

Node types are objects allocated once per Schema and used to tag Node instances with a type. They contain information about the node type, such as its name and what kind of node it represents.

name: string

The name the node type has in this schema.

schema: Schema

A link back to the Schema the node type belongs to.

spec: NodeSpec

The spec that this type is based on

isBlock: bool

True if this is a block type

isText: bool

True if this is the text node type.

isInline: bool

True if this is an inline type.

isTextblock: bool

True if this is a textblock type, a block that contains inline content.

isLeaf: bool

True for node types that allow no content.

create(attrs: ?Object, content: ?Fragment | Node | [Node], marks: ?[Mark]) → Node

Create a Node of this type. The given attributes are checked and defaulted (you can pass null to use the type's defaults entirely, if no required attributes exist). content may be a Fragment, a node, an array of nodes, or null. Similarly marks may be null to default to the empty set of marks.

createChecked(attrs: ?Object, content: ?Fragment | Node | [Node], marks: ?[Mark]) → Node

Like create, but check the given content against the node type's content restrictions, and throw an error if it doesn't match.

createAndFill(attrs: ?Object, content: ?Fragment | Node | [Node], marks: ?[Mark]) → ?Node

Like create, but see if it is necessary to add nodes to the start or end of the given fragment to make it fit the node. If no fitting wrapping can be found, return null. Note that, due to the fact that required nodes can always be created, this will always succeed if you pass null or Fragment.empty as content.

validContent(content: Fragment, attrs: ?Object) → bool

Returns true if the given fragment is valid content for this node type with the given attributes.

class MarkType

Like nodes, marks (which are associated with nodes to signify things like emphasis or being part of a link) are tagged with type objects, which are instantiated once per Schema.

name: string

The name of the mark type.

schema: Schema

The schema that this mark type instance is part of.

spec: MarkSpec

The spec on which the type is based.

create(attrs: ?Object) → Mark

Create a mark of this type. attrs may be null or an object containing only some of the mark's attributes. The others, if they have defaults, will be added.

removeFromSet(set: [Mark]) → [Mark]

When there is a mark of this type in the given set, a new set without it is returned. Otherwise, the input set is returned.

isInSet(set: [Mark]) → ?Mark

Tests whether there is a mark of this type in the given set.

class ContentMatch

Represents a partial match of a node type's content expression, and can be used to find out whether further content matches here, and whether a given position is a valid end of the parent node.

matchNode(node: Node) → ?ContentMatch

Match a node, returning a new match after the node if successful.

matchType(type: NodeType, attrs: ?Object, marks: ?[Mark] = Mark.none) → ?ContentMatch

Match a node type and marks, returning an match after that node if successful.

matchFragment(fragment: Fragment, from: ?number = 0, to: ?number = fragment.childCount) → ?ContentMatch | bool

Try to match a fragment. Returns a new match when successful, null when it ran into a required element it couldn't fit, and false if it reached the end of the expression without matching all nodes.

matchToEnd(fragment: Fragment, start: ?number, end: ?number) → bool

Returns true only if the fragment matches here, and reaches all the way to the end of the content expression.

validEnd() → bool

Returns true if this position represents a valid end of the expression (no required content follows after it).

fillBefore(after: Fragment, toEnd: bool, startIndex: ?number) → ?Fragment

Try to match the given fragment, and if that fails, see if it can be made to match by inserting nodes in front of it. When successful, return a fragment of inserted nodes (which may be empty if nothing had to be inserted). When toEnd is true, only return a fragment if the resulting match goes to the end of the content expression.

allowsMark(markType: MarkType) → bool

Check whether a node with the given mark type is allowed after this position.

findWrapping(target: NodeType, targetAttrs: ?Object) → ?[{type: NodeType, attrs: Object}]

Find a set of wrapping node types that would allow a node of type target with attributes targetAttrs to appear at this position. The result may be empty (when it fits directly) and will be null when no such wrapping exists.

class OrderedMap

Persistent data structure representing an ordered mapping from strings to values, with some convenient update methods.

get(key: string) → ?any

Retrieve the value stored under key, or return undefined when no such key exists.

update(key: string, value: any, newKey: ?string) → OrderedMap

Create a new map by replacing the value of key with a new value, or adding a binding to the end of the map. If newKey is given, the key of the binding will be replaced with that key.

remove(key: string) → OrderedMap

Return a map with the given key removed, if it existed.

addToStart(key: string, value: any) → OrderedMap

Add a new key to the start of the map.

addToEnd(key: string, value: any) → OrderedMap

Add a new key to the end of the map.

addBefore(place: string, key: string, value: any) → OrderedMap

Add a key after the given key. If place is not found, the new key is added to the end.

forEach(f: fn(key: string, value: any))

Call the given function for each key/value pair in the map, in order.

prepend(map: Object | OrderedMap) → OrderedMap

Create a new map by prepending the keys in this map that don't appear in map before the keys in map.

append(map: Object | OrderedMap) → OrderedMap

Create a new map by appending the keys in this map that don't appear in map after the keys in map.

subtract(map: Object | OrderedMap) → OrderedMap

Create a map containing all the keys in this map that don't appear in map.

size: number

The amount of keys in this map.

static from(value: ?Object | OrderedMap) → OrderedMap

Return a map with the given content. If null, create an empty map. If given an ordered map, return that map itself. If given an object, create a map from the object's properties.

DOM Representation

Because representing a document as a tree of DOM nodes is central to the way ProseMirror operates, DOM parsing and serializing is integrated with the model.

(But note that you do not need to have a DOM implementation loaded to load this module.)

class DOMParser

A DOM parser represents a strategy for parsing DOM content into a ProseMirror document conforming to a given schema. Its behavior is defined by an array of rules.

new DOMParser(schema: Schema, rules: [ParseRule])

Create a parser that targets the given schema, using the given parsing rules.

schema: Schema
rules: [ParseRule]
parse(dom: dom.Node, options: ?Object = {}) → Node

Parse a document from the content of a DOM node. To provide an explicit parent document (for example, when not in a browser window environment, where we simply use the global document), pass it as the document property of options.

static schemaRules(schema: Schema) → [ParseRule]

Extract the parse rules listed in a schema's node specs.

static fromSchema(schema: Schema) → DOMParser

Construct a DOM parser using the parsing rules listed in a schema's node specs.

interface ParseRule

A value that describes how to parse a given DOM node or inline style as a ProseMirror node or mark.

tag: ?string

A CSS selector describing the kind of DOM elements to match. A single rule should have either a tag or a style property.

style: ?string

A CSS property name to match. When given, this rule matches inline styles that list that property.

node: ?string

The name of the node type to create when this rule matches. Only valid for rules with a tag property, not for style rules. Each rule should have one of a node, mark, or ignore property (except when it appears in a node or mark spec, in which case the node or mark property will be derived from its position).

mark: ?string

The name of the mark type to wrap the matched content in.

ignore: ?bool

When true, ignore content that matches this rule.

attrs: ?Object

Attributes for the node or mark created by this rule. When getAttrs is provided, it takes precedence.

getAttrs(dom.Node | string) → ?bool | Object

A function used to compute the attributes for the node or mark created by this rule. Can also be used to describe further conditions the DOM element or style must match. When it returns false, the rule won't match. When it returns null or undefined, that is interpreted as an empty/default set of attributes.

Called with a DOM Element for tag rules, and with a string (the style's value) for style rules.

contentElement: ?string

For tag rules that produce non-leaf nodes or marks, by default the content of the DOM element is parsed as content of the mark or node. If the child nodes are in a descendent node, this may be a CSS selector string that the parser must use to find the actual content element.

preserveWhitespace: ?bool

Controls whether whitespace should be preserved when parsing the content inside the matched element.

class DOMSerializer

A DOM serializer knows how to convert ProseMirror nodes and marks of various types to DOM nodes.

new DOMSerializer(nodes: Object<fn(node: Node) → DOMOutputSpec>, marks: Object<fn(mark: Mark) → DOMOutputSpec>)

Create a serializer. nodes should map node names to functions that take a node and return a description of the corresponding DOM. marks does the same for mark names.

serializeFragment(fragment: Fragment, options: ?Object = {}) → dom.DocumentFragment

Serialize the content of this fragment to a DOM fragment. When not in the browser, the document option, containing a DOM document, should be passed so that the serialize can create nodes.

serializeNode(node: Node, options: ?Object = {}) → dom.Node

Serialize this node to a DOM node. This can be useful when you need to serialize a part of a document, as opposed to the whole document. To serialize a whole document, use serializeFragment on its content.

static fromSchema(schema: Schema) → DOMSerializer

Build a serializer using the toDOM properties in a schema's node and mark specs.

static nodesFromSchema(schema: Schema) → Object<fn(node: Node) → DOMOutputSpec>

Gather the serializers in a schema's node specs into an object. This can be useful as a base to build a custom serializer from.

static marksFromSchema(schema: Schema) → Object<fn(mark: Mark) → DOMOutputSpec>

Gather the serializers in a schema's mark specs into an object.

interface DOMOutputSpec

A description of a DOM structure. Can be either a string, which is interpreted as a text node, a DOM node, which is interpreted as itself, or an array.

An array describes a DOM element. The first element in the array should be a string, and is the name of the DOM element. If the second element is a non-Array, non-DOM node object, it is interpreted as an object providing the DOM element's attributes. Any elements after that (including the 2nd if it's not an attribute object) are interpreted as children of the DOM elements, and must either be valid DOMOutputSpec values, or the number zero.

The number zero (pronounced “hole”) is used to indicate the place where a ProseMirror node's content should be inserted.

module transform

This module defines a way to transform documents. You can read more about transformations in this guide.

Steps

Transforming happens in Steps, which are atomic, well-defined modifications to a document. Applying a step produces a new document.

Each step provides a change map that maps positions in the old document to position in the transformed document. Steps can be inverted to create a step that undoes their effect, and chained together in a convenience object called a Transform.

class Step

A step object wraps an atomic operation. It generally applies only to the document it was created for, since the positions associated with it will only make sense for that document.

New steps are defined by creating classes that extend Step, overriding the apply, invert, map, getMap and fromJSON methods, and registering your class with a unique JSON-serialization identifier using Step.jsonID.

apply(doc: Node) → StepResult

Applies this step to the given document, returning a result object that either indicates failure, if the step can not be applied to this document, or indicates success by containing a transformed document.

getMap() → StepMap

Get the step map that represents the changes made by this step.

invert(doc: Node) → Step

Create an inverted version of this step. Needs the document as it was before the step as argument.

map(mapping: Mappable) → ?Step

Map this step through a mappable thing, returning either a version of that step with its positions adjusted, or null if the step was entirely deleted by the mapping.

merge(other: Step) → ?Step

Try to merge this step with another one, to be applied directly after it. Returns the merged step when possible, null if the steps can't be merged.

toJSON() → Object

Create a JSON-serializeable representation of this step. By default, it'll create an object with the step's JSON id, and each of the steps's own properties, automatically calling toJSON on the property values that have such a method.

static fromJSON(schema: Schema, json: Object) → Step

Deserialize a step from its JSON representation. Will call through to the step class' own implementation of this method.

static jsonID(id: string, stepClass: constructor<Step>)

To be able to serialize steps to JSON, each step needs a string ID to attach to its JSON representation. Use this method to register an ID for your step classes. Try to pick something that's unlikely to clash with steps from other modules.

class StepResult

The result of applying a step. Contains either a new document or a failure value.

doc: ?Node

The transformed document.

failed: ?string

Text providing information about a failed step.

static ok(doc: Node) → StepResult

Create a successful step result.

static fail(message: string) → StepResult

Create a failed step result.

static fromReplace(doc: Node, from: number, to: number, slice: Slice) → StepResult

Call Node.replace with the given arguments. Create a successful result if it succeeds, and a failed one if it throws a ReplaceError.

class ReplaceStep extends Step

Replace a part of the document with a slice of new content.

new ReplaceStep(from: number, to: number, slice: Slice, structure: bool)

The given slice should fit the 'gap' between from and to—the depths must line up, and the surrounding nodes must be able to be joined with the open sides of the slice. When structure is true, the step will fail if the content between from and to is not just a sequence of closing and then opening tokens (this is to guard against rebased replace steps overwriting something they weren't supposed to).

class ReplaceAroundStep extends Step

Replace a part of the document with a slice of content, but preserve a range of the replaced content by moving it into the slice.

new ReplaceAroundStep(from: number, to: number, gapFrom: number, gapTo: number, slice: Slice, insert: number, structure: bool)

Create a replace-wrap step with the given range and gap. insert should be the point in the slice into which the gap should be moved. structure has the same meaning as it has in the ReplaceStep class.

class AddMarkStep extends Step

Add a mark to all inline content between two positions.

new AddMarkStep(from: number, to: number, mark: Mark)

class RemoveMarkStep extends Step

Remove a mark from all inline content between two positions.

new RemoveMarkStep(from: number, to: number, mark: Mark)

Position Mapping

Mapping positions from one document to another by running through the replacements produced by steps is a fundamental operation in ProseMirror.

interface Mappable

There are several things that positions can be mapped through. We'll denote those as 'mappable'.

map(pos: number, bias: ?number) → number

Map a position through this object. When given, bias (should be -1 or 1, defaults to 1) determines in which direction to move when a chunk of content is inserted at or around the mapped position.

mapResult(pos: number, bias: ?number) → MapResult

Map a position, and return an object containing additional information about the mapping. The result's deleted field tells you whether the position was deleted (completely enclosed in a replaced range) during the mapping.

class MapResult

An object representing a mapped position with extra information.

pos: number

The mapped version of the position.

deleted: bool

Tells you whether the position was deleted, that is, whether the step removed its surroundings from the document.

class StepMap

A map describing the deletions and insertions made by a step, which can be used to find the correspondence between positions in the pre-step version of a document and the same position in the post-step version. This class implements Mappable.

new StepMap(ranges: [number])

Create a position map. The modifications to the document are represented as an array of numbers, in which each group of three represents a modified chunk as [start, oldSize, newSize].

mapResult(pos: number, bias: ?number) → MapResult

Map the given position through this map. The bias parameter can be used to control what happens when the transform inserted content at (or around) this position—if bias is negative, the a position before the inserted content will be returned, if it is positive, a position after the insertion is returned.

map(pos: number, bias: ?number) → number

Map the given position through this map, returning only the mapped position.

forEach(f: fn(oldStart: number, oldEnd: number, newStart: number, newEnd: number))

Calls the given function on each of the changed ranges denoted by this map.

invert() → StepMap

Create an inverted version of this map. The result can be used to map positions in the post-step document to the pre-step document.

class Mapping

A mapping represents a pipeline of zero or more step maps. It has special provisions for losslessly handling mapping positions through a series of steps in which some steps are inverted versions of earlier steps. (This comes up when ‘rebasing’ steps for collaboration or history management.) This class implements Mappable.

new Mapping(maps: ?[StepMap])

Create a new remapping with the given position maps.

maps: [StepMap]

The step maps in this mapping.

from: number

The starting position in the maps array, used when map or mapResult is called.

to: number

The end positions in the maps array.

slice(from: ?number = 0, to: ?number = this.maps.length) → Mapping

Create a remapping that maps only through a part of this one.

appendMap(map: StepMap, mirrors: ?number)

Add a step map to the end of this remapping. If mirrors is given, it should be the index of the step map that is the mirror image of this one.

appendMapping(mapping: Mapping)

Add all the step maps in a given mapping to this one (preserving mirroring information).

map(pos: number, bias: ?number) → number

Map a position through this remapping.

mapResult(pos: number, bias: ?number) → MapResult

Map a position through this remapping, returning a mapping result.

Transform Helpers

Because you often need to collect a number of steps together to effect a composite change, ProseMirror provides an abstraction to make this easy. A value of this class is also the payload in the transform action.

class Transform

Abstraction to build up and track such an array of steps.

The high-level transforming methods return the Transform object itself, so that they can be chained.

new Transform(doc: Node)

Create a transformation that starts with the given document.

addMark(from: number, to: number, mark: Mark) → Transform

Add the given mark to the inline content between from and to.

removeMark(from: number, to: number, mark: ?Mark | MarkType = null) → Transform

Remove the given mark, or all marks of the given type, from inline nodes between from and to.

clearMarkup(from: number, to: number) → Transform

Remove all marks and non-text inline nodes from the given range.

delete(from: number, to: number) → Transform

Delete the content between the given positions.

replace(from: number, to: ?number = from, slice: ?Slice = Slice.empty) → Transform

Replace the part of the document between from and to with the part of the source between start and end.

replaceWith(from: number, to: number, content: Fragment | Node | [Node]) → Transform

Replace the given range with the given content, which may be a fragment, node, or array of nodes.

insert(pos: number, content: Fragment | Node | [Node]) → Transform

Insert the given content at the given position.

lift(range: NodeRange, target: number) → Transform

Split the content in the given range off from its parent, if there is sibling content before or after it, and move it up the tree to the depth specified by target. You'll probably want to use liftTarget to compute target, in order to be sure the lift is valid.

wrap(range: NodeRange, wrappers: [{type: NodeType, attrs: ?Object}]) → Transform

Wrap the given range in the given set of wrappers. The wrappers are assumed to be valid in this position, and should probably be computed with findWrapping.

setBlockType(from: number, to: ?number = from, type: NodeType, attrs: ?Object) → Transform

Set the type of all textblocks (partly) between from and to to the given node type with the given attributes.

setNodeType(pos: number, type: ?NodeType, attrs: ?Object) → Transform

Change the type and attributes of the node after pos.

split(pos: number, depth: ?number = 1, typesAfter: ?[?{type: NodeType, attrs: ?Object}]) → Transform

Split the node at the given position, and optionally, if depth is greater than one, any number of nodes above that. By default, the parts split off will inherit the node type of the original node. This can be changed by passing an array of types and attributes to use after the split.

join(pos: number, depth: ?number = 1, ?bool) → Transform

Join the blocks around the given position. If depth is 2, their last and first siblings are also joined, and so on.

doc: Node

The current document (the result of applying the steps in the transform).

steps: [Step]

The steps in this transform.

docs: [Node]

The documents before each of the steps.

mapping: Mapping

A mapping with the maps for each of the steps in this transform.

before: Node

The document at the start of the transformation.

step(step: Step) → Transform

Apply a new step in this transformation, saving the result. Throws an error when the step fails.

maybeStep(step: Step) → StepResult

Try to apply a step in this transformation, ignoring it if it fails. Returns the step result.

The following helper functions can be useful when creating transformations or determining whether they are even possible.

replaceStep(doc: Node, from: number, to: ?number = from, slice: ?Slice = Slice.empty) → ?Step

"Fit" a slice into a given position in the document, producing a step that inserts it.

liftTarget(range: NodeRange) → ?number

Try to find a target depth to which the content in the given range can be lifted.

findWrapping(range: NodeRange, nodeType: NodeType, attrs: ?Object) → ?[{type: NodeType, attrs: ?Object}]

Try to find a valid way to wrap the content in the given range in a node of the given type. May introduce extra nodes around and inside the wrapper node, if necessary. Returns null if no valid wrapping could be found.

canSplit(doc: Node, pos: number, depth: ?[?{type: NodeType, attrs: ?Object}] = 1) → bool

Check whether splitting at the given position is allowed.

canJoin(doc: Node, pos: number) → bool

Test whether the blocks before and after a given position can be joined.

joinPoint(doc: Node, pos: number, dir: ?number = -1) → ?number

Find an ancestor of the given position that can be joined to the block before (or after if dir is positive). Returns the joinable point, if any.

insertPoint(doc: Node, pos: number, nodeType: NodeType, attrs: ?Object) → ?number

Try to find a point where a node of the given type can be inserted near pos, by searching up the node hierarchy when pos itself isn't a valid place but is at the start or end of a node. Return null if no position was found.

module commands

This module exports a number of ‘commands‘, which are building block functions that encapsulate an editing action. A command function takes an editor state and optionally an onAction function that it can use to take an action. It should return a boolean that indicates whether it could perform any action. When no onAction callback is passed, the command should do a 'dry run', determining whether it is applicable, but not actually doing anything.

These are mostly used to bind keys to, and to define menu items.

chainCommands(...commands: [fn(EditorState, ?fn(action: Action)) → bool]) → fn(EditorState, ?fn(action: Action)) → bool

Combine a number of command functions into a single function (which calls them one by one until one returns true).

deleteSelection(state: EditorState, onAction: ?fn(action: Action)) → bool

Delete the selection, if there is one.

joinBackward(state: EditorState, onAction: ?fn(action: Action)) → bool

If the selection is empty and at the start of a textblock, move that block closer to the block before it, by lifting it out of its parent or, if it has no parent it doesn't share with the node before it, moving it into a parent of that node, or joining it with that.

joinForward(state: EditorState, onAction: ?fn(action: Action)) → bool

If the selection is empty and the cursor is at the end of a textblock, move the node after it closer to the node with the cursor (lifting it out of parents that aren't shared, moving it into parents of the cursor block, or joining the two when they are siblings).

deleteCharBefore(state: EditorState, onAction: ?fn(action: Action)) → bool

Delete the character before the cursor, if the selection is empty and the cursor isn't at the start of a textblock.

deleteWordBefore(state: EditorState, onAction: ?fn(action: Action)) → bool

Delete the word before the cursor, if the selection is empty and the cursor isn't at the start of a textblock.

deleteCharAfter(state: EditorState, onAction: ?fn(action: Action)) → bool

Delete the character after the cursor, if the selection is empty and the cursor isn't at the end of its textblock.

deleteWordAfter(state: EditorState, onAction: ?fn(action: Action)) → bool

Delete the word after the cursor, if the selection is empty and the cursor isn't at the end of a textblock.

joinUp(state: EditorState, onAction: ?fn(action: Action)) → bool

Join the selected block or, if there is a text selection, the closest ancestor block of the selection that can be joined, with the sibling above it.

joinDown(state: EditorState, onAction: ?fn(action: Action)) → bool

Join the selected block, or the closest ancestor of the selection that can be joined, with the sibling after it.

lift(state: EditorState, onAction: ?fn(action: Action)) → bool

Lift the selected block, or the closest ancestor block of the selection that can be lifted, out of its parent node.

newlineInCode(state: EditorState, onAction: ?fn(action: Action)) → bool

If the selection is in a node whose type has a truthy code property in its spec, replace the selection with a newline character.

createParagraphNear(state: EditorState, onAction: ?fn(action: Action)) → bool

If a block node is selected, create an empty paragraph before (if it is its parent's first child) or after it.

liftEmptyBlock(state: EditorState, onAction: ?fn(action: Action)) → bool

If the cursor is in an empty textblock that can be lifted, lift the block.

splitBlock(state: EditorState, onAction: ?fn(action: Action)) → bool

Split the parent block of the selection. If the selection is a text selection, also delete its content.

selectParentNode(state: EditorState, onAction: ?fn(action: Action)) → bool

Move the selection to the node wrapping the current selection, if any. (Will not select the document node.)

wrapIn(nodeType: NodeType, attrs: ?Object) → fn(state: EditorState, onAction: ?fn(action: Action)) → bool

Wrap the selection in a node of the given type with the given attributes.

setBlockType(nodeType: NodeType, attrs: ?Object) → fn(state: EditorState, onAction: ?fn(action: Action)) → bool

Returns a command that tries to set the textblock around the selection to the given node type with the given attributes.

toggleMark(markType: MarkType, attrs: ?Object) → fn(state: EditorState, onAction: ?fn(action: Action)) → bool

Create a command function that toggles the given mark with the given attributes. Will return false when the current selection doesn't support that mark. This will remove the mark if any marks of that type exist in the selection, or add it otherwise. If the selection is empty, this applies to the stored marks instead of a range of the document.

baseKeymap: Object

A basic keymap containing bindings not specific to any schema. Binds the following keys (when multiple commands are listed, they are chained with chainCommands:

  • Enter to newlineInCode, createParagraphNear, liftEmptyBlock, splitBlock
  • Backspace to deleteSelection, joinBackward, deleteCharBefore
  • Mod-Backspace to deleteSelection, joinBackward, deleteWordBefore
  • Delete to deleteSelection, joinForward, deleteCharAfter
  • Mod-Delete to deleteSelection, joinForward, deleteWordAfter
  • Alt-ArrowUp to joinUp
  • Alt-ArrowDown to joinDown
  • Mod-BracketLeft to lift
  • Escape to selectParentNode

module history

An implementation of undo/redo history for ProseMirror.

history: Plugin

A plugin that enables the undo history for an editor. Supports these configuration fields:

depth: number
The amount of history events that are collected before the oldest events are discarded. Defaults to 100.
preserveItems: bool
Whether to preserve the steps exactly as they came in. Must be true when using the history together with the collaborative editing plugin, to allow syncing the history when concurrent changes come in.
undo(state: EditorState, onAction: ?fn(action: Action)) → bool

A command function that undoes the last change, if any.

redo(state: EditorState, onAction: ?fn(action: Action)) → bool

A command function that redoes the last undone change, if any.

undoDepth(state: EditorState) → number

The amount of undoable events available in a given state.

redoDepth(state: EditorState) → number

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

module collab

This module implements an API into which a communication channel for collaborative editing can be hooked. See this guide for more details and an example.

collab(config: ?Object) → Plugin

Creates a plugin that enables the collaborative editing framework for the editor.

config: ?Object

An optional set of options

version: ?number

The starting version number of the collaborative editing. Defaults to 0.

clientID: ?number

This client's ID, used to distinguish its changes from those of other clients. Defaults to a random 32-bit number.

getVersion(state: EditorState) → number

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

receiveAction(state: EditorState, steps: [Step], clientIDs: [number]) → Action

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

sendableSteps(state: EditorState) → ?{version: number, steps: [Step], clientID: number}

Provides the data describing the editor's unconfirmed steps, which you'd send to the central authority. Returns null when there is nothing to send.

module keymap

A plugin for conveniently defining key bindings.

keymap(bindings: Object) → Plugin

Create a keymap plugin for the given set of bindings.

Bindings should map key names to command-style functions, which will be called with (EditorState, onAction, EditorView) arguments, and should return true when they've handled the key. Note that the view argument isn't part of the command protocol, but can be used as an escape hatch if a binding needs to directly interact with the UI.

Key names may be strings like "Ctrl-Shift-Enter", a key identifier prefixed with zero or more modifiers. Key identifiers are based on the strings that can appear in KeyEvent.code.

For convenience, this module adds a few shorthands, like being able to say A instead of KeyA for the A key, and 1 instead of Digit1. It also allows Shift to cover both LeftShift and RightShift, and similarly for other keys that have both a left and right variant.

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 say Mod- as a shorthand for Cmd- on Mac and Ctrl- on other platforms.

Binding a typed character (i.e. a keypress instead of a keydown event) is done by wrapping the character in single quotes, as in "'x'". No modifiers are allowed for typed characters (since keypress events don't expose modifier info).

You can add multiple keymap plugins to an editor. The order in which they appear determines their precedence (the ones early in the array get to dispatch first).

module inputrules

This module defines a plugin for attaching ‘input rules’ to an editor, which can react to or transform text typed by the user. It also comes with a bunch of default rules that can be enabled in this plugin.

class InputRule

Input rules are regular expressions describing a piece of text that, when typed, causes something to happen. This might be changing two dashes into an emdash, wrapping a paragraph starting with "> " into a blockquote, or something entirely different.

new InputRule(match: RegExp, handler: string | fn(state: EditorState, match: [string], start: number, end: number) → ?EditorTransform)

Create an input rule. The rule applies when the user typed something and the text directly in front of the cursor matches match, which should probably end with $.

The handler can be a string, in which case the matched text, or the first matched group in the regexp, simply be replaced by that string.

Or a it can be a function, which will be called with the match array produced by RegExp.exec, as well as the start and end of the matched range, and which can return a transform that describes the rule's effect, or null to indicate the input was not handled.

inputRules(config: {rules: [InputRule]}) → Plugin

Create an input rules plugin. When enabled, it will cause text input that matches any of the given rules to trigger the rule's action, and binds the backspace key, when applied directly after an input rule triggered, to undo the rule's effect.

The module comes with a number of predefined rules:

emDash: InputRule

Converts double dashes to an emdash.

ellipsis: InputRule

Converts three dots to an ellipsis character.

openDoubleQuote: InputRule

“Smart” opening double quotes.

closeDoubleQuote: InputRule

“Smart” closing double quotes.

openSingleQuote: InputRule

“Smart” opening single quotes.

closeSingleQuote: InputRule

“Smart” closing single quotes.

smartQuotes: [InputRule]

Smart-quote related input rules.

allInputRules: [InputRule]

All schema-independent input rules defined in this module.

These utility functions take schema-specific parameters and create input rules specific to that schema.

wrappingInputRule(regexp: RegExp, nodeType: NodeType, getAttrs: ?Object | fn([string]) → ?Object, joinPredicate: ?fn([string], Node) → bool) → InputRule

Build an input rule for automatically wrapping a textblock when a given string is typed. The regexp argument is directly passed through to the InputRule constructor. You'll probably want the regexp to start with ^, so that the pattern can only occur at the start of a textblock.

nodeType is the type of node to wrap in. If it needs attributes, you can either pass them directly, or pass a function that will compute them from the regular expression match.

By default, if there's a node with the same type above the newly wrapped node, the rule will try to join those two nodes. You can pass a join predicate, which takes a regular expression match and the node before the wrapped node, and can return a boolean to indicate whether a join should happen.

textblockTypeInputRule(regexp: RegExp, nodeType: NodeType, getAttrs: ?Object | fn([string]) → ?Object) → InputRule

Build an input rule that changes the type of a textblock when the matched text is typed into it. You'll usually want to start your regexp with ^ to that it is only matched at the start of a textblock. The optional getAttrs parameter can be used to compute the new node's attributes, and works the same as in the wrappingInputRule function.

blockQuoteRule(nodeType: NodeType) → InputRule

Given a blockquote node type, returns an input rule that turns "> " at the start of a textblock into a blockquote.

orderedListRule(nodeType: NodeType) → InputRule

Given a list node type, returns an input rule that turns a number followed by a dot at the start of a textblock into an ordered list.

bulletListRule(nodeType: NodeType) → InputRule

Given a list node type, returns an input rule that turns a bullet (dash, plush, or asterisk) at the start of a textblock into a bullet list.

codeBlockRule(nodeType: NodeType) → InputRule

Given a code block node type, returns an input rule that turns a textblock starting with three backticks into a code block.

headingRule(nodeType: NodeType, maxLevel: number) → InputRule

Given a node type and a maximum level, creates an input rule that turns up to that number of # characters followed by a space at the start of a textblock into a heading whose level corresponds to the number of # signs.

module schema-basic

This module defines a simple schema, to use directly, extend, or to reuse pieces in a schema you assemble.

schema: Schema

This schema rougly corresponds to the document schema used by CommonMark, minus the list elements, which are defined in the schema-list module.

To reuse elements from this schema, extend or read from its nodeSpec and markSpec properties.

nodes: Object
doc: NodeSpec

The top level document node.

paragraph: NodeSpec

A plain paragraph textblock.

blockquote: NodeSpec

A blockquote wrapping one or more blocks.

horizontal_rule: NodeSpec

A horizontal rule.

heading: NodeSpec

A heading textblock, with a level attribute that should hold the number 1 to 6.

code_block: NodeSpec

A code listing. Disallows marks or non-text inline nodes by default.

text: NodeSpec

The text node.

image: NodeSpec

An inline image node. Supports src, alt, and href attributes. The latter two default to the empty string.

hard_break: NodeSpec

A hard line break.

marks: Object
em: MarkSpec

An emphasis mark.

strong: MarkSpec

A strong mark.

A link. Has href and title attributes. title defaults to the empty string.

code: MarkSpec

Code font mark.

module schema-list

This module exports list-related schema elements and commands. The commands assume which assume lists to be nestable, but with the restriction that the first child of a list item is a plain paragraph.

These are the node specs:

orderedList: NodeSpec

An ordered list node type spec. Has a single attribute, order, which determines the number at which the list starts counting, and defaults to 1.

bulletList: NodeSpec

A bullet list node spec.

listItem: NodeSpec

A list item node spec.

You can extend a schema with this helper function.

addListNodes(nodes: OrderedMap, itemContent: string, listGroup: ?string) → OrderedMap

Convenience function for adding list-related node types to a map describing the nodes in a schema. Adds OrderedList as "ordered_list", BulletList as "bullet_list", and ListItem as "list_item". itemContent determines the content expression for the list items. If you want the commands defined in this module to apply to your list structure, it should have a shape like "paragraph block*", a plain textblock type followed by zero or more arbitrary nodes. listGroup can be given to assign a group name to the list node types, for example "block".

Using this would look something like this:

const mySchema = new Schema({
  nodes: addListNodes(baseSchema.nodeSpec, "paragraph block*", "block"),
  marks: baseSchema.markSpec
})

The following functions are commands:

wrapInList(nodeType: NodeType, attrs: ?Object) → fn(state: EditorState, onAction: ?fn(action: Action)) → bool

Returns a command function that wraps the selection in a list with the given type an attributes. If apply is false, only return a value to indicate whether this is possible, but don't actually perform the change.

splitListItem(nodeType: NodeType) → fn(state: EditorState) → bool

Build a command that splits a non-empty textblock at the top level of a list item by also splitting that list item.

liftListItem(nodeType: NodeType) → fn(state: EditorState, onAction: ?fn(action: Action)) → bool

Create a command to lift the list item around the selection up into a wrapping list.

sinkListItem(nodeType: NodeType) → fn(state: EditorState, onAction: ?fn(action: Action)) → bool

Create a command to sink the list item around the selection down into an inner list.

module schema-table

This module defines schema elements and commands to integrate tables in your editor.

Note that Firefox will, by default, add various kinds of controls to editable tables, even though those don't work in ProseMirror. The only way to turn these off is globally, which you might want to do with the following code:

document.execCommand("enableObjectResizing", false, "false")
document.execCommand("enableInlineTableEditing", false, "false")

These are the node specs for basic table support:

table: NodeSpec

A table node spec. Has one attribute, columns, which holds a number indicating the amount of columns in the table.

tableRow: NodeSpec

A table row node spec. Has one attribute, columns, which holds a number indicating the amount of columns in the table.

tableCell: NodeSpec

A table cell node spec.

Two special step implementations are necessary to atomically add or remove columns. You probably don't have to interact with these directly.

class AddColumnStep extends Step

A Step subclass for adding a column to a table in a single atomic step.

static create(doc: Node, tablePos: number, columnIndex: number, cellType: NodeType, cellAttrs: ?Object) → AddColumnStep

Create a step that inserts a column into the table after tablePos, at the index given by columnIndex, using cells with the given type and attributes.

class RemoveColumnStep extends Step

A subclass of Step that removes a column from a table.

static create(doc: Node, tablePos: number, columnIndex: number) → RemoveColumnStep

Create a step that deletes the column at columnIndex in the table after tablePos.

And some utility functions:

addTableNodes(nodes: OrderedMap, cellContent: string, tableGroup: ?string) → OrderedMap

Convenience function for adding table-related node types to a map describing the nodes in a schema. Adds Table as "table", TableRow as "table_row", and TableCell as "table_cell". cellContent should be a content expression describing what may occur inside cells.

createTable(nodeType: NodeType, rows: number, columns: number, attrs: ?Object) → Node

Create a table node with the given number of rows and columns.

And a number of table-related commands:

addColumnBefore(state: EditorState, onAction: ?fn(action: Action)) → bool

Command function that adds a column before the column with the selection.

addColumnAfter(state: EditorState, onAction: ?fn(action: Action)) → bool

Command function that adds a column after the column with the selection.

removeColumn(state: EditorState, onAction: ?fn(action: Action)) → bool

Command function that removes the column with the selection.

addRowBefore(state: EditorState, onAction: ?fn(action: Action)) → bool

Command function that adds a row after the row with the selection.

addRowAfter(state: EditorState, onAction: ?fn(action: Action)) → bool

Command function that adds a row before the row with the selection.

removeRow(state: EditorState, onAction: ?fn(action: Action)) → bool

Command function that removes the row with the selection.

selectNextCell(state: EditorState, onAction: ?fn(action: Action)) → bool

Move to the next cell in the current table, if there is one.

selectPreviousCell(state: EditorState, onAction: ?fn(action: Action)) → bool

Move to the previous cell in the current table, if there is one.