11

When the Vim process is abruptly terminated (e.g. system crash), it leaves a SWP file. Opening the original file in Vim later gives the option of recovery. Most of the time the recovered file is the same as the saved file, because I have a habit of saving often. Then Vim says:

Recovery completed. Buffer contents equals file contents. 
You may want to delete the .swp file now.

Well, of course I want to delete the .swp file now!

How can I get Vim to always delete the SWP file automatically in this case?

There seems to be no built-in setting to do this, so I'm looking for an appropriate autocommand event.

One way I found is to :e # after the message, which causes the swap-exists options to appear again, then I can "Delete It". But I shouldn't really have to do those extra steps each time.

1
  • Thanks! I found your :e # trick is, albeit not ideal, but still more useful than the current answer below. :-)
    – RayLuo
    Commented Dec 1, 2017 at 8:09

1 Answer 1

6

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .