How do I navigate undo branches to recover changes that were overwritten by a new edit?
Answer
g- / g+
Explanation
Vim doesn't have a simple linear undo stack — it maintains a full undo tree with branches. When you undo several changes and then make a new edit, the undone changes aren't lost; they live on a separate branch. The g- and g+ commands let you walk through every state in the undo tree chronologically, including states on other branches that u and <C-r> can't reach.
How it works
uundoes along the current branch (going toward the root of the tree)<C-r>redoes along the current branchg-moves to the chronologically older state across all branchesg+moves to the chronologically newer state across all branches:undolistshows all leaf nodes (tips) of the undo tree with their timestamps:earlier {N}and:later {N}navigate by step count or time
The key insight: u followed by a new edit creates a fork. The old redo path becomes a branch. Only g- and g+ can traverse between branches.
Example
Imagine this editing sequence:
- Type
AAA— state 1 - Type
BBB— state 2 - Press
utwice — back to empty (state 0) - Type
CCC— state 3 (a new branch!)
Now pressing <C-r> does nothing — you're at the tip of the new branch. The BBB and AAA states are on the old branch. But pressing g- walks backward through time: state 3 → state 2 → state 1 → state 0. And g+ walks forward: state 0 → state 1 → state 2 → state 3.
This means no edit is ever truly lost as long as you haven't closed the file (or have undofile enabled).
Tips
- Use
:earlier 5mto jump to the buffer's state from 5 minutes ago, or:later 10mto move forward 10 minutes — time-based undo navigation :earlier 3fjumps to the state from 3 file-writes ago — useful for reverting to saved states- Use
:undolistto see all the branch tips and their change numbers - Enable
set undofilein your vimrc to persist the undo tree across sessions — branches are preserved even after restarting Vim - The undotree plugin provides a visual tree browser if you want a graphical view of all branches
- The undo tree can get very large in long editing sessions — use
:set undolevels=5000to control how many undo steps Vim retains