Change Vim swap/backup/undo file name

swapfile, vim

Solution

I have this in my `.vimrc` and it names the swap files with full path names and percent signs just as you describe:

" Store swap files in fixed location, not current directory.
set dir=~/.vimswap//,/var/tmp//,/tmp//,.

The key is the `//` at the end of the directories. See this note from `:help dir`:

- For Unix and Win32, if a directory ends in two path separators `"//"` or `"\\"`, the swap file name will be built from the complete path to the file with all path separators substituted to percent '%' signs. This will ensure file name uniqueness in the preserve directory.

Problem

Is it possible to change the way Vim names its swap/backup/undo files? To avoid clutter, I've set options in my `~/.vimrc` to dump these files in `~/.vim/tmp/{swap,backup,undo}`; however, as I routinely edit files in different directories with the same name, I often end up with lots of otherwise indistinguishable files and Vim sometimes has trouble recovering. Ideally, I'd like to use the naming scheme that the persistent undo has (`%path%to%file.undo`) for all these auxiliary files; there's no obvious way to set it, but can it be done with `Buf{Read,Write}` macros?

Original source