vimtricks.wiki Concise Vim tricks, one at a time.

How do I stop Vim from creating backup and swap files in my project directories?

Answer

:set backupdir=~/.vim/backup// directory=~/.vim/swap//

Explanation

How it works

By default, Vim creates backup files (ending in ~) and swap files (ending in .swp) in the same directory as the file you are editing. This clutters your project with extra files and can cause issues with version control and build tools.

You can redirect these files to a centralized location:

  • backupdir controls where backup files (filename~) are stored
  • directory controls where swap files (.filename.swp) are stored

The double forward slash (//) at the end of the path tells Vim to use the full file path in the filename, which prevents name collisions when editing files with the same name in different directories.

Common configurations:

" Redirect to central directories
set backupdir=~/.vim/backup//
set directory=~/.vim/swap//

" Or disable them entirely
set nobackup
set nowritebackup
set noswapfile

You can also configure the undo directory if you use persistent undo:

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

Note: You must create these directories yourself before Vim can use them. Vim will not create them automatically.

Example

Add this to your ~/.vimrc:

" Create directories if they don't exist
silent! call mkdir($HOME . '/.vim/backup', 'p', 0700)
silent! call mkdir($HOME . '/.vim/swap', 'p', 0700)
silent! call mkdir($HOME . '/.vim/undo', 'p', 0700)

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

Now your project directories stay clean. All backup, swap, and undo files are stored under ~/.vim/ instead of alongside your source code. The mkdir calls with silent! ensure the directories exist without showing errors if they already do.

Next

How do you yank a single word into a named register?