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 distributed as a set of JavaScript modules. This
reference manual describes the exported API per module. So if you want
to use something from the edit module, you have to import
it from there.
var edit = require("prosemirror/dist/edit")
var editor = new edit.ProseMirror()
Or in ES6 syntax:
import {ProseMirror} from "prosemirror/dist/edit"
let editor = new ProseMirror()
Note that the content of the dist directory only exists in a built
version of code. If you are getting it from npm, you should be fine.
If you manually cloned the
git repository, you'll
need to npm install inside of it first.
This module implements the ProseMirror editor. It contains
functionality related to editing, selection, and integration with
the browser. ProseMirror is the class you'll want to instantiate
and interact with when using the editor.
Options
schema: Schema πThe schema that the editor's document should use.
doc: any πThe starting document. Usually a Node, but can be in another
format when the docFormat option is also specified.
docFormat: ?string πThe format in which the doc option is given. Defaults to null
(a raw Node).
place: ?union<DOMNode, fn(DOMNode)> πDetermines the placement of the editor in the page. When null,
the editor is not placed. When a DOM node is given, the editor is
appended to that node. When a function is given, it is called
with the editor's wrapping DOM node, and is expected to place it
into the document.
historyDepth: number πThe amount of history events that are collected before the oldest
events are discarded. Defaults to 100.
historyEventDelay: number πThe amount of milliseconds that must pass between changes to
start a new history event. Defaults to 500.
scrollThreshold: number πThe minimum distance to keep between the position of document
changes and the editor bounding rectangle before scrolling the view.
Defaults to 0.
scrollMargin: number πDetermines how far to scroll when the scroll threshold is
surpassed. Defaults to 5.
commands: CommandSet πSpecifies the set of commands available in the editor
(which in turn determines the base key bindings and items available
in the menus). Defaults to CommandSet.default.
commandParamPrompt: ParamPrompt πA default parameter prompting class to use when a
command is executed without providing
parameters.
label: ?string πThe label of the editor. When set, the editable DOM node gets an
aria-label attribute with this value.
translate(string) βΒ string πOptional function to translate strings such as menu labels and prompts.
When set, should be a function that takes a string as argument and returns
a string, i.e. :: (string) β string
FIXME create a way to explicitly force a menu redraw
This is the class used to represent instances of the editor. A
ProseMirror editor holds a document and a
selection, and displays an editable surface
representing that document in the browser document.
Contains event methods (on, etc) from the event
mixin.
Constructor
new ProseMirror(opts:Β Object) πConstruct a new editor from a set of options
and, if it has a place option, add it to the
document.
Properties
schema: Schema πThe schema for this editor's document.
content: DOMNode πThe editable DOM node containing the document.
wrapper: DOMNode πThe outer DOM element of the editor.
mod: Object πA namespace where modules can store references to themselves
associated with this editor instance.
commands: Object<Command> πThe commands available in the editor.
selection: Selection πGet the current selection.
doc: Node πThe current document.
history: History πThe edit history for the editor.
tr: EditorTransform πCreate an editor- and selection-aware Transform for this editor.
Methods
setOption(name:Β string, value:Β any) πUpdate the value of the given option.
getOption(name:Β string) βΒ any πGet the current value of the given option.
setTextSelection(anchor:Β number, head:Β ?number = anchor) πSet the selection to a text selection from
anchor to head, or, if head is null, a cursor selection at
anchor.
setNodeSelection(pos:Β number) πSet the selection to a node selection on the node after pos.
setSelection(selection:Β Selection) πSet the selection to the given selection object.
setContent(value:Β any, format:Β ?string) πReplace the editor's document. When format is given, it should
be a parsable format, and value should something in
that format. If not, value should be a Node.
getContent(format:Β ?string, options:Β ?Object) βΒ any πGet the editor's content in a given format. When format is not
given, a Node is returned. If it is given, it should be an
existing serialization format. Options to the serializer
may be given as a second argument.
setDoc(doc:Β Node, sel:Β ?Selection) πSet the editor's content, and optionally include a new selection.
apply(transform:Β Transform, options:Β ?Object = nullOptions) βΒ union<Transform, bool> πApply a transformation (which you might want to create with the
tr getter) to the document in the editor.
The following options are supported:
selection: ?Selection
- A new selection to set after the transformation is applied.
scrollIntoView: ?bool
- When true, scroll the selection into view on the next
redraw.
filter: ?bool
- When set to false, suppresses the ability of the
"filterTransform" event
to cancel this transform.
Returns the transform, or false if there were no steps in it.
Has the following property:
scroll: Object πThe object {scrollIntoView: true}, which is a common argument to
pass to ProseMirror.apply or EditorTransform.apply.
checkPos(pos:Β number, textblock:Β ?bool) πVerify that the given position is valid in the current document,
and throw an error otherwise. When textblock is true, the position
must also fall within a textblock node.
flush() βΒ bool πFlush any pending changes to the DOM. When the document,
selection, or marked ranges in an editor change, the DOM isn't
updated immediately, but rather scheduled to be updated the next
time the browser redraws the screen. This method can be used to
force this to happen immediately. It can be useful when you, for
example, want to measure where on the screen a part of the
document ends up, immediately after changing the document.
Returns true when it updated the document DOM.
addKeymap(map:Β Keymap, rank:Β ?number = 50) πAdd a
keymap
to the editor. Keymaps added in this way are queried before the
base keymap. The rank parameter can be used to
control when they are queried relative to other maps added like
this. Maps with a lower rank get queried first.
removeKeymap(map:Β union<string, Keymap>) πRemove the given keymap, or the keymap with the given name, from
the editor.
markRange(from:Β number, to:Β number, options:Β ?Object) βΒ MarkedRange πCreate a marked range between the given positions. Marked ranges
βtrackβ the part of the document they point toβas the document
changes, they are updated to move, grow, and shrink along with
their content.
options may be an object containing these properties:
inclusiveLeft: bool = false
- Whether the left side of the range is inclusive. When it is,
content inserted at that point will become part of the range.
When not, it will be outside of the range.
inclusiveRight: bool = false
- Whether the right side of the range is inclusive.
removeWhenEmpty: bool = true
- Whether the range should be forgotten when it becomes empty
(because all of its content was deleted).
className: string
- A CSS class to add to the inline content that is part of this
range.
removeRange(range:Β MarkedRange) πRemove the given range from the editor.
setMark(type:Β MarkType, to:Β ?bool, attrs:Β ?Object) πSet (when to is true), unset (to is false), or toggle (to
is null) the given mark type on the selection. When there is a
non-empty selection, the marks of the selection are updated. When
the selection is empty, the set of active
marks is updated.
activeMarks() βΒ [Mark] πGet the marks at the cursor. By default, this yields the marks
associated with the content at the cursor, as per Node.marksAt.
But setMark may have been used to change the set of active
marks, in which case that set is returned.
focus() πGive the editor focus.
hasFocus() βΒ bool πQuery whether the editor has focus.
posAtCoords(coords:Β {top:Β number, left:Β number}) βΒ ?number πIf the given coordinates (which should be relative to the top
left corner of the windowβnot the page) fall within the editable
content, this method will return the document position that
corresponds to those coordinates.
coordsAtPos(pos:Β number) βΒ {top:Β number, left:Β number, bottom:Β number} πFind the screen coordinates (relative to top left corner of the
window) of the given document position.
scrollIntoView(pos:Β ?number = null) πScroll the given position, or the cursor position if pos isn't
given, into view.
execCommand(name:Β string, params:Β ?[any]) βΒ bool πExecute the named command. If the command takes
parameters, they can be passed as an array.
keyForCommand(name:Β string) βΒ ?string πReturn the name of the key that is bound to the given command, if
any.
translate(string:Β string) βΒ string πReturn a translated string, if a translate function has been supplied,
or the original string.
Events
optionChanged(name:Β string, value:Β any) πFired when setOption is called.
beforeSetDoc(doc:Β Node, selection:Β Selection) πFired when setDoc is called, before
the document is actually updated.
setDoc(doc:Β Node, selection:Β Selection) πFired when setDoc is called, after
the document is updated.
change() πFired when the document has changed. See
setDoc and
transform for more specific
change-related events.
filterTransform(transform:Β Transform) πFired before a transform (applied without filter: false) is
applied. The handler can return a truthy value to cancel the
transform.
beforeTransform(transform:Β Transform, options:Β Object) πIndicates that the given transform is about to be
applied. The handler may add additional
steps to the transform, but it it not allowed to
interfere with the editor's state.
transform(transform:Β Transform, selectionBeforeTransform:Β Selection, options:Β Object) πSignals that a (non-empty) transformation has been aplied to
the editor. Passes the Transform, the selection before the
transform, and the options given to apply
as arguments to the handler.
flushing() πFired when the editor is about to flush
an update to the DOM.
draw() πFired when the editor redrew its document in the DOM.
flush() πFired when the editor has finished
flushing an update to the DOM.
activeMarkChange() πFired when the set of active marks changes.
selectionChange() πIndicates that the editor's selection has changed.
commandsChanging() πFired before the set of commands for the editor is updated.
commandsChanged() πFired when the set of commands for the editor is updated.
textInput() πFired when the user types text into the editor.
interaction() πFired when the user interacts with the editor, for example by
clicking on it or pressing a key while it is focused. Mostly
useful for closing or resetting transient UI state such as open
menus.
transformPastedText(text:Β string) βΒ string πFired when plain text is pasted. Handlers must return the given
string or a transformed version of
it.
transformPastedHTML(html:Β string) βΒ string πFired when html content is pasted or dragged into the editor.
Handlers must return the given string or a
transformed version of it.
transformPasted(slice:Β Slice) βΒ Slice πFired when something is pasted or dragged into the editor. The
given slice represents the pasted content, and your handler can
return a modified version to manipulate it before it is inserted
into the document.
drop(event:Β DOMEvent) πFired when a drop event occurs on the editor content. A handler
may declare the event handled by calling preventDefault on it
or returning a truthy value.
focus() πFired when the editor gains focus.
blur() πFired when the editor loses focus.
An editor selection. Can be one of two selection types:
TextSelection and NodeSelection. Both have the properties
listed here, but also contain more information (such as the
selected node or the
head and anchor).
Properties
from: number πThe left-bound of the selection.
to: number πThe right-bound of the selection.
empty: bool πTrue if the selection is an empty text selection (head an anchor
are the same).
Methods
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.
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).
Constructor
new TextSelection(anchor:Β number, head:Β ?number) πConstruct a text selection. When head is not given, it defaults
to anchor.
Properties
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).
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.
Constructor
new NodeSelection(from:Β number, to:Β number, node:Β Node) πCreate a node selection. Does not verify the validity of its
arguments. Use ProseMirror.setNodeSelection for an easier,
error-checking way to create a node selection.
Properties
node: Node πThe selected node.
A marked range. Includes the methods
from the event mixin.
Properties
from: ?number πThe current start position of the range. Updated whenever the
editor's document is changed. Set to null when the marked
range is removed.
to: ?number πThe current end position of the range. Updated whenever the
editor's document is changed. Set to null when the marked
range is removed.
Events
removed(from:Β number, to:Β number) πSignalled when the marked range is removed from the editor.
A command is a named piece of functionality that can be bound to
a key, shown in the menu, or otherwise exposed to the user.
The commands available in a given editor are determined by the
commands option. By default, they come from the baseCommands
object and the commands registered with
schema items. Registering a CommandSpec on a node or
mark type will cause that command to come into scope
in editors whose schema includes that item.
Properties
name: string πThe name of the command.
spec: CommandSpec πThe command's specifying object.
params: [CommandParam] πGet the list of parameters that this command expects.
label: string πGet the label for this command.
Methods
exec(pm:Β ProseMirror, params:Β ?[any]) βΒ ?bool πExecute this command. If the command takes
parameters, they can be passed as second
argument here, or otherwise the user will be prompted for them
using the value of the commandParamPrompt option.
Returns the value returned by the command spec's run
method, or a ParamPrompt instance if the
command is ran asynchronously through a prompt.
select(pm:Β ProseMirror) βΒ bool πAsk this command whether it is currently relevant, given the
editor's document and selection. If the command does not define a
select method, this always returns true.
active(pm:Β ProseMirror) βΒ bool πAsk this command whether it is βactiveβ. This is mostly used to
style inline mark icons (such as strong) differently when the
selection contains such marks.
The type used as the value of the commands option. Allows you
to specify the set of commands that are available in the editor by
adding and modifying command specs.
Methods
add(set:Β union<Object<CommandSpec>, "schema">, filter:Β ?fn(string, CommandSpec) βΒ bool) βΒ CommandSet πAdd a set of commands, creating a new command set. If set is
the string "schema", the commands are retrieved from the
editor's schema's registry, otherwise, it
should be an object mapping command names to command specs.
A filter function can be given to add only the commands for which
the filter returns true.
update(update:Β Object<?CommandSpec>) βΒ CommandSet πCreate a new command set by adding, modifying, or deleting
commands. The update object can map a command name to null to
delete it, to a full CommandSpec (containing a run property)
to add it, or to a partial CommandSpec (without a run
property) to update some properties in the command by that name.
Static properties
empty: CommandSet πA set without any commands.
default: CommandSet πThe default value of the commands option. Includes the base
commands and the commands defined by the schema.
Commands are defined using objects that specify various aspects of
the command. The only property that must appear in a command spec
is run. You should probably also give your
commands a label.
label: string πA user-facing label for the command. This will be used, among other
things. as the tooltip title for the command's menu item. If there
is no label, the command's name will be used instead.
run(pm:Β ProseMirror, ...params:Β [any]) βΒ ?bool πThe function that executes the command. If the command has
parameters, their values are passed as
arguments. For commands registered on node or
mark types, this will be bound to the node or mark type when this
function is ran. Should return false when the command could not
be executed.
params: [CommandParam] πThe parameters that this command expects.
select(pm:Β ProseMirror) βΒ bool πThe function used to select the command. this
will again be bound to a node or mark type, when available.
active(pm:Β ProseMirror) βΒ bool πThe function used to determine whether the command is
active. this refers to the associated node or
mark type.
keys: union<Object<[string]>, [string]> πThe default key bindings for this command. May either be an array
of strings containing key
names,
or an object with optional all, mac, and pc properties,
specifying arrays of keys for different platforms.
derive: union<bool, Object> πMark and node types often need to define
boilerplate commands. To reduce the amount of duplicated code, you
can derive such commands by setting the derive property to either
true or an object which is passed to the deriving function. If
this object has a name property, that is used, instead of the
command name, to pick a deriving function.
For node types, you can derive "insert", "make", and "wrap".
For mark types, you can derive "set", "unset", and "toggle".
The parameters that a command can take are specified using objects
with the following properties:
label: string πThe user-facing name of the parameter. Shown to the user when
prompting for this parameter.
type: string πThe type of the parameter. Supported types are "text" and "select".
default: any πA default value for the parameter.
prefill(ProseMirror) βΒ ?any πA function that, given an editor instance (and a this bound to
the command's source item), tries to derive an initial value for
the parameter, or return null if it can't.
validate(any) βΒ ?string πAn optional function that is called to validate values provided for
this parameter. Should return a falsy value when the value is
valid, and an error message when it is not.
You can add several properties to node types to
influence the way the editor interacts with them.
Methods
countCoordsAsChild(node:Β Node, pos:Β number, dom:Β DOMNode, coords:Β {left:Β number, top:Β number}) βΒ ?number πSpecifies that, if this node is clicked, a child node might
actually be meant. This is used to, for example, make clicking a
list marker (which, in the DOM, is part of the list node) select
the list item it belongs to. Should return null if the given
coordinates don't refer to a child node, or the position
before the child otherwise.
handleClick(pm:Β ProseMirror, event:Β MouseEvent, pos:Β number, node:Β Node) βΒ bool πIf a node is directly clicked (that is, the click didn't land in a
DOM node belonging to a child node), and its type has a
handleClick method, that method is given a chance to handle the
click. The method is called, and should return false if it did
not handle the click.
The event passed is the event for "mousedown", but calling
preventDefault on it has no effect, since this method is only
called after a corresponding "mouseup" has occurred and
ProseMirror has determined that this is not a drag or multi-click
event.
handleDoubleClick(pm:Β ProseMirror, event:Β MouseEvent, pos:Β number, node:Β Node) βΒ bool πThis works like handleClick, but is
called for double clicks instead.
handleContextMenu(pm:Β ProseMirror, event:Β MouseEvent, pos:Β number, node:Β Node) βΒ bool πWhen the context
menu
is activated in the editable context, nodes that the clicked
position falls inside of get a chance to react to it. Node types
may define a handleContextMenu method, which will be called when
present, first on inner nodes and then up the document tree, until
one of the methods returns something other than false.
The handlers can inspect event.target to figure out whether they
were directly clicked, and may call event.preventDefault() to
prevent the native context menu.
An undo/redo history manager for an editor instance.
Properties
undoDepth: number πThe amount of undoable events available.
redoDepth: number πThe amount of redoable events available.
Methods
undo() βΒ bool πUndo one history event. The return value indicates whether
anything was actually undone. Note that in a collaborative
context, or when changes are applied
without adding them to the history, it is possible for
undoDepth to have a positive value, but
this method to still return false, when non-history changes
overwrote all remaining changes in the history.
redo() βΒ bool πRedo one history event. The return value indicates whether
anything was actually redone.
getVersion() βΒ Object πGet the current βversionβ of the editor content. This can be used
to later check whether anything changed, or
to roll back to this version.
isAtVersion(version:Β Object) βΒ bool πReturns true when the editor history is in the state that it
was when the given version was recorded.
That means either no changes were made, or changes were
done/undone and then undone/redone again.
backToVersion(version:Β Object) βΒ bool πRolls back all changes made since the given
version was recorded. Returns false if
that version was no longer found in the history, and thus the
action could not be completed.
Extends Transform.
A selection-aware extension of Transform. Use
ProseMirror.tr to create an instance.
selection: Selection πGet the editor's current selection, mapped
through the steps in this transform.
apply(options:Β ?Object) βΒ ?EditorTransform πApply the transformation. Returns the transform, or false it is
was empty.
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.
typeText(text:Β string) βΒ EditorTransform πReplace the selection with a text node containing the given string.
Functions
defineOption(name:Β string, defaultValue:Β any, update:Β ?fn(pm:Β ProseMirror, newValue:Β any, oldValue:Β any, init:Β bool), updateOnInit:Β bool) πDefine a new option. The update handler will be called with the
option's old and new value every time the option is
changed. When updateOnInit is false, it
will not be called on editor init, otherwise it is called with null as the old value,
and a fourth argument of true.
Constants
baseCommands: Object<CommandSpec> πThe set of default commands defined by the core library. They are
included in the default command set.
deleteSelection πDelete the selection, if there is one.
Keybindings: Backspace, Delete, Mod-Backspace, Mod-Delete,
**Ctrl-H (Mac), Alt-Backspace (Mac), Ctrl-D (Mac),
**Ctrl-Alt-Backspace (Mac), Alt-Delete (Mac), Alt-D (Mac)
joinBackward π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.
Keybindings: Backspace, Mod-Backspace
deleteCharBefore πDelete the character before the cursor, if the selection is empty
and the cursor isn't at the start of a textblock.
Keybindings: Backspace, Ctrl-H (Mac)
deleteWordBefore πDelete the word before the cursor, if the selection is empty and
the cursor isn't at the start of a textblock.
Keybindings: Mod-Backspace, Alt-Backspace (Mac)
joinForward π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).
Keybindings: Delete, Mod-Delete
deleteCharAfter πDelete the character after the cursor, if the selection is empty
and the cursor isn't at the end of its textblock.
Keybindings: Delete, Ctrl-D (Mac)
deleteWordAfter πDelete the word after the cursor, if the selection is empty and the
cursor isn't at the end of a textblock.
Keybindings: Mod-Delete, Ctrl-Alt-Backspace (Mac), Alt-Delete
(Mac), Alt-D (Mac)
joinUp π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.
Keybindings: Alt-Up
joinDown πJoin the selected block, or the closest ancestor of the selection
that can be joined, with the sibling after it.
Keybindings: Alt-Down
lift πLift the selected block, or the closest ancestor block of the
selection that can be lifted, out of its parent node.
Keybindings: Ctrl-[
newlineInCode πIf the selection is in a node whose type has a truthy isCode
property, replace the selection with a newline character.
Keybindings: Enter
createParagraphNear πIf a block node is selected, create an empty paragraph before (if
it is its parent's first child) or after it.
Keybindings: Enter
liftEmptyBlock πIf the cursor is in an empty textblock that can be lifted, lift the
block.
Keybindings: Enter
splitBlock πSplit the parent block of the selection. If the selection is a text
selection, delete it.
Keybindings: Enter
selectParentNode πMove the selection to the node wrapping the current selection, if
any. (Will not select the document node.)
Keybindings: Esc
undo πUndo the most recent change event, if any.
Keybindings: Mod-Z
redo πRedo the most recently undone change event, if any.
Keybindings: Mod-Y, Shift-Mod-Z
Commands
strong:set πAdd the strong mark to the selected content.
strong:unset πRemove the strong mark from the selected content.
strong:toggle πToggle the strong mark. If there is any strong
content in the selection, or there is no selection and the active
marks contain the strong mark, this
counts as active and executing it removes the
mark. Otherwise, this does not count as active, and executing it
makes the selected content strong.
Keybindings: Mod-B
em:set πAdd the emphasis mark to the selected content.
em:unset πRemove the emphasis mark from the selected content.
em:toggle πToggle the emphasis mark. If there is any emphasized
content in the selection, or there is no selection and the active
marks contain the emphasis mark, this
counts as active and executing it removes the
mark. Otherwise, this does not count as active, and executing it
makes the selected content emphasized.
Keybindings: Mod-I
code:set πAdd the code mark to the selected content.
code:unset πRemove the code mark from the selected content.
code:toggle πToggle the code mark. If there is any code-styled
content in the selection, or there is no selection and the active
marks contain the code mark, this
counts as active and executing it removes the
mark. Otherwise, this does not count as active, and executing it
styles the selected content as code.
Keybindings: Mod-`
link:unset πRemoves all links for the selected content, or, if there is no
selection, from the active marks. Will
only select itself when there is a link in the
selection or active marks.
link:set πAdds a link mark to the selection or set of active
marks. Takes parameters to determine the
attributes of the link:
href: string
- The link's target.
title: string
- The link's title.
Only selects itself when unlink isn't selected, so that only one
of the two is visible in the menu at any time.
image:insert πReplace the selection with an image node. Takes paramers
that specify the image's attributes:
src: string
- The URL of the image.
alt: string
- The alt text for the image.
title: string
- A title for the image.
bullet_list:wrap πWrap the selection in a bullet list.
Keybindings: Shift-Ctrl-8
ordered_list:wrap πWrap the selection in an ordered list.
Keybindings: Shift-Ctrl-9
blockquote:wrap πWrap the selection in a block quote.
Keybindings: Shift-Ctrl-.
hard_break:insert πReplace the selection with a hard break node. If the selection is
in a node whose type has a truthy isCode property
(such as CodeBlock in the default schema), a regular newline is
inserted instead.
Keybindings: Mod-Enter, Shift-Enter
list_item:split πIf the selection is a text selection inside of a child of a list
item, split that child and the list item, and delete the selection.
Keybindings: Enter
list_item:lift πLift a list item into a parent list.
Keybindings: Mod-[
list_item:sink πMove a list item into a sublist.
Keybindings: Mod-]
heading:make_ πThe commands make1 to make6 set the textblocks in the
selection to become headers with the given level.
Keybindings: Shift-Ctrl-1 through Shift-Ctrl-6
paragraph:make πSet the textblocks in the selection to be regular paragraphs.
Keybindings: Shift-Ctrl-0
code_block:make πSet the textblocks in the selection to be code blocks.
Keybindings: Shift-Ctrl-\
horizontal_rule:insert πReplace the selection with a horizontal rule.
Keybindings: Mod-Shift-Minus
This module defines ProseMirror's document model, the data
structure used to define and inspect content documents. It
includes:
This module does not depend on the browser API being available
(i.e. you can load it into any JavaScript environment).
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.
Properties
type: NodeType πThe type of node that this is.
attrs: Object πAn object mapping attribute names to string values. The kind of
attributes allowed and required are determined by the node
type.
content: Fragment πThe node's content.
marks: [Mark] πThe marks (things like whether it is emphasized or part of a
link) associated with this node.
nodeSize: number πThe size of this node. For text node, this is the amount of
characters. For 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.
textContent: string πConcatenate all the text nodes found in this fragment and its
children.
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.
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.
text: ?string πFor text nodes, this contains the node's text content.
Methods
child(index:Β number) βΒ Node πGet the child node at the given index. Raise 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)) πCall f for every child node, passing the node and its offset
into this parent node.
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.
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.
resolve(pos:Β number) βΒ ResolvedPos πResolve the given position in the document, returning an object
describing its path through the document.
marksAt(pos:Β number) βΒ [Mark] πGet the marks at the given position factoring in the surrounding marks'
inclusiveLeft and inclusiveRight properties. If the position is at the
start of a non-empty node, 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.
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 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 properties
fromJSON(schema:Β Schema, json:Β Object) βΒ Node πDeserialize a node from its JSON representation.
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.
Properties
textContent: string πConcatenate all the text nodes found in this fragment and its
children.
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.
Methods
toString() βΒ string πReturn a debugging string that describes this fragment.
cut(from:Β number, to:Β ?number) βΒ Fragment πCut out the sub-fragment between the two given positions.
append(other:Β Fragment) βΒ Fragment πCreate a new fragment containing the content of this fragment and
other.
replaceChild(index:Β number, node:Β Node) βΒ Fragment πCreate a new fragment in which the node at the given index is
replaced by the given node.
toJSON() βΒ ?Object πCreate a JSON-serializeable representation of this fragment.
eq(other:Β Fragment) βΒ bool πCompare this fragment to another one.
child(index:Β number) βΒ Node πGet the child node at the given index. Raise 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)) πCall f for every child node, passing the node and its offset
into this parent node.
Static properties
fromJSON(schema:Β Schema, value:Β ?Object) βΒ Fragment πDeserialize a fragment from its JSON representation.
fromArray(array:Β [Node]) βΒ Fragment πBuild a fragment from an array of nodes. Ensures that adjacent
text nodes with the same style are joined together.
from(nodes:Β ?union<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.
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).
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.
Properties
type: MarkType πThe type of this mark.
attrs: Object πThe attributes associated with this mark.
Methods
toJSON() βΒ Object πConvert this mark to a JSON-serializeable representation.
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 or another of its type
is already in the set, the set itself 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.
Static properties
sameSet(a:Β [Mark], b:Β [Mark]) βΒ bool πTest whether two sets of marks are identical.
setFrom(marks:Β ?union<Mark, [Mark]>) βΒ [Mark] πCreate a properly sorted mark set from null, a single mark, or an
unsorted array of marks.
The node and mark types
that make up a schema have several things in commonβthey support
attributes, and you can register values
with them. This class implements this functionality, and acts as a
superclass to those NodeType and MarkType.
Properties
attrs: Object<Attribute> πThe set of attributes to associate with each node or mark of this
type.
Static properties
updateAttrs(attrs:Β Object<?Attribute>) πAdd or remove attributes from this type. Expects an object
mapping names to either attributes (to add) or null (to remove
the attribute by that name).
register(namespace:Β string, name:Β string, value:Β any) πRegister a value in this type's registry. Various components use
Schema.registry to query values from the marks and nodes that
make up the schema. The namespace, for example
"command", determines which component will see
this value. name is a name specific to this value. Its meaning
differs per namespace.
Subtypes inherit the registered values from their supertypes.
They can override individual values by calling this method to
overwrite them with a new value, or with null to disable them.
registerComputed(namespace:Β string, name:Β string, f:Β fn(SchemaItem) βΒ any) πRegister a value in this types's registry, like
register, but providing a function that
will be called with the actual node or mark type, whose return
value will be treated as the effective value (or will be ignored,
if null).
cleanNamespace(namespace:Β string) πBy default, schema items inherit the
registered items from their superclasses.
Call this to disable that behavior for the given namespace.
Extends SchemaItem.
Node types are objects allocated once per Schema
and used to tag Node instances with a type. They are
instances of sub-types of this class, and contain information about
the node type (its name, its allowed attributes, methods for
serializing it to various formats, information to guide
deserialization, and so on).
Properties
name: string πThe name the node type has in this schema.
schema: Schema πA link back to the Schema the node type belongs to.
isBlock: bool πTrue if this is a block type.
isTextblock: bool πTrue if this is a textblock type, a block that contains inline
content.
isInline: bool πTrue if this is an inline type.
isText: bool πTrue if this is the text node type.
selectable: bool πControls whether nodes of this type can be selected (as a user
node selection).
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.
locked: bool πControls whether this node type is locked.
isLeaf: bool πTrue for node types that allow no content.
Methods
create(attrs:Β ?Object, content:Β ?union<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.
validContent(content:Β Fragment, attrs:Β ?Object) βΒ bool πReturns true if the given fragment is valid content for this node
type.
fixContent(content:Β Fragment, attrs:Β ?Object) βΒ ?Fragment πVerify whether the given fragment would be valid content for this
node type, and if not, try to insert content before and/or after
it to make it valid. Returns null if no valid fragment could be
created.
Extends NodeType.
Base type for block nodetypes.
Extends Block.
Base type for textblock node types.
Extends NodeType.
Base type for inline node types.
Extends Inline.
The text node type.
Attributes are named values associated with nodes and marks.
Each node type or mark type has a fixed set of attributes, which
instances of this class are used to control. Attribute values must
be JSON-serializable.
Constructor
new Attribute(options:Β ?Object = {}) πCreate an attribute. options is an object containing the
settings for the attributes. The following settings are
supported:
default: ?any
- The default value for this attribute, to choose when no
explicit value is provided.
compute: ?(Fragment) β any
- A function that computes a default value for the attribute from
the node's content.
label: ?string
- A user-readable text label associated with the attribute.
Attributes that have no default or compute property must be
provided whenever a node or mark of a type that has them is
created.
Extends SchemaItem.
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.
Properties
name: string πThe name of the mark type.
schema: Schema πThe schema that this mark type instance is part of.
inclusiveRight: bool πWhether this mark should be active when the cursor is positioned
at the end of the mark.
Methods
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.
An object describing a schema, as passed to the Schema
constructor.
nodes: union<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: ?union<Object<constructor<MarkType>>, OrderedMap<constructor<MarkType>>> πThe mark types that exist in this schema.
type: constructor<NodeType> πThe NodeType class to be used for this node.
content: ?string πThe content expression for this node, as parsed by
ContentExpr.parse. 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.
Each document is based on a single schema, which provides the
node and mark types that it is made up of (which, in turn,
determine the structure it is allowed to have).
Constructor
new Schema(spec:Β SchemaSpec) πConstruct a schema from a specification.
Properties
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.)
Methods
node(type:Β union<string, NodeType>, attrs:Β ?Object, content:Β ?union<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.
When creating a text node, content should be a string and is
interpreted as the node's text.
This method is bound to the Schema, meaning you don't have to
call it as a method, but can pass it to higher-order functions
and such.
text(text:Β string, marks:Β ?[Mark]) βΒ Node πCreate a text node in the schema. This method is bound to the
Schema. Empty text nodes are not allowed.
mark(name:Β string, attrs:Β ?Object) βΒ Mark πCreate a mark with the named type
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.
nodeType(name:Β string) βΒ NodeType πGet the NodeType associated with the given name in
this schema, or raise an error if it does not exist.
registry(namespace:Β string, f:Β fn(name:Β string, value:Β any, source:Β union<NodeType, MarkType>, name:Β string)) πRetrieve all registered items under the given name from this
schema. The given function will be called with the name, each item, the
elementβnode type or mark typeβthat it was associated with, and
that element's name in the schema.
Represents a partial match of a node type's content
expression.
Methods
matchNode(node:Β Node) βΒ ?ContentMatch πMatch a node, returning an updated match if successful.
matchType(type:Β NodeType, attrs:Β ?Object, marks:Β [Mark]) βΒ ?ContentMatch πMatch a node type and marks, returning an updated match if
successful.
matchFragment(fragment:Β Fragment, from:Β ?number = 0, to:Β ?number = fragment.childCount) βΒ ?union<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 (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
type to appear at this position. The result may be empty (when
it fits directly) and will be null when no such wrapping exists.
Extends Block.
The default top-level document node type.
Extends Block.
The default blockquote node type.
Extends Block.
The default ordered list node type. Has a single attribute,
order, which determines the number at which the list starts
counting, and defaults to 1.
Extends Block.
The default bullet list node type.
Extends Block.
The default list item node type.
Extends Block.
The default horizontal rule node type.
Extends Textblock.
The default heading node type. Has a single attribute
level, which indicates the heading level, and defaults to 1.
Properties
maxLevel: number πControls the maximum heading level. Has the value 6 in the
Heading class, but you can override it in a subclass.
Extends Textblock.
The default code block / listing node type. Only
allows unmarked text nodes inside of it.
Extends Textblock.
The default paragraph node type.
Extends Inline.
The default inline image node type. Has these
attributes:
src (required): The URL of the image.
alt: The alt text.
title: The title of the image.
Extends Inline.
The default hard break node type.
Extends MarkType.
The default emphasis mark type.
Extends MarkType.
The default strong mark type.
Extends MarkType.
The default link mark type. Has these attributes:
href (required): The link target.
title: The link's title.
Extends MarkType.
The default code font mark type.
Extends ProseMirrorError.
Error type raised by Node.replace when given an invalid
replacement.
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.
Constructor
new Slice(content:Β Fragment, openLeft:Β number, openRight:Β number, possibleParent:Β ?Node) π
Properties
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.
Methods
toJSON() βΒ ?Object πConvert a slice to a JSON-serializable representation.
Static properties
fromJSON(schema:Β Schema, json:Β ?Object) βΒ Slice πDeserialize a slice from its JSON representation.
empty: Slice πThe empty slice.
The usual way to represent positions in a document is with a
plain integer. Since those tell you very little about the context
of that position, 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.
Properties
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.
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.
Methods
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.
sameDepth(other:Β ResolvedPos) βΒ number πThe depth up to which this position and the other share the same
parent nodes.
sameParent(other:Β ResolvedPos) βΒ bool πQuery whether the given position shares the same parent node.
Functions
findDiffStart(a:Β Node, b:Β Node) βΒ ?number πFind the first position at which nodes a and b differ, or
null if they are the same.
findDiffEnd(a:Β Node, b:Β Node) βΒ ?{a:Β number, b:Β number} πFind the first position, searching from the end, at which nodes a
and b 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.
Constants
defaultSchema: Schema πProseMirror's default document schema.
This module defines a way to transform documents. Transforming
happens in Steps, which are atomic, well-defined modifications to
a document. Applying a step produces a new document
and a position map that maps positions in the old
document to position in the new document. Steps can be
inverted to create a step that undoes their effect,
and chained together in a convenience object called a Transform.
This module does not depend on the browser API being available
(i.e. you can load it into any JavaScript environment).
You can read more about transformations in this
guide.
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, posMap and fromJSON
methods, and registering your class with a unique
JSON-serialization identifier using Step.register.
Methods
apply(doc:Β Node) βΒ ?StepResult πApplies this step to the given document, returning a result
containing the transformed document (the input document is not
changed) and a PosMap. If the step could not meaningfully be
applied to the given document, this returns null.
posMap() βΒ PosMap πGet the position 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 input.
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.
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 properties
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.
register(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.
The result of applying a step. Contains either a
new document or a failure value.
Constructor
new StepResult(doc:Β ?Node, failed:Β ?string) π
Properties
doc: ?Node πThe transformed document.
failed: ?string πA text providing information about a failed step.
Static properties
ok(doc:Β Node) βΒ StepResult πCreate a successful step result.
fail(val:Β string) βΒ StepResult πCreate a failed step result.
fromReplace(doc:Β Node, from:Β number, to:Β number, slice:Β Slice) βΒ StepResult πRun Node.replace, create a successful result if it succeeds,
and a failed one if it throws a ReplaceError.
Extends Step.
Add a mark to all inline content between two positions.
Constructor
new AddMarkStep(from:Β number, to:Β number, mark:Β Mark) π
Extends Step.
Remove a mark from all inline content between two positions.
Constructor
new RemoveMarkStep(from:Β number, to:Β number, mark:Β Mark) π
Extends Step.
Replace a part of the document with a slice of new content.
Constructor
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).
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.
Constructor
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. inset
should be the point in the slice into which the gap should be
moved. structure has the same meaning as it has in the
Replace step.
There are various things that positions can be mapped through.
We'll denote those as 'mappable'. This is not an actual class in
the codebase, only an agreed-on interface.
map(pos:Β number, bias:Β ?number) βΒ number πMap a position through this object. When given, the bias
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.
The return value of mapping a position.
Properties
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.
A position map, holding information about the way positions in
the pre-step version of a document correspond to positions in the
post-step version. This class implements Mappable.
Constructor
new PosMap(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 an [start, oldSize, newSize] chunk.
Methods
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.
invert() βΒ PosMap π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.
A remapping represents a pipeline of zero or more mappings. It
is a specialized data structured used to manage mapping through a
series of steps, typically including inverted and non-inverted
versions of the same step. (This comes up when βrebasingβ steps for
collaboration or history management.) This class implements
Mappable.
Constructor
new Remapping(head:Β ?[PosMap] = [], tail:Β ?[PosMap] = []) π
Properties
head: [PosMap] πThe maps in the head of the mapping are applied to input
positions first, back-to-front. So the map at the end of this
array (if any) is the very first one applied.
Methods
addToFront(map:Β PosMap, corr:Β ?number) βΒ number πAdd a map to the mapping's front. If this map is the mirror image
(produced by an inverted step) of another map in this mapping,
that map's id (as returned by this method or
addToBack) should be passed as a second
parameter to register the correspondence.
addToBack(map:Β PosMap, corr:Β ?number) βΒ number πAdd a map to the mapping's back. If the map is the mirror image
of another mapping in this object, the id of that map should be
passed to register the correspondence.
mapResult(pos:Β number, bias:Β ?number) βΒ MapResult πMap a position through this remapping, returning a mapping
result.
map(pos:Β number, bias:Β ?number) βΒ number πMap a position through this remapping.
A change to a document often consists of a series of
steps. This class provides a convenience abstraction to
build up and track such an array of steps. A Transform object
implements Mappable.
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.
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 πApply a new step in this transformation, returning the step
result.
mapResult(pos:Β number, bias:Β ?number) βΒ MapResult πMap a position through the whole transformation (all the position
maps in maps), and return the result.
map(pos:Β number, bias:Β ?number) βΒ number πMap a position through the whole transformation, and return the
mapped position.
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:Β ?union<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:Β union<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:Β union<Fragment, Node, [Node]>) βΒ Transform πInsert the given content at the given position.
insertText(pos:Β number, text:Β string) βΒ Transform πInsert the given text at pos, inheriting the marks of the
existing content at that position.
insertInline(pos:Β number, node:Β Node) βΒ Transform πInsert the given node at pos, inheriting the marks of the
existing content at that position.
lift(from:Β number, to:Β ?number = from, silent:Β ?bool = false) βΒ Transform πLift the nearest liftable ancestor of the sibling
range of the given positions out of its parent
(or do nothing if no such node exists). When silent is true, this
won't raise an error when the lift is impossible.
wrap(from:Β number, to:Β ?number = from, type:Β NodeType, wrapAttrs:Β ?Object) βΒ Transform πWrap the sibling range of the given positions
in a node of the given type, with the given attributes (if
possible).
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, typeAfter:Β ?NodeType, attrsAfter:Β ?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 part
split off will inherit the node type of the original node. This can
be changed by passing typeAfter and attrsAfter.
join(pos:Β number, depth:Β ?number = 1, silent:Β ?bool = false) βΒ Transform πJoin the blocks around the given position. When silent is true,
the method will return without raising an error if the position
isn't a valid place to join.
canLift(doc:Β Node, from:Β number, to:Β ?number) βΒ bool πTells you whether the range in the given positions' shared
ancestor, or any of its ancestor nodes, can be lifted out of a
parent.
canWrap(doc:Β Node, from:Β number, to:Β ?number, type:Β NodeType, attrs:Β ?Object) βΒ bool πDetermines whether the sibling range of the
given positions can be wrapped in the given node type.
canSplit(doc:Β Node, pos:Β number, depth:Β ?NodeType = 1, typeAfter:Β ?Object) βΒ bool πCheck whether splitting at the given position is allowed.
joinable(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.
This module provides a way to register and access functions that
serialize and parse ProseMirror documents to and from
various formats, along with the basic formats required to run the
editor.
These are the formats defined by this module:
"json"
- Uses
Node.toJSON and Schema.nodeFromJSON to convert a
document to and from JSON.
"dom"
- Parses DOM
Nodes,
serializes to a DOM
fragment.
See
toDOM and fromDOM.
"html"
- Serialize to and parse from HTML text. See
toHTML and fromHTML.
"text"
- Convert to and from plain text. See
toText and fromText.
The markdown module in the distribution defines an additional format:
"markdown"
- Convert to and from CommonMark marked-up
text. See
toMarkdown and fromMarkdown.
To define the way node and mark types are
parsed, you can associate one or more DOM parsing specifications to
them using the register method with the
"parseDOM" namespace, using the HTML node name (lowercase) as
value name. Each of them defines a parsing strategy for a certain
type of DOM node. When "_" is used as name, the parser is
activated for all nodes.
rank: ?number πThe precedence of this parsing strategy. Should be a number between
0 and 100, which determines when this parser gets a chance relative
to others that apply to the node (low ranks go first). Defaults to
parse: union<string, fn(dom:Β DOMNode, state:Β DOMParseState) βΒ ?bool> πThe function that, given a DOM node, parses it, updating the parse
state. It should return (the exact value) false when it wants to
indicate that it was not able to parse this node. This function is
called in such a way that this is bound to the type that the
parse spec was associated with.
When this is set to the string "block", the content of the DOM
node is parsed as the content in a node of the type that this spec
was associated with.
When set to the string "mark", the content of the DOM node is
parsed with an instance of the mark that this spec was associated
with added to their marks.
selector: ?string πA css selector to match against. If present, it will try to match the selector
against the dom node prior to calling the parse function.
A state object used to track context during a parse,
and to expose methods to custom parsing functions.
Properties
options: Object πThe options passed to this parse.
schema: Schema πThe schema that we are parsing into.
Methods
insert(type:Β NodeType, attrs:Β ?Object, content:Β [Node]) βΒ ?Node πInsert a node of the given type, with the given content, based on
dom, at the current position in the document.
wrapIn(dom:Β DOMNode, type:Β NodeType, attrs:Β ?Object) πParse the contents of dom as children of a node of the given
type.
wrapMark(inner:Β DOMNode, mark:Β Mark) πParse the contents of dom, with mark added to the set of
current marks.
Object used to to expose relevant values and methods
to DOM serializer functions.
Properties
options: Object πThe options passed to the serializer.
doc: DOMDocument πThe DOM document in which we are working.
Methods
elt(type:Β string, attrs:Β ?Object, ...content:Β [union<string, DOMNode>]) βΒ DOMNode πCreate a DOM node of the given type, with (optionally) the given
attributes and content. Content elements may be strings (for text
nodes) or other DOM nodes.
renderAs(node:Β Node, tagName:Β string, tagAttrs:Β ?Object) βΒ DOMNode πRender the content of ProseMirror node into a DOM node with the
given tag name and attributes.
serializeTo(doc:Β Node, format:Β string, options:Β ?Object) βΒ any πSerialize the given document to the given format. If options is
given, it will be passed along to the serializer function.
knownTarget(format:Β string) βΒ bool πQuery whether a given serialization format has been registered.
defineTarget(format:Β string, func:Β fn(Node, ?Object) βΒ any) πRegister a function as the serializer for format.
parseFrom(schema:Β Schema, value:Β any, format:Β string, options:Β ?Object) βΒ Node πParse document value from the format named by format. If
options is given, it is passed along to the parser function.
knownSource(format:Β string) βΒ bool πQuery whether a parser for the named format has been registered.
defineSource(format:Β string, func:Β fn(Schema, any, ?Object) βΒ Node) πRegister a parser function for format.
fromDOM(schema:Β Schema, dom:Β DOMNode, options:Β ?Object) βΒ Node πParse document from the content of a DOM node. To pass 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.
fromHTML(schema:Β Schema, html:Β string, options:Β ?Object) βΒ Node πParses the HTML into a DOM, and then calls through to fromDOM.
toDOM(content:Β union<Node, Fragment>, options:Β ?Object) βΒ DOMFragment πSerialize the given content 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.
To define rendering behavior for your own node and
mark types, give them a serializeDOM method. This
method is passed a Node and a DOMSerializer, and should return
the DOM
node that
represents this node and its content. For marks, that should be an
inline wrapping node like <a> or <strong>.
Individual attributes can also define serialization behavior. If an
Attribute object has a serializeDOM method, that will be called
with the DOM node representing the node that the attribute applies
to and the atttribute's value, so that it can set additional DOM
attributes on the DOM node.
nodeToDOM(node:Β Node, options:Β ?Object) βΒ DOMNode πSerialize a given node to a DOM node. This is useful when you need
to serialize a part of a document, as opposed to the whole
document.
toHTML(content:Β union<Node, Fragment>, options:Β ?Object) βΒ string πSerialize a node as an HTML string. Goes through toDOM and then
serializes the result. Again, you must pass a document option
when not in the browser.
fromText(schema:Β Schema, text:Β string) βΒ Node πConvert a string into a simple ProseMirror document.
toText(content:Β union<Node, Fragment>) βΒ string πSerialize content as a plain text string.
Defines a parser and serializer for
CommonMark text (registered in the
format module under "markdown").
Schema-specific parsing logic can be defined
registering values with parsing information
on mark and node types, using the
"parseMarkdown" namespace.
The name of the registered item should be the
markdown-it token
name that the parser should respond to,
To influence the way the markdown-it parser is initialized and
configured, you can register values under the "configureMarkdown"
namespace. An item with the name "init" will be called to
initialize the parser. Items with other names will be called with a
parser and should return a parser. You could for example configure
a subscript mark to enable the subscript
plugin:
SubMark.register("configureMarkdown", "sub", parser => {
return parser.use(require("markdown-it-sub"))
})
parse: union<string, fn(state:Β MarkdownParseState, token:Β MarkdownToken) βΒ Node> πThe parsing function for this token. It is, when a matching token
is encountered, passed the parsing state and the token, and must
return a Node if the parsing spec was for a node type, and a
Mark if it was for a mark type.
The function will be called so that this is bound to the node or
mark type instance that the spec was associated with.
As a shorthand, parse can be set to a string. You can use
"block" to create a node of the type that this spec was
associated with, and wrap the content between the open and close
tokens in this node.
Alternatively, it can be set to "mark", if the spec is associated
with a mark type, which will cause the content between
the opening and closing token to be marked with an instance of that
mark type.
attrs: ?union<Object, fn(MarkdownParseState, MarkdownToken) βΒ Object> πWhen parse is set to a string, this property can be used to
specify attributes for the node or mark. It may hold an object or a
function that, when called with the parser
state and the token object, returns an
attribute object.
Object used to track the context of a running parse,
and to expose parsing-related methods to node-specific parsing
functions.
Properties
schema: Schema πThe schema into which we are parsing.
options: Object πThe options passed to the parser.
Methods
addText(text:Β string) πAdds the given text to the current position in the document,
using the current marks as styling.
openMark(mark:Β Mark) πAdds the given mark to the set of active marks.
closeMark(mark:Β Mark) πRemoves the given mark from the set of active marks.
addNode(type:Β NodeType, attrs:Β ?Object, content:Β ?[Node]) βΒ ?Node πAdd a node at the current position.
openNode(type:Β NodeType, attrs:Β ?Object) πWrap subsequent content in a node of the given type.
closeNode() βΒ ?Node πClose and return the node that is currently on top of the stack.
getAttr(tok:Β MarkdownToken, name:Β string) βΒ any πRetrieve the named attribute from the given token.
This is an object used to track state and expose
methods related to markdown serialization. Instances are passed to
node and mark serialization methods (see toMarkdown).
Properties
options: Object πThe options passed to the serializer. The following are supported:
hardBreak: ?string
- Markdown to use for hard line breaks. Defaults to a backslash
followed by a newline.
Methods
wrapBlock(delim:Β string, firstDelim:Β ?string, node:Β Node, f:Β fn()) πRender a block, prefixing each line with delim, and the first
line in firstDelim. node should be the node that is closed at
the end of the block, and f is a function that renders the
content of the block.
ensureNewLine() πEnsure the current content ends with a newline.
write(content:Β ?string) πPrepare the state for writing output (closing closed paragraphs,
adding delimiters, and so on), and then optionally add content
(unescaped) to the output.
closeBlock(node:Β Node) πClose the block for the given node.
text(text:Β string, escape:Β ?bool) πAdd the given text to the document. When escape is not false,
it will be escaped.
render(node:Β Node) πRender the given node as a block.
renderContent(parent:Β Node) πRender the contents of parent as block nodes.
renderInline(parent:Β Node) πRender the contents of parent as inline content.
esc(str:Β string, startOfLine:Β ?bool) βΒ string πEscape the given string so that it can safely appear in Markdown
content. If startOfLine is true, also escape characters that
has special meaning only at the start of the line.
repeat(str:Β string, n:Β number) βΒ string πRepeat the given string n times.
Functions
fromMarkdown(schema:Β Schema, text:Β string, options:Β ?Object) βΒ Node πParse a string as CommonMark markup, and
create a ProseMirror document corresponding to its meaning. Note
that, by default, some CommonMark features, namely inline HTML and
tight lists, are not supported.
toMarkdown(doc:Β Node, options:Β ?Object) βΒ string πSerialize the content of the given node to CommonMark.
To define serialization behavior for your own node
types, give them a serializeMarkDown method. It will
be called with a MarkdownSerializer and a Node, and should
update the serializer's state to add the content of the node.
Mark types can define openMarkdown and
closeMarkdown properties, which provide the markup text that
marked content should be wrapped in. They may hold either a string
or a function from a MarkdownSerializer and a Mark to a string.
This module defines a way to attach β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 with the
autoInput option.
autoInput: union<bool, [union<string, Object<?InputRule>>]> πControls the input rules initially active in the
editor. Pass an array of sources, which can be either the string
"schema", to add rules registered on the
schema items (under the namespace "autoInput"), or an object
containing input rules. To remove previously included rules, you
can add an object that maps their name to null.
The value false (the default) is a shorthand for no input rules,
and the value true for ["schema", autoInputRules].
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, filter:Β ?string, handler:Β union<string, fn(pm:Β ProseMirror, match:Β [string], pos:Β number)>) π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 $. You can optionally
provide a filter, which should be a single character that always
appears at the end of the match, and will be used to only apply
the rule when there's an actual chance of it succeeding.
The handler can be a string, in which case the matched text
will simply be replaced by that string, or a function, which will
be called with the match array produced by
RegExp.exec,
and should produce the effect of the rule.
addInputRule(pm:Β ProseMirror, rule:Β InputRule) πAdd the given input rule to an editor. From now on,
whenever the rule's pattern is typed, its handler is activated.
Note that the effect of an input rule can be canceled by pressing
Backspace right after it happens.
removeInputRule(pm:Β ProseMirror, rule:Β InputRule) πRemove the given rule (added earlier with addInputRule) from the
editor.
autoInputRules: Object<InputRule> πBase set of input rules, enabled by default when autoInput is set
to true.
When given a truthy value, enables the menu bar module for this
editor. The menu bar takes up space above the editor, showing
currently available commands (that have been
added to the menu). To configure the
module, you can pass a configuration object, on which the following
properties are supported:
float: bool = false
- When enabled, causes the menu bar to stay visible when the
editor is partially scrolled out of view, by making it float at
the top of the viewport.
content: [MenuGroup]
- Determines the content of the menu.
When given a truthy value, enables the tooltip menu module for this
editor. This menu shows up when there is a selection, and
optionally in certain other circumstances, providing
context-relevant commands.
By default, the tooltip will show inline menu commands (registered
with the menuGroup command property)
when there is an inline selection, and block related commands when
there is a node selection on a block.
The module can be configured by passing an object. These properties
are recognized:
showLinks: bool = true
- Causes a tooltip with the link target to show up when the
cursor is inside of a link (without a selection).
selectedBlockMenu: bool = false
- When enabled, and a whole block is selected or the cursor is
inside an empty block, the block menu gets shown.
inlineContent: [MenuGroup]
- The menu elements to show when displaying the menu for inline
content.
blockContent: [MenuGroup]
- The menu elements to show when displaying the menu for block
content.
selectedBlockContent: [MenuGroup]
- The elements to show when a full block has been selected and
selectedBlockMenu is enabled. Defaults to concatenating
inlineContent and blockContent.
position: string
- Where, relative to the selection, the tooltip should appear.
Defaults to
"above". Can also be set to "below".
This module defines a number of building blocks for ProseMirror
menus, as consumed by the menubar and
tooltipmenu modules.
The types defined in this module aren't the only thing you can
display in your menu. Anything that conforms to this interface can
be put into a menu structure.
Render the element for display in the menu. Returning null can be
used to signal that this element shouldn't be displayed for the
given editor state.
A menu group represents a group of things that may appear in a
menu. It may be either a MenuElement, a MenuCommandGroup, or an
array of such values. Can be reduced to an array of MenuElements
using resolveGroup.
Wraps a command so that it can be rendered in a
menu.
Constructor
new MenuCommand(command:Β union<Command, string>, options:Β MenuCommandSpec) π
Methods
command(pm:Β ProseMirror) βΒ Command πRetrieve the command associated with this object.
render(pm:Β ProseMirror) βΒ DOMNode πRenders the command according to its display
spec, and adds an event handler which
executes the command when the representation is clicked.
Represents a group of commands, as
they appear in the editor's schema.
Constructor
new MenuCommandGroup(name:Β string, options:Β ?MenuCommandSpec) πCreate a group for the given group name, optionally adding or
overriding fields in the commands' specs.
Methods
get(pm:Β ProseMirror) βΒ [MenuCommand] πGet the group of matching commands in the given editor.
A drop-down menu, displayed as a label with a downwards-pointing
triangle to the right of it.
Constructor
new Dropdown(options:Β Object, content:Β MenuGroup) πCreate a dropdown wrapping the given group. Options may include
the following properties:
label: string
- The label to show on the drop-down control. When
activeLabel is also given, this one is used as a
fallback.
activeLabel: bool
- Instead of showing a fixed label, enabling this causes the
element to search through its content, looking for an
active command. If one is found, its
activeLabel property is
shown as the drop-down's label.
title: string
- Sets the
title
attribute given to the menu control.
class: string
- When given, adds an extra CSS class to the menu control.
Methods
render(pm:Β ProseMirror) βΒ DOMNode πReturns a node showing the collapsed menu, which expands when clicked.
Represents a submenu wrapping a group of items that start hidden
and expand to the right when hovered over or tapped.
Creates a submenu for the given group of menu elements. The
following options are recognized:
label: string
- The label to show on the submenu.
Renders the submenu.
The menu module gives meaning to an additional property in
command specs.
menu: MenuCommandSpec πAdds the command to a menu group, so that it is picked up by
MenuCommandGroup objects with the matching
name.
Configures the way a command shows up in a menu, when wrapped in a
MenuCommand.
group: string πIdentifies the group this command should be added to (for example
"inline" or "block"). Only meaningful when associated with a
CommandSpec (as opposed to passed directly to MenuCommand).
rank: number πDetermines the command's position in its group (lower ranks come
first). Only meaningful in a CommandSpec.
display: Object πDetermines how the command is shown in the menu. It may have either
a type property containing one of the strings shown below, or a
render property that, when called with the command and a
ProseMirror instance as arguments, returns a DOM node
representing the command's menu representation.
"icon"
- Show the command as an icon. The object may have
{path, width, height} properties, where path is an SVG path
spec,
and width and height provide the viewbox in which that path
exists. Alternatively, it may have a text property specifying
a string of text that makes up the icon, with an optional
style property giving additional CSS styling for the text,
or a dom property containing a DOM node.
"label"
- Render the command as a label. Mostly useful for commands
wrapped in a drop-down or similar menu. The object
should have a
label property providing the text to display.
activeLabel: string πWhen used in a Dropdown with activeLabel enabled, this should
provide the text shown when the command is active.
select: string πControls whether the command's select
method has influence on its appearance. When set to "hide", or
not given, the command is hidden when it is not selectable. When
set to "ignore", the select method is not called. When set to
"disable", the command is shown in disabled form when select
returns false.
class: string πOptionally adds a CSS class to the command's DOM representation.
css: string πOptionally adds a string of inline CSS to the command's DOM
representation.
execEvent: string πDefines which event on the command's DOM representation should
trigger the execution of the command. Defaults to mousedown.
resolveGroup(pm:Β ProseMirror, content:Β MenuGroup) βΒ [MenuElement] πResolve the given MenuGroup into a flat array of renderable
elements.
renderGrouped(pm:Β ProseMirror, content:Β [MenuGroup]) βΒ ?DOMFragment πRender the given menu groups into a document fragment, placing
separators between them (and ensuring no superfluous separators
appear when some of the groups turn out to be empty).
inlineGroup: MenuCommandGroup πThe inline command group.
The default insert dropdown menu.
The default textblock type menu.
blockGroup: MenuCommandGroup πThe block command group.
historyGroup: MenuCommandGroup πThe history command group.
The ui/prompt module implements functionality for prompting
the user for command parameters.
The default implementation gets the job done, roughly, but you'll
probably want to customize it in your own system (or submit patches
to improve this implementation).
This class represents a dialog that prompts for command
parameters. It is the default value of the
commandParamPrompt option. You can set this option to a subclass
(or a complete reimplementation) to customize the way in which
parameters are read.
Constructor
new ParamPrompt(pm:Β ProseMirror, command:Β Command) πConstruct a prompt. Note that this does not
open it yet.
Properties
pm: ProseMirror πcommand: Command πfields: [DOMNode] πAn array of fields, as created by ParamTypeSpec.render, for
the command's parameters.
form: DOMNode πAn HTML form wrapping the fields.
paramTypes: Object<ParamTypeSpec> πA collection of default renderers and readers for parameter
types, which parameter
handlers can optionally use to prompt for
parameters. render should create a form field for the parameter,
and read should, given that field, return its value.
Methods
close() πClose the prompt.
open() πOpen the prompt's dialog.
values() βΒ ?[any] πRead the values from the form's field. Validate them, and when
one isn't valid (either has a validate function that produced an
error message, or has no validate function, no value, and no
default value), show the problem to the user and return null.
defaultValue(param:Β CommandParam) βΒ ?any πGet a parameter's default value, if any.
prompt() βΒ {close:Β fn()} πOpen a prompt with the parameter form in it. The default
implementation calls openPrompt.
reportInvalid(dom:Β DOMNode, message:Β string) πReport a field as invalid, showing the given message to the user.
By default, the prompting interface only knows how to prompt for
parameters of type text and select. You can change the way
those are prompted for, and define new types, by writing to
ParamPrompt.paramTypes. All methods on these specs will be called
with this bound to the relevant ProseMirror instance.
render(param:Β CommandParam, value:Β ?any) βΒ DOMNode πCreate the DOM structure for a parameter field of this type, and
pre-fill it with value, if given.
read(field:Β DOMNode) βΒ any πRead the value from the DOM field created by
render.
validate(field:Β DOMNode) βΒ ?string πOptional. Validate the value in the given field, and return a
string message if it is not a valid input for this type.
reportInvalid(field:Β DOMNode, message:Β string) πReport the value in the given field as invalid, showing the given
error message. This property is optional, and the prompt
implementation will fall back to its own method of showing the
message when it is not provided.
Functions
openPrompt(pm:Β ProseMirror, content:Β DOMNode, options:Β ?Object) βΒ {close:Β fn()} πOpen a dialog box for the given editor, putting content inside of
it. The close method on the return value can be used to
explicitly close the dialog again. The following options are
supported:
pos: {left: number, top: number}
- Provide an explicit position for the element. By default, it'll
be placed in the center of the editor.
onClose: fn()
- A function to be called when the dialog is closed.
Used to show tooltips. An instance of this class is a persistent
DOM node (to allow position and opacity animation) that can be
shown and hidden. It is positioned relative to a position (passed
when showing the tooltip), and points at that position with a
little arrow-like triangle attached to the node.
new Tooltip(wrapper:Β DOMNode, options:Β union<string, Object>) πCreate a new tooltip that lives in the wrapper node, which should
be its offset anchor, i.e. it should have a relative or
absolute CSS position. You'll often want to pass an editor's
wrapper node. options may be an object
containg a direction string and a getBoundingRect function which
should return a rectangle determining the space in which the tooltip
may appear. Alternatively, options may be a string specifying the
direction. The direction can be "above", "below", "right",
"left", or "center". In the latter case, the tooltip has no arrow
and is positioned centered in its wrapper node.
detach() πRemove the tooltip from the DOM.
open(node:Β DOMNode, pos:Β ?{left:Β number, top:Β number}) πMake the tooltip visible, show the given node in it, and position
it relative to the given position. If pos is not given, the
tooltip stays in its previous place. Unless the tooltip's
direction is "center", pos should definitely be given the
first time it is shown.
close() πClose (hide) the tooltip.
Helper for scheduling updates whenever any of a series of events
happen.
Constructor
new UpdateScheduler(pm:Β ProseMirror, events:Β string, start:Β fn() βΒ ?fn()) πCreates an update scheduler for the given editor. events should
be a space-separated list of event names (for example
"selectionChange change"). start should be a function as
expected by scheduleDOMUpdate.
Methods
detach() πDetach the event handlers registered by this scheduler.
force() πForce an update. Note that if the editor has scheduled a flush,
the update is still delayed until the flush occurs.
Functions
scheduleDOMUpdate(pm:Β ProseMirror, f:Β fn() βΒ ?fn() βΒ ?fn()) πSchedule a DOM update function to be called either the next time
the editor is flushed, or if no flush happens
immediately, after 200 milliseconds. This is used to synchronize
DOM updates and read to prevent DOM layout
thrashing.
Often, your updates will need to both read and write from the DOM.
To schedule such access in lockstep with other modules, the
function you give can return another function, which may return
another function, and so on. The first call should write to the
DOM, and not read. If a read needs to happen, that should be
done in the function returned from the first call. If that has to
be followed by another write, that should be done in a function
returned from the second function, and so on.
unscheduleDOMUpdate(pm:Β ProseMirror, f:Β fn() βΒ ?fn() βΒ ?fn()) πCancel an update scheduled with scheduleDOMUpdate. Calling this with
a function that is not actually scheduled is harmless.
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.
Options
collab: ?Object πWhen given, enables the collaborative editing framework for the
editor. Will register itself of the Collab class as
.mod.collab.
If the object given has a version property, that will determine
the starting version number of the collaborative editing.
This class accumulates changes that have to be sent to the
central authority in the collaborating group, signals an event when
it has something to send, and makes it possible to integrate
changes made by peers into our local document. It is created and
attached to the editor (under .mod.collab) by setting the
collab option.
Includes the event mixin.
Properties
version: number πThe version number of the last update received from the central
authority. Starts at 0 or the value of the version property
in the option object, for the editor's value when the option
was enabled.
Methods
hasSendableSteps() βΒ bool πReports whether the editor has any unsent steps.
sendableSteps() βΒ {version:Β number, steps:Β [Step]} πProvides the data describing the editor's unconfirmed steps. The
version and array of steps are the things you'd send to the
central authority. The whole return value must be passed to
confirmSteps when the steps go through.
receive(steps:Β [Step], clientIDs:Β [number]) βΒ [PosMap] πPushes a set of steps (received from the central authority) into
the editor. Will recognize its own changes, and confirm
unconfirmed steps as appropriate. Remaining unconfirmed steps
will be rebased over remote steps.
Returns the position maps produced by applying the
steps.
Events
mustSend() πFired when there are new steps to send to the central
authority. Consumers should respond by calling
sendableSteps and pushing those to the authority.
collabTransform(transform:Β Transform, selectionBeforeTransform:Β Selection) πSignals that a transformation has been aplied to the editor. Passes the Transform and the selection
before the transform as arguments to the handler.
Persistent data structure representing an ordered mapping from
strings to values, with some convenient update methods.
Properties
size: number πThe amount of keys in this map.
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.
forEach(f:Β fn(key:Β string, value:Β any)) πCall the given function for each key/value pair in the map, in
order.
prepend(map:Β union<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:Β union<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:Β union<Object, OrderedMap>) βΒ OrderedMap πCreate a map containing all the keys in this map that don't
appear in map.
Static properties
from(value:Β ?union<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.
A set of methods for objects that emit events. Added by calling
eventMixin on a constructor.
on(type:Β string, handler:Β fn(...args:Β [any])) πRegister an event handler for the given event type.
off(type:Β string, handler:Β fn(...args:Β [any])) πUnregister an event handler for the given event type.
signal(type:Β string, ...args:Β [any]) πSignal an event of the given type, passing any number of
arguments. Will call the handlers for the event, passing them the
arguments.
signalHandleable(type:Β string, ...args:Β [any]) βΒ any πSignal a handleable event of
the given type. All handlers for the event will be called with
the given arguments, until one of them returns something that is
not the value null or undefined. When that happens, the
return value of that handler is returned. If that does not
happen, undefined is returned.
signalPipelined(type:Β string, value:Β any) βΒ any πGive all handlers for an event a chance to transform a value. The
value returned from a handler will be passed to the next handler.
The method returns the value returned by the final handler (or
the original value, if there are no handlers).
hasHandler(type:Β string) βΒ bool πQuery whether there are any handlers for this event type.
Functions
eventMixin(ctor:Β fn()) πAdd the methods in the EventMixin interface to the prototype
object of the given constructor.
Constants
methods
Constructor
new ProseMirrorError(message:Β any) πSuperclass for ProseMirror-related errors. Does some magic to
make it safely subclassable even on ES5 runtimes.