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.
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:Β Pos, head:Β ?Pos)
πSet the selection to a text selection from
anchor
to head
, or, if head
is null, a cursor selection at
anchor
.
setNodeSelection(pos:Β Pos)
π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) βΒ 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.
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:Β Pos, 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()
π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.
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:Β Pos, to:Β Pos, 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}) βΒ ?Pos
π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:Β Pos) βΒ {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:Β ?Pos = 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.
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.
textInput()
πFired when the user types text into the editor.
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. Handlers must return the given
string or a transformed version of
it.
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.
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.
Extends ProseMirrorError
.
Error type used to signal selection-related problems.
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: Pos
πThe left-bound of the selection.
to: Pos
πThe right-bound of the selection.
Static properties
empty: bool
πTrue if the selection is an empty text selection (head an anchor
are the same).
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:Β Pos, head:Β ?Pos)
πConstruct a text selection. When head
is not given, it defaults
to anchor
.
Properties
anchor: Pos
πThe selection's immobile side (does not move when pressing
shift-arrow).
head: Pos
π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:Β Pos, to:Β Pos, 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: ?Pos
π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: ?Pos
π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:Β Pos, to:Β Pos)
π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, path:Β [number], dom:Β DOMNode, coords:Β {left:Β number, top:Β number}) βΒ ?Pos
π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, path:Β [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, path:Β [number], node:Β Node) βΒ bool
πThis works like handleClick
, but is
called for double clicks instead.
handleContextMenu(pm:Β ProseMirror, event:Β MouseEvent, path:Β [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.
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
selectNodeLeft
πSelect the node directly before the cursor, if any.
Keybindings: Left, Mod-Left
selectNodeRight
πSelect the node directly after the cursor, if any.
Keybindings: Right, Mod-Right
selectNodeUp
πSelect the node directly above the cursor, if any.
Keybindings: Up
selectNodeDown
πSelect the node directly below the cursor, if any.
Keybindings: Down
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-Mod-8
ordered_list:wrap
πWrap the selection in an ordered list.
Keybindings: Shift-Mod-8
blockquote:wrap
πWrap the selection in a block quote.
Keybindings: Shift-Mod-.
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
:heading::make_
πThe commands make1
to make6
set the textblocks in the
selection to become headers with the given level.
Keybindings: Shift-Mod-1 through Shift-Mod-6
paragraph:make
πSet the textblocks in the selection to be regular paragraphs.
Keybindings: Shift-Mod-0
code_block:make
πSet the textblocks in the selection to be code blocks.
Keybindings: Shift-Mod-\
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:
-
The node type that represents document elements
-
The schema types used to tag and constrain the
document structure
-
The data type for document positions
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.
size: number
πThe size of the node's content, which is the maximum offset in
the node. For nodes that don't contain text, this is also the
number of child nodes that the node has.
width: number
πThe width of this node. Always 1 for non-text nodes, and the
length of the text for text nodes.
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(off:Β number) βΒ Node
πRetrieve the child at the given offset. Note that this is not
the appropriate way to loop over a node. child
's complexity may
be non-constant for some nodes, and it will return the same node
multiple times when calling it for different offsets within a
text node.
iter(start:Β ?number, end:Β ?number) βΒ Iterator<Node>
πCreate an iterator over this node's children, optionally starting
and ending at a given offset.
reverseIter(start:Β ?number, end:Β ?number) βΒ Iterator<Node>
πCreate a reverse iterator (iterating from the node's end towards
its start) over this node's children, optionally starting and
ending at a given offset. Note: if given, start
should be
greater than (or equal) to end
.
chunkBefore(off:Β number) βΒ {start:Β number, node:Β Node}
πFind the node that sits before a given offset. Can be used to
find out which text node covers a given offset. The start
property of the return value is the starting offset of the
returned node. It is an error to call this with offset 0.
chunkAfter(off:Β number) βΒ {start:Β number, node:Β Node}
πFind the node that sits after a given offset. The start
property of the return value is the starting offset of the
returned node. It is an error to call this with offset
corresponding to the end of the node.
forEach(f:Β fn(node:Β Node, start:Β number, end:Β number))
πCall the given function for each child node. The function will be
given the node, as well as its start and end offsets, as
arguments.
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.
slice(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.
splice(from:Β number, to:Β number, replace:Β Fragment) βΒ Node
πCreate a copy of this node with the content between the given
offsets replaced by the given fragment.
append(fragment:Β Fragment, joinLeft:Β ?number = 0, joinRight:Β ?number = 0) βΒ Node
πAppend the given fragment to this node's
content, and create a new node with the result.
replace(pos:Β number, node:Β Node) βΒ Node
πReturn a copy of this node with the child at the given offset
replaced by the given node. Note: The offset should not fall
within a text node.
replaceDeep(path:Β [number], node:Β Node) βΒ Node
πReturn a copy of this node with the descendant at path
replaced
by the given replacement node. This will copy as many sub-nodes as
there are elements in path
.
close(depth:Β number, side:Β string) βΒ Node
πβCloseβ this node by making sure that, if it is empty, and is not
allowed to be so, it has its default content inserted. When depth
is greater than zero, sub-nodes at the given side (which can be
"start"
or "end"
) are closed too. Returns itself if no work
is necessary, or a closed copy if something did need to happen.
path(path:Β [number]) βΒ Node
πGet the descendant node at the given path, which is interpreted
as a series of offsets into successively deeper nodes. For example,
if a node contains a paragraph and a list with 3 items, the path
to the first item in the list would be [1, 0].
nodeAfter(pos:Β Pos) βΒ ?Node
πGet the node after the given position, if any.
pathNodes(path:Β [number]) βΒ [Node]
πGet an array of all nodes along a path.
siblingRange(from:Β Pos, to:Β Pos) βΒ {from:Β Pos, to:Β Pos}
πFinds the narrowest sibling range (two positions that both point
into the same node) that encloses the given positions.
nodesBetween(from:Β ?Pos, to:Β ?Pos, f:Β fn(node:Β Node, path:Β [number], parent:Β Node))
πIterate over all nodes between the given two positions, calling
the callback with the node, the path towards it, and its parent
node, as arguments. from
and to
may be null
to denote
starting at the start of the node or ending at its end. Note that
the path passed to the callback is mutated as iteration
continues, so if you want to preserve it, make a copy.
inlineNodesBetween(from:Β ?Pos, to:Β ?Pos, f:Β fn(node:Β Node, path:Β [number], start:Β number, end:Β number, parent:Β Node))
πCalls the given function for each inline node between the two
given positions. Pass null for from
or to
to start or end at
the start or end of the node.
sliceBetween(from:Β ?Pos, to:Β ?Pos) βΒ Node
πReturns a copy of this node containing only the content between
from
and to
. You can pass null
for either of them to start
or end at the start or end of the node.
marksAt(pos:Β Pos) βΒ [Mark]
πGet the marks of the node before the given position or, if that
position is at the start of a non-empty node, those of the node
after it.
rangeHasMark(from:Β ?Pos, to:Β ?Pos, 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.
toJSON() βΒ Object
πReturn a JSON-serializeable representation of this node.
[Symbol.iterator]() βΒ Iterator<Node>
πA fragment is iterable, in the ES6 sense.
Static properties
fromJSON(schema:Β Schema, json:Β Object) βΒ Node
πDeserialize a node from its JSON representation.
A fragment is an abstract type used to represent a node's
collection of child nodes. It tries to hide considerations about
the actual way in which the child nodes are stored, so that
different representations (nodes that only contain simple nodes
versus nodes that also contain text) can be approached using the
same API.
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.
size: number
πThe maximum offset in this fragment.
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.
Methods
append(other:Β Fragment, joinLeft:Β ?number = 0, joinRight:Β ?number = 0) βΒ Fragment
πCreate a fragment that combines this one with another fragment.
Takes care of merging adjacent text nodes and can also merge
βopenβ nodes at the boundary. joinLeft
and joinRight
give the
depth to which the left and right fragments are open. If open
nodes with the same markup are found on both sides, they are
joined. If not, the open nodes are closed.
toString() βΒ string
πReturn a debugging string that describes this fragment.
toArray(from:Β ?number = 0, to:Β ?number = this.size, f:Β ?fn(Node) βΒ Node) βΒ [Node]
πProduce an array with the child nodes between the given
boundaries, optionally mapping a function over them.
map(f:Β fn(Node) βΒ Node) βΒ Fragment
πProduce a new Fragment by mapping all this fragment's children
through a function.
some(f:Β fn(Node) βΒ bool) βΒ ?Node
πReturns the first child node for which the given function returns
true
, or undefined otherwise.
sliceBetween(from:Β ?Pos, to:Β ?Pos) βΒ Fragment
πSlice out the sub-fragment between the two given positions.
null
can be passed for either to indicate the slice should go
all the way to the start or end of the fragment.
iter(start:Β ?number = 0, end:Β ?number = this.size) βΒ Iterator<Node>
πCreate a forward iterator over the content of the fragment. An
explicit start and end offset can be given to have the iterator
go over only part of the content. If an iteration bound falls
within a text node, only the part that is within the bounds is
yielded.
reverseIter(start:Β ?number = this.size, end:Β ?number = 0) βΒ Iterator<Node>
πCreate a reverse iterator over the content of the fragment. An
explicit start and end offset can be given to have the iterator
go over only part of the content. Note: start
should be
greater than end
, when passed.
child(off:Β number) βΒ Node
πGet the child at the given offset. Might return a text node that
stretches before and/or after the offset.
forEach(f:Β fn(node:Β Node, start:Β number, end:Β number))
πCall the given function for each node in the fragment, passing it
the node, its start offset, and its end offset.
chunkBefore(off:Β number) βΒ {start:Β number, node:Β Node}
πFind the node before the given offset. Returns an object
containing the node as well as its start index. Offset should be
greater than zero.
chunkAfter(off:Β number) βΒ {start:Β number, node:Β Node}
πFind the node after the given offset. Returns an object
containing the node as well as its start index. Offset should be
less than the fragment's size.
slice(from:Β number, to:Β ?number = this.size) βΒ Fragment
πReturn a fragment with only the nodes between the given offsets.
When to
is not given, the slice will go to the end of the
fragment.
replace(offset:Β number, node:Β Node) βΒ Fragment
πReturn a fragment in which the node at the given offset is
replaced by the given node. The node, as well as the one it
replaces, should not be text nodes.
toJSON() βΒ Object
πCreate a JSON-serializeable representation of this fragment.
[Symbol.iterator]() βΒ Iterator<Node>
πA fragment is iterable, in the ES6 sense.
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.
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.
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.
Instances of the Pos
class represent positions in a document.
A position is an array of integers that describe a path to the target
node (see Node.path
) and an integer offset into that target node.
Constructor
new Pos(path:Β [number], offset:Β number)
π
Properties
path: [number]
πThe path to the target node.
offset: number
πThe offset into the target node.
depth: number
πThe length of the position's path.
Methods
toString()
πReturn a string representation of the path of the form
"0/2:10"
, where the numbers before the colon are the path, and
the number after it is the offset.
max(other:Β Pos) βΒ Pos
πReturn the greater of two positions.
min(other:Β Pos) βΒ Pos
πReturn the lesser of two positions.
cmp(other:Β Pos) βΒ number
πCompares this position to another position, and returns a number.
Of this result number, only the sign is significant. It is
negative if this position is less than the other one, zero if
they are the same, and positive if this position is greater.
shorten(to:Β ?number = null, offset:Β ?number = 0) βΒ Pos
πCreate a position pointing into a parent of this position's
target. When to
is given, it determines the new length of the
path. By default, the path becomes one shorter. The offset
parameter can be used to determine where in this parent the
position points. By default, it points before the old target. You
can pass a negative or positive integer to move it backward or
forward (note: this method performs no bounds checking).
move(by:Β number) βΒ Pos
πCreate a position with an offset moved relative to this
position's offset. For example moving 0/1:10
by -2
yields
0/1:8
.
toPath(move:Β ?number = 0) βΒ [number]
πConvert this position to an array of numbers (including its
offset). Optionally pass an argument to adjust the value of the
offset.
isValid(doc:Β Node, requireTextblock:Β ?bool) βΒ bool
πChecks whether this position is valid in the given document. When
requireTextblock
is true, only positions inside textblocks are
considered valid.
toJSON() βΒ Object
πConvert the position to a JSON-safe representation.
Static properties
samePath(pathA:Β [number], pathB:Β [number]) βΒ bool
πCompares two paths and returns true when they are the same.
from(array:Β [number], move:Β ?number = 0) βΒ Pos
πBuild a position from an array of numbers (as in
toPath
), taking the last element of the array as
offset and optionally moving it by move
.
fromJSON(json:Β Object) βΒ Pos
πCreate a position from a JSON representation.
Extends ProseMirrorError
.
The exception type used to signal schema-related
errors.
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.
contains: ?NodeKind
πThe kind of nodes this node may contain. null
means it's a
leaf node.
kind: ?NodeKind
πSets the kind of the node, which is used to
determine valid parent/child relations.
Should only be null
for nodes that can't be child nodes (i.e.
the document top node).
canBeEmpty: bool
πControls whether this node is allowed to be empty.
containsMarks: union<bool, [string]>
πThe mark types that child nodes of this node may have. false
means no marks, true
means any mark, and an array of strings
can be used to explicitly list the allowed mark types.
Methods
canContainFragment(fragment:Β Fragment) βΒ bool
πTest whether the content of the given fragment could be contained
in this node type.
canContain(node:Β Node) βΒ bool
πTest whether the given node could be contained in this node type.
canContainMark(mark:Β MarkType) βΒ bool
πTest whether this node type can contain children with the given
mark type.
canContainType(type:Β NodeType) βΒ bool
πTest whether this node type can contain nodes of the given node
type.
canContainContent(type:Β NodeType) βΒ bool
πTest whether the nodes that can be contained in the given node
type are a sub-type of the nodes that can be contained in this
type.
findConnection(other:Β NodeType) βΒ ?[NodeType]
πFind a set of intermediate node types, possibly empty, that have
to be inserted between this type and other
to put a node of
type other
into this type.
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.
Class used to represent node kind.
Constructor
new NodeKind(name:Β string, supers:Β ?[NodeKind], subs:Β ?[NodeKind])
πCreate a new node kind with the given set of superkinds (the new
kind counts as a member of each of the superkinds) and subkinds
(which will count as a member of this new kind). The name
field
is only for debugging purposesβkind equivalens is defined by
identity.
Methods
isSubKind(other:Β NodeKind) βΒ bool
πTest whether other
is a subkind of this kind (or the same
kind).
Static properties
block: NodeKind
πThe node kind used for generic block nodes.
inline: NodeKind
πThe node kind used for generic inline nodes.
text: NodeKind
πThe node kind used for text nodes. Subkind of
NodeKind.inline
.
list_item: NodeKind
πThe node kind used for list items in the default
schema.
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 strings 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.
Constructor
new Attribute(options:Β ?Object = {})
πCreate an attribute. options
is an object containing the
settings for the attributes. The following settings are
supported:
default
: ?string
- The default value for this attribute, to choose when no
explicit value is provided.
compute
: ?(Fragment) β string
- 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.
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.
Static properties
rank: number
πMark type ranks are used to determine the order in which mark
arrays are sorted. (If multiple mark types end up with the same
rank, they still get a fixed order in the schema, but there's no
guarantee what it will be.)
A schema specification is a blueprint for an actual
Schema
. It maps names to node and mark types.
A specification consists of an object that associates node names
with node type constructors and another similar object associating
mark names with mark type constructors.
Constructor
new SchemaSpec(nodes:Β ?Object<constructor<NodeType>>, marks:Β ?Object<constructor<MarkType>>)
πCreate a schema specification from scratch. The arguments map
node names to node type constructors and mark names to mark type
constructors.
Methods
update(nodes:Β ?Object<?NodeType>, marks:Β ?Object<?MarkType>) βΒ SchemaSpec
πBase a new schema spec on this one by specifying nodes and marks
to add or remove.
When nodes
is passed, it should be an object mapping type names
to either null
, to delete the type of that name, or to a
NodeType
subclass, to add or replace the node type of that
name.
Similarly, marks
can be an object to add, change, or remove
mark types in 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
spec: SchemaSpec
πThe specification on which the schema is based.
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.
defaultTextblockType() βΒ ?NodeType
πReturn the default textblock type for this schema, or null
if
it does not contain a node type with a defaultTextblock
property.
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.
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
.
Class used to signal model-related errors.
Functions
findDiffStart(a:Β Node, b:Β Node) βΒ ?Pos
πFind the first position at which nodes a
and b
differ, or
null
if they are the same.
findDiffEnd(a:Β Node, b:Β Node) βΒ ?{a:Β Pos, b:Β Pos}
π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
emptyFragment: 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).
defaultSpec: SchemaSpec
πThe specification for the default schema.
defaultSchema: Schema
πProseMirror's default document schema.
This module defines a way to transform documents. Transforming
happens in Step
s, 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.
These are the types of steps defined:
join
-
Join two block elements together. from
and to
must point at
the end of the first and start of the second element (so that
the intention is preserved even when the positions are mapped).
split
-
Split a block node at pos
. The parameter, if given, may be
{type, ?attrs}
object giving the node type and optionally the
attributes of the node created to hold the content after the
split.
ancestor
-
Change the stack of nodes that wrap the part of the document
between from
and to
, which must point into the same parent
node.
The set of ancestors to replace is determined by the depth
property of the step's parameter. If this is greater than
zero, from
and to
must point at the start and end of a
stack of nodes, of that depth, since this step will not split
nodes.
The set of new ancestors to wrap with is determined by the
types
and attrs
properties of the parameter. The first
should be an array of NodeType
s, and the second, optionally,
an array of attribute objects.
replace
-
Delete the part of the document between from
and to
and
optionally replace it with another chunk of content. pos
must
point at the βrootβ at which the cut startsβa position between
and above from
and to
.
When new content is to be inserted, the step's parameter should
be an object of shape {content:
Fragment
, openLeft: number, openRight: number}
. The step will insert the
given content at the root of the cut, and openLeft
and
openRight
indicate how much of the content on both sides
should be consided βopenβ.
A replace step will try to join open nodes on both sides of the
cut. That is, nodes in the original document that are partially
cut off by from
and to
, and nodes at the sides of the
replacement content as specificed by openLeft
and
openRight
. For example, if openLeft
is 2, the first node of
the replacement content as well as its first child is
considered open. Whenever two open nodes with the same
markup end up next to each other, they are
joined. Open nodes that aren't joined are closed
to ensure their content (or lack of it) is valid.
addMark
-
Add the Mark
given as the step's parameter to all
inline content between from
and to
(when allowed).
removeMark
-
Remove the Mark
given as the step's parameter from all inline
content between from
and to
.
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.
Constructor
new Step(type:Β string, from:Β ?Pos, to:Β ?Pos, pos:Β ?Pos, param:Β ?any = null)
πBuild a step. The type should name a defined step
type, and the shape of the positions and parameter should be
appropriate for that type.
Properties
type: string
πThe type of the step.
from: ?Pos
πThe start of the step's range, if any. Which of the three
optional positions associated with a step a given step type
uses differs. The way each of these positions is mapped when
the step is mapped over a position mapping depends
on its role.
to: ?Pos
πThe end of the step's range.
pos: ?Pos
πThe base position for this step.
param: ?any
πExtra step-type-specific information associated with the step.
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
.
invert(oldDoc:Β Node, map:Β PosMap) βΒ Step
πCreate an inverted version of this step. Needs the document as it
was before the step, as well as PosMap
created by applying the
step to that document, as input.
map(remapping:Β 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.
Static properties
fromJSON(schema:Β Schema, json:Β Object) βΒ Step
πDeserialize a step from its JSON representation.
define(type:Β string, implementation:Β Object)
πDefine a new type of step. Implementation should have the
following properties:
apply
`(doc: Node, step: Step) β ?StepResult
- Applies the step to a document.
invert
`(step: Step, oldDoc: Node, map: PosMap) β Step
- Create an inverted version of the step.
paramToJSON
`(param: ?any) β ?Object
- Serialize this step type's parameter to JSON.
paramFromJSON
`(schema: Schema, json: ?Object) β ?any
- Deserialize this step type's parameter from JSON.
Objects of this type are returned as the result of
applying a transform step to a document.
Properties
doc: Node
πThe transformed document.
map: PosMap
πThe position map that describes the correspondence between the
old and the new document.
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:Β Pos, bias:Β ?number) βΒ MapResult
π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.
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
.
Methods
map(pos:Β Pos, 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.
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.
The return value of mapping a position.
Properties
pos: Pos
π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 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.
map(pos:Β Pos, bias:Β ?number) βΒ MapResult
πMap a position through this remapping, optionally passing a bias
direction.
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.
steps: [Step]
πThe accumulated steps.
docs: [Node]
πThe individual document versions. Always has a length one more
than steps
, since it also includes the original starting
document.
maps: [PosMap]
πThe position maps produced by the steps. Has the same length as
steps
.
doc: Node
πThe current version of the transformed document.
before: Node
πThe original input document.
step(step:Β Step) βΒ ?StepResult
πAdd a step to this transformation. If the step can be
applied to the current document, the result of
applying it is returned, and an element is added to the
steps
, docs
, and
maps
arrays.
map(pos:Β Pos, bias:Β ?number) βΒ MapResult
πMap a position through the whole transformation (all the position
maps in maps
), and return the result.
join(at:Β Pos) βΒ Transform
πJoin the blocks around the given position.
split(pos:Β Pos, 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
.
splitIfNeeded(pos:Β Pos, depth:Β ?number = 1) βΒ Transform
πSplit at the given position, if that position isn't already at
the start or end of a node. If depth
is greater than one, also do
so for parent positions above the given position.
lift(from:Β Pos, to:Β ?Pos = from) βΒ 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).
wrap(from:Β Pos, to:Β ?Pos, 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:Β Pos, to:Β ?Pos, 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:Β Pos, type:Β NodeType, attrs:Β ?Object) βΒ Transform
πChange the type and attributes of the node after pos
.
delete(from:Β Pos, to:Β Pos) βΒ Transform
πDelete the content between the given positions.
replace(from:Β Pos, to:Β Pos, source:Β Node, start:Β Pos, end:Β Pos) βΒ Transform
πReplace the part of the document between from
and to
with the
part of the source
between start
and end
.
replaceWith(from:Β Pos, to:Β Pos, 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:Β Pos, content:Β union<Fragment, Node, [Node]>) βΒ Transform
πInsert the given content at the pos
.
insertText(pos:Β Pos, text:Β string) βΒ Transform
πInsert the given text at pos
, inheriting the marks of the
existing content at that position.
insertInline(pos:Β Pos, node:Β Node) βΒ Transform
πInsert the given node at pos
, inheriting the marks of the
existing content at that position.
addMark(from:Β Pos, to:Β Pos, mark:Β Mark) βΒ Transform
πAdd the given mark to the inline content between from
and to
.
removeMark(from:Β Pos, to:Β Pos, 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:Β Pos, to:Β Pos, newParent:Β ?NodeType) βΒ Transform
πRemove all marks and non-text inline nodes, or if newParent
is
given, all marks and inline nodes that may not appear as content of
newParent
, from the given range.
joinableBlocks(doc:Β Node, pos:Β Pos) βΒ bool
πTest whether the blocks before and after a given position can be
joined.
joinPoint(doc:Β Node, pos:Β Pos, dir:Β ?number = -1) βΒ ?Pos
π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.
canLift(doc:Β Node, from:Β Pos, to:Β ?Pos) βΒ bool
πTells you whether the given positions' sibling
range, or any of its ancestor nodes, can be
lifted out of a parent.
canWrap(doc:Β Node, from:Β Pos, to:Β ?Pos, type:Β NodeType) βΒ bool
πDetermines whether the sibling range of the
given positions can be wrapped in the given node type.
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:Β DOMNode, attrs:Β NodeType, content:Β ?Object, [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(node:Β Node, options:Β ?Object) βΒ DOMFragment
πSerialize the content of the given node 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(node:Β Node, 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(doc:Β Node) βΒ string
πSerialize a node 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.
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(ProseMirror, [string], Pos)>)
π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
.
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 MenuElement
s
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.
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, doc:Β Node, 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.
confirmSteps(sendable:Β {version:Β number, doc:Β Node, steps:Β [Step]})
πTells the module that a set of unconfirmed steps have been
accepted by the central authority, and can now be considered
confirmed.
receive(steps:Β [Step]) βΒ [PosMap]
πPushes a set of steps (made by peers and received from the
central authority) into the editor. This will rebase any
unconfirmed steps over these 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.
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
Extends Error
.
Superclass for ProseMirror-related errors. Does some magic to
make it safely subclassable even on ES5 runtimes.
Constructor
new ProseMirrorError(message:Β string)
πCreate an instance of this error type, capturing the current
stack.
Extends ProseMirrorError
.
Error type used to signal miscellaneous invariant violations.
Extends ProseMirrorError
.
Error type used to report name clashes or other violations in
namespacing.