Merge Commands on ProseMirror Undo Stack

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store