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

How do I automatically save and restore fold states between Vim sessions using autocmds?

Answer

autocmd BufWinLeave * mkview

Explanation

By default, Vim forgets your folds, cursor position, and scroll state every time you close a file. Adding two autocmds to your vimrc tells Vim to save the current window view when you leave a buffer and restore it when you return — making fold states, cursor position, and local options persist seamlessly across sessions.

How it works

  • autocmd BufWinLeave * fires whenever any buffer's window is about to be closed or hidden
  • mkview saves the current window's state: folds, cursor position, scroll position, and local option settings
  • autocmd BufWinEnter * fires when entering any buffer window
  • silent loadview silently restores the saved view; the silent suppresses the error that occurs when no view file exists yet

Example

Add this to your ~/.vimrc or ~/.config/nvim/init.vim:

augroup auto_view
  autocmd!
  autocmd BufWinLeave * mkview
  autocmd BufWinEnter * silent loadview
augroup END

With this in place, every file you open will remember its folds and cursor position the next time you open it.

Tips

  • Views are stored in ~/.vim/view/ (Vim) or ~/.local/state/nvim/view/ (Neovim) by default; change with :set viewdir
  • Use :set viewoptions=folds,cursor,curdir to control exactly what is saved (omit curdir if you don't want the working directory saved)
  • The augroup/autocmd! pattern prevents duplicate autocmds if you re-source your vimrc
  • To save views manually without the autocmd, just run :mkview and :loadview yourself

Next

How do I create new files and directories directly inside Vim's built-in file browser without leaving Vim?