How to relocate temporary Vim files

I'm a big fan of Vim but it has an annoying habit of littering your working directory with its own swap, backup, and undo files. You can relocate these temporary files to a central repository by adding the following lines to your .vimrc file:

" Relocate backup files, swap files, and undo files.
set backupdir=~/.cache/vim//
set directory=~/.cache/vim//
set undodir=~/.cache/vim//

(The trailing double slash tells Vim to encode the file's original path in its name so files from different directories can co-exist peacefully.)

You'll need to make sure the directory you specify exists or Vim will throw a mild fit. You can add the following snippet to your .vimrc file to create the directory automatically on startup if it doesn't already exist.

if !isdirectory($HOME . "/.cache/vim")
    call mkdir($HOME . "/.cache/vim", "p")
endif

The "p" flag ensures that intermediary directories along the path will be created if necessary.