Last Updated: November 19, 2020
·
25.13K
· Rafael Bicalho

Vim "swap", "backup" and "undo" files.

These files can be put in a fixed directory to keep things more organized.

First of all, create these three folders:

mkdir ~/.vim/.backup ~/.vim/.swp ~/.vim/.undo

Now, put these lines in your vimrc file.

set undodir=~/.vim/.undo//

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

set directory=~/.vim/.swp//

the "//" at the end of each directory means that file names will be built from the complete path to the file with all path separators substituted to percent "%" sign. This will ensure file name uniqueness in the preserve directory.

Alternatively you can turn them off, putting this in your vimrc file:

set nobackup

set noswapfile

Related protips:

Basic Vim commands - For getting started

3 Responses
Add your response

Thanks for the tip! I have set this up for myself as well, but the set backupdir=~/.vim/.backup// is not working as expected for me. It is putting the backup files in the correct directory, but the backup filenames are not what I expected. If I were to edit ~/foo.txt, then the backup file in my new vim backupdir is ~/.vim/.backup/foo.txt~ and not ~/vim/.backup/home%user%foo.txt~. Do you have this same issue as well?

Here's my config file if you're interested: https://github.com/kaleb/vim-files/blob/master/xdg.vim#L10

over 1 year ago ·

@kaleb "the "//" at the end of each directory means that file names will be built from the complete path to the file with all path separators substituted to percent "%" sign. This will ensure file name uniqueness in the preserve directory."

over 1 year ago ·

On a Windows system, I'm checking for existence of my preferred swap folder with

if isdirectory($HOME . '/.vimswap') == 0
  :silent !md \%UserProfile\%\\.vimswap
endif

then pointing to it with set directory=$HOME/.vimswap//

over 1 year ago ·