From version 7.3, Vim supports persistent undo. With this feature enabled, Vim automatically saves history to external files, making the undo/redo functionality continue to work after restarting Vim or closing a buffer. This makes Vim much more comfortable if you use it as a core part of your development workflow, especially if you use it with other terminal applications.
Before I learned about persistent undo, I felt uncomfortable to make changes spanning across multiple files. I don’t like to keep many buffers open, so I rather jump from file to file with fzf or use the shell to navigate around and occasionally open Vim when I need to edit something.
Having short editing sessions, I can’t access recent history information after I reopen a file. This info is often crucial, as a simple undo/redo combination allows me to recover some context about what I’ve been doing in that file before.
In this aspect, persistent undo increases the comfort level of the lightweight Vim + terminal combination to be a bit closer to what IDEs provide; tools that I usually don’t restart too often and provide a consistent feeling by keeping track of the stuff I do in them in a session.
We write articles like this regularly. Join our mailing list and let's keep in touch.
set undofile is sufficient to enable this feature. However, by default Vim creates the history files next to the files that are being edited. I don’t really like this, so I use the
set undodir option as well to specify the exact location of these files.
Taking the idea from this StackExchange thread I also added some instructions to my .vimrc file to create a temporary directory to store my history files. Because I don’t want to bother about deleting the old entries, I put the undo directory to the
/tmp folder as it’s subject to system level cleanups. This way I can’t count on the history files to survive system restarts, but it’s fine for me, they are usually needed for one coding session. If you store them elsewhere, make sure to create a Cron job to periodically delete them.
It’s also worth mentioning that it is best to create the undo directory with
700 permissions (
drwx------), as it grants all rights to the owner, but nothing to anybody else.
So, to summarize, I’ve added the following to my .vimrc file:
As far as I can tell now, having
undofile enabled provides a great deal of comfort for free. If you use Vim solely to edit configuration files it might not be a big deal, but in any other case I recommend this feature.