Introduction to Vim's swap files

When you edit a file in Vim, you have probably noticed the (temporary) .swp file that gets created. By default it'll be in the same location as the file that you are editing (although you can change this).

The swap file contains the info about changes made to the file (or buffer).

In theory this can mean that if Vim or you computer crashes, you can recover the edits that you made. They also provide a way for Vim to ensure that you don't accidentally open the same file more than once at the same time (this is more useful for systems that have more than one user logged in at once).

However these swap files can get annoying. If you force Vim to quit (or your SSH connection gets terminated before you :q Vim) then the .swp file will just live there forever! Until you go and delete it anyway. This can mean that your applications and websites end up with a bunch of .swp files, and could possibly be read by anyone going to http://yoursite.com/.index.php.swp.

So, what can you do about the Vim swap files?

I always prefer to keep all the vim swap files in their own directory. Then if Vim quits without removing the swap files it won't get uploaded to a site, included in an app or checked into any version control system.

First, create a directory where you want to store your vim swap files:

mkdir ~/vimswap/

Then update your ~/.vimrc file and include the following line:

set directory^=$HOME/vimswap//

How to disable the Vim swap file functionality completely

Enter the following config into your ~/.vimrc

 set noswapfile