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

How do I keep my undo history after closing and reopening a file?

Answer

:set undofile

Explanation

By default, Vim's undo history is lost when you close a file. Enabling undofile tells Vim to save the entire undo tree to a hidden file on disk, so you can undo and redo changes from previous editing sessions — even days or weeks later. This is one of Vim's most powerful and underused features.

How it works

  • :set undofile enables persistent undo for the current buffer
  • Vim writes the undo history to a file in the undodir directory (defaults to . — the same directory as the edited file)
  • When you reopen the file, Vim loads the undo history automatically and you can press u to undo changes from your last session
  • The entire undo tree is preserved, including all branches — not just the linear undo stack

Setup

Add this to your vimrc for a clean configuration:

set undofile
set undodir=~/.vim/undodir

Then create the directory:

mkdir -p ~/.vim/undodir

Without setting undodir, Vim saves undo files alongside your source files (e.g., .main.go.un~), which clutters your project and your version control.

Example

Day 1: You edit config.yaml, make several changes, and close Vim.

Day 2: You reopen config.yaml and realize a change from yesterday was wrong. Press u repeatedly — Vim undoes changes from yesterday's session, stepping back through the full history.

You can even use :earlier 1d to jump to the state of the file from one day ago, or :later 2h to move forward two hours.

Tips

  • Use :earlier {time} and :later {time} to navigate the undo tree by wall-clock time: :earlier 30m reverts to the state from 30 minutes ago
  • Set undolevels to control how many undo steps Vim keeps in memory: :set undolevels=5000 (default is 1000)
  • The undo files in undodir can grow over time — periodically clean out old ones if disk space is a concern
  • Use :undolist to see the branches of your undo tree
  • Persistent undo works per-file — each file gets its own undo history file, identified by its full path
  • Combine with set undoreload=10000 to preserve undo history even when reloading a buffer with :e!
  • Neovim stores undo files in ~/.local/share/nvim/undo/ by default, so no setup is needed for undodir

Next

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