Merge Commands on ProseMirror Undo Stack

Ana Chang
1 min readApr 22, 2022

When using the prosemirror-history package to support “Undo” and “Redo” in your ProseMirror text editor, sometimes you would like to merge multiple commands into one item on the undo stack. Otherwise the user has to hit “undo” multiple times to undo something they accomplished with a single action in the editor.

It turns out it is very easy to do this, but it took me a long time to discover how to do it.

By default each call to dispatch adds a new item to the undo stack. If you are using transactions it is easy to append new steps to the existing transaction and then call dispatch on the final transaction, which results in one item on the undo stack. However, if the action you would like to perform is not exposed as a transaction, but is only exposed as a command, you have to dispatch each command separately. This results in one item on the undo stack for each command.

So, how do you get one item on the undo stack for multiple commands? It turns out the prosemirror-history package supports this by using a metadata property. You can set the metadata for"appendedTransaction" on a transaction where the value is the transaction to append to.

For example the following function dispatches two commands and combines them into one item on the undo stack.

--

--