Vim undo branches
You probably already know how to use vim's basic undo and redo features. For a quick refresher, read this short tutorial on how to use vim redo and undo. Vim's undo branches are a little more complex but extremely powerful. They allow you to recover lost changes in vim even if you undo them and make new changes.
Here's how they work. Every "change" you make in vim results in another node in your undo history. Before you knew about undo branches, you could think of this history as strictly linear. I make 5 distinct changes, and I can go back in time up to 5 times. I can then go forward in time 5 times. But what if I go back 3 changes and then make a new change? Are those previous 3 changes lost forever?
In order to understand this concept, you need to know how vim stores these changes under the hood—a tree structure. Each node of the tree corresponds to one change. As you make changes and navigate up and down the tree using u
undo and ctrl-r
redo, vim builds out this tree keeping a numeric index associated with each change. This allows you to use the g-
and g+
commands to traverse through the history in chronological order rather than just through the one branch of the tree you're currently in.
This gets confusing quickly, so let's jump into some examples.