Introduction
Vim's persistent undo feature saves undo history to disk so it survives editor restarts. However, when files are deleted or moved, the corresponding undo files (.un~ files) remain on disk, accumulating over time and consuming storage:
find ~/.vim/undo/ -type f | wc -l
# Shows thousands of stale undo files for files that no longer existSymptoms
- Undo directory grows to hundreds of megabytes or gigabytes
- Undo files exist for source files that have been deleted
- Git status shows undo files as untracked in the project directory
- Disk usage increases over time without apparent cause
- Undo history works for files that no longer exist (stale data)
Common Causes
- Persistent undo enabled with
set undodirbut no cleanup mechanism - Files deleted outside Vim (rm, git clean, file manager)
- Project directories renamed or moved, orphaning undo files
- Undo files stored alongside source files (
set undodir=.) polluting git repos - Long-running projects accumulating years of undo history
Step-by-Step Fix
- 1.Configure a centralized undo directory to keep undo files organized:
- 2.```vim
- 3." In ~/.vimrc
- 4.set undofile
- 5.set undodir=~/.vim/undo//
- 6.
` - 7.Create the directory:
- 8.```bash
- 9.mkdir -p ~/.vim/undo
- 10.
` - 11.Clean up stale undo files that no longer have corresponding source files:
- 12.```bash
- 13.#!/bin/bash
- 14.# clean-undo.sh
- 15.UNDO_DIR="$HOME/.vim/undo"
- 16.COUNT=0
find "$UNDO_DIR" -type f -name '*.un~' | while read -r undo_file; do # Reconstruct the original file path # Vim encodes the path in the undo filename original_path=$(echo "$undo_file" | sed 's|'$UNDO_DIR'/||' | sed 's|%|/|g')
if [ ! -f "$original_path" ]; then rm "$undo_file" COUNT=$((COUNT + 1)) fi done
echo "Removed $COUNT stale undo files" ```
- 1.Use a simpler cleanup by removing all undo files older than 30 days:
- 2.```bash
- 3.find ~/.vim/undo -type f -mtime +30 -delete
- 4.
` - 5.Add cleanup to a cron job for automatic maintenance:
- 6.```bash
- 7.# Clean undo files older than 7 days, weekly
- 8.0 3 * * 0 find ~/.vim/undo -type f -mtime +7 -delete
- 9.
` - 10.Disable persistent undo for specific file types or directories:
- 11.```vim
- 12." Disable undo for generated files
- 13.autocmd FileType min,javascriptreact set noundofile
- 14.autocmd BufReadPost /tmp/* set noundofile
- 15.
`
Prevention
- Use a centralized undo directory (
~/.vim/undo//) instead of storing undo files alongside source files - Add undo file patterns to
.gitignore:*.un~ - Schedule periodic cleanup of stale undo files with a cron job
- Monitor undo directory size:
du -sh ~/.vim/undo/ - Consider disabling persistent undo for temporary or generated files
- Use
set undolevels=1000to limit undo history depth per file - Document undo directory location and cleanup procedures in your Vim setup guide
- For Neovim, use
vim.fn.stdpath('data') .. '/undo'for the undo directory path