brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: set undofile keeps your Vim undo history after you close the file

Vim
~/tips/tip-vim-undofile-persistent-undo

set undofile

Saves Vim undo history in a file so you can still undo after reopening the document.

Closing a file in Vim normally throws away the undo history, so tomorrow’s u has nothing to undo. One option in your vimrc changes that, and I think it should be on by default.

Add this line to your .vimrc, or run it by hand to try it:

set undofile

From then on, Vim writes the undo history to a separate file whenever you write the buffer, and reads it back when you open the file again. Undo files sit in the same directory as the edited file unless you point somewhere else with undodir. A central folder keeps your project directories clean, though I would create that folder first:

mkdir -p ~/.vim/undo
set undodir=~/.vim/undo

Vim maps the full filesystem path of each file to its own undo file, so two files with the same name in different folders do not collide. The function undofile() tells you which name Vim would use. You can also save and load a history by hand with :wundo {file} and :rundo {file}.

A few caveats from the help text. Vim stores a hash of the file contents, and it ignores the undo file when the file changed after the undo file was written. That protects you from a corrupted undo, but it also means an edit made by another program wipes the old history. An undo file is also ignored when its owner differs from the owner of the edited file, unless the undo file belongs to you. Text properties are not stored.

Vim never deletes undo files, so if you edit a lot of files you will need to clean up the folder yourself. Most errors while reading or writing an undo file are silent unless verbose is set, so if history does not come back, check the folder permissions before blaming Vim. Also think twice on shared machines, because the undo file contains earlier versions of your text, including things you deleted on purpose.

Further reading: Vim help: undo.txt, persistent undo

Going deeper: Guide: advanced tmux, a config that grows with you, formats, layouts and more

More Vim tips :%s/<Ctrl-r><Ctrl-w>/newname/g /oldname find . -name "*.conf" | vim – vim --clean file.txt :set textwidth=72 All Vim tips (45) All topics

Link