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

How do I configure Vim to auto-save files when I switch away?

Answer

:set autowriteall and autocmd FocusLost * silent! wa

Explanation

How it works

Vim can be configured to automatically save your files when you switch to another window or application. This combines two approaches:

Approach 1: autowriteall

:set autowriteall tells Vim to automatically save the current buffer whenever you execute a command that would switch to a different buffer, such as :next, :make, :tag, or :edit. This catches many common cases.

Approach 2: FocusLost autocmd

autocmd FocusLost * silent! wa

This creates an autocommand that triggers when Vim's terminal window loses focus (e.g., you switch to a browser or another terminal). silent! wa writes all modified buffers, and the ! after silent suppresses error messages for buffers that cannot be saved (like unnamed buffers).

Related options:

  • :set autowrite - Saves on a smaller set of commands (:make, :next, etc.)
  • :set autowriteall - Saves on a broader set of commands
  • autocmd FocusLost * silent! wa - Saves when the terminal loses focus
  • autocmd BufLeave * silent! w - Saves when leaving any buffer

Note: FocusLost requires terminal support. It works in GVim, Neovim, and most modern terminal emulators. Some older terminals may not send the focus event.

Example

Add to your ~/.vimrc:

set autowriteall
autocmd FocusLost * silent! wa

Now your workflow becomes:

  1. Edit a file in Vim
  2. Switch to your browser to test changes (Alt-Tab)
  3. Vim automatically saves all modified files
  4. Your changes are immediately available

This is especially useful for web development where you constantly switch between editor and browser, or when using a file watcher that triggers builds on save.

Next

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