How do I merge consecutive edits so they undo in a single step?
Answer
:undojoin<CR>
Explanation
By default, separate edits often become separate undo entries, which makes replaying or backing out a multi-part change noisy. :undojoin tells Vim to merge the next change into the previous undo block, so a related sequence behaves like one atomic edit in undo history. This is especially useful in scripted or command-line driven edits where you intentionally split operations for clarity but want one clean undo point.
How it works
- Run one change first (for example a substitution or normal-mode edit)
- Execute
:undojoinimmediately before the next change - The next edit is folded into the same undo entry as the previous one
- Repeating this between related edits keeps history concise and semantically grouped
Example
Imagine you run two consecutive cleanup commands:
:%s/foo/bar/g
:undojoin
:%s/baz/qux/g
Without :undojoin, pressing u undoes these in two steps. With :undojoin, one u reverts both changes together.
Tips
:undojoinmust come after a change and before the next change- If there is no prior change to join, Vim reports an error
- Pair this with batch refactors to keep undo history meaningful rather than fragmented