vimtricks.wiki Concise Vim tricks, one at a time.

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

  • u undoes along the current branch (going toward the root of the tree)
  • <C-r> redoes along the current branch
  • g- moves to the chronologically older state across all branches
  • g+ moves to the chronologically newer state across all branches
  • :undolist shows 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:

  1. Type AAA — state 1
  2. Type BBB — state 2
  3. Press u twice — back to empty (state 0)
  4. 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 5m to jump to the buffer's state from 5 minutes ago, or :later 10m to move forward 10 minutes — time-based undo navigation
  • :earlier 3f jumps to the state from 3 file-writes ago — useful for reverting to saved states
  • Use :undolist to see all the branch tips and their change numbers
  • Enable set undofile in 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=5000 to control how many undo steps Vim retains

Next

How do I edit multiple lines at once using multiple cursors in Vim?