Vim Swap and Backup Files Dilemma

:: May 27, 2021 :: vim L1 ::

Sooner or later you’ll notice that, when you edit files, Vim creates files named like .filename.swp in the same location as the file you’re editing. These files are called swap files.


Swap files

Swap files store changes you’ve made to the buffer. If your Vim crashes, a swap file will allow you to recover those changes. Another important role of swap files is to act as a lock mechanism: if you open a file, which is already opened in another Vim session, you’ll be warned. That can be useful, especially on a system with multiple users.

Disabling swap files

You can disable swap files entirely by adding set noswapfile to your .vimrc. However, I’d recommend you not to disable them, unless you really know what you’re doing. Instead, you could organize swap files better.

Swap files organization

Usually the most annoying thing about swap files is that they’re created all around your file system, wherever you edit your files. To solve this, you can save all the swap files in one location.

First, create a directory for storing swap files, for example: $ mkdir ~/.vim/swp

Then, put this snippet in your .vimrc: set directory=$HOME/.vim/swp//

The directory option contains a list of directories where Vim will try to store swap files. The // at the end tells Vim to use the absolute path to the file to create the swap file. This will ensure that swap file name is unique, so there are no collisions between files with the same name from different directories.


Note: My book Mastering Vim Quickly: From WTF to OMG in no time helped thousands of people to drastically improve their Vim skills within an hour! If you'd like to do the same, look it up: ebook + screencasts | paperback

Backup files

Vim can make backups of files you edit, so you’re safe from losing data. I don’t use this Vim feature personally, and I would suggest you set up a better backup solution for your work.

Of course, this feature can be useful. Backups are controlled by the settings of two options: backup and writebackup. If interested, look these up in :help.

Just like for swap files, you can also keep backup files better organized, by creating a directory and adding it to your .vimrc:

set backupdir=~/.vim/.backup//

You're welcome to join my private email list or follow me on Twitter.