Vim - automatically delete SWP file after recovery doesn't change the original file
Solution 1:
Note: you haven’t said which operating system you’re using. The following works with a Unix shell but if running Windows, you could download a bare-bones Cygwin or some other shell.
I used to do the same as you, run :e
to re-open the same file to get the option to delete the recovery file. After a crash or unexpected computer restart, I clean up all the remnant Vim recovery files by running vim -r
on the swap files and letting the recovery proceed.
When files have not changed
If the files haven’t changed, I want to delete the recovery file immediately. It would be great if Vim could do this automatically but unfortunately, it doesn’t.
When files have changed
If the files have changed, I run the DiffOrig
command to compare the differences between the original and the recovered versions. If I’m happy with the changes from the recovery file, I exit by saving the files with the :x
command. If not, I discard the recovered changes by quitting with :q!
. If the recovery file isn’t associated with a saved file, e.g, .swp
, I usually use the :w filename
to save the recovered buffer to a file with a filename.
DiffOrig helper
I added the DiffOrig command to my .vimrc
so that it’s always available.
command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis | wincmd p | diffthis
Shell script
I run the following script in my shell to find every swap-file in the current directory tree. Each swap-file is then used to open Vim in “recovery mode” and is then deleted after Vim is closed.
find . -type f -name '.*.sw?' -exec vim -r "{}" -c DiffOrig \; -exec rm -iv "{}" \;
The rm -i
option requires confirmation (y
) to delete the file. If you’re more confident and want to speed up the process, this can be omitted.