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

How do I enable persistent undo so undo history survives closing files?

Answer

:set undofile undodir=~/.vim/undodir

Explanation

By default, Vim's undo history is lost when you close a file. Enabling undofile saves undo history to disk, letting you undo changes even after closing and reopening files — days or weeks later. This is one of Vim's most underused power features.

How it works

  • undofile — enables persistent undo (saves undo history per file)
  • undodir — directory where undo files are stored
  • Undo files are named after the original file's full path
  • History persists across Vim sessions indefinitely

Example

" In your vimrc
set undofile
set undodir=~/.vim/undodir

" Create the directory first!
" mkdir -p ~/.vim/undodir
Workflow:
1. Edit file.py, make changes, save and quit
2. Next day: open file.py
3. Press u — undoes yesterday's changes!
4. :earlier 1h — go back to the state from 1 hour ago

Tips

  • Create the undodir directory before enabling: mkdir -p ~/.vim/undodir
  • Pair with :earlier and :later for time-based undo: :earlier 10m
  • Use UndotreeToggle plugin to visualize the full undo tree
  • Undo files can grow large — periodically clean old ones from undodir

Next

How do I return to normal mode from absolutely any mode in Vim?