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 hiddenmkviewsaves the current window's state: folds, cursor position, scroll position, and local option settingsautocmd BufWinEnter *fires when entering any buffer windowsilent loadviewsilently restores the saved view; thesilentsuppresses 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,curdirto control exactly what is saved (omitcurdirif you don't want the working directory saved) - The
augroup/autocmd!pattern prevents duplicate autocmds if you re-source yourvimrc - To save views manually without the autocmd, just run
:mkviewand:loadviewyourself