Everytime I cut out of a session in vim by losing my connection I'm rather filled with dred (and yet I continue to use vim...what a masochistist I must be) because when I open my files again a pile of swap-files are waiting to take a shot at destroying my work. What are the best practices for working with vim swap files? Do you just pick the newest one? If the file works the way you expect, do you just delete the swap files? How do you get rid of them?
Recovering files is always safe, because vim never writes any changes until you write them yourself. So recovering from a swap file and then closing without saving won't change anything.
Organize your swapfiles:
Get vim to put all your swap files in the same place, so you always know where they are:
or wherever you prefer. Use
// at the end of the filename makes vim use absolute file paths for the swap file names so you don't get name collisions. Make sure the directory exists, or vim won't use it (it won't create it for you).
Note: This only works on environment variables, if you want to use a vimscript variable then we need to use some
execute "set directory^=".my_vim_home_var."/swap//"
Diff the differences:
Vim's help suggests a very useful command to use in this situation:
:DiffOrig. It's not a default vim command, so copy the implementation from
:h :DiffOrig into your vimrc. (it's also in
$VIMRUNTIME/defaults.vim if you have vim8). Now, you can recover the file and simply run DiffOrig to get a vimdiff of what's changed from the unmodified version.
If you want to compare the contents of multiple swap files, recover your file with each different swap file, and then write the result to temporary files. Now load up the files and run
:diffthis on each file, make the changes you want, write back to the original file, and delete the temporary and swap files.
:swapname : get the name vim is using for the swap file for the current buffer (
:recover : recovers the selected file, same as when you start vim and press R (
Check out the help:
Vim has an entire section of the user manual on recovery:
Vim's reference help on swap files:
:h swap-file ,
Help on the directory option (for setting the swap file location):
Edit: Modified example for setting directory, as pointed out in comments by @B Layer
Personally, I have turned off swap and backup files, as it tends to create swap files and backup files everywhere and frequently creates conflicts. Vim's persistent-undo has been much more reliable and error-free.
Vim currently has persistent undo, its a much more fine grained method of backup. Every time, you press Esc, the current state of the file is captured.
To use vim this way:
- create a directory where you editing history for each file will be captured
- tell vim to use that directory
- enable persistent undo
In the shell:
set undodir=~/.vim/undodir set undofile
To turn off swap files: