Vim: How to keep folds on save?

This behavior is normal. Vim's default is not to remember which code you had folded vs. unfolded from one session to the next. You can save your current folds; when you finish editing a file, before exiting vim, enter the command :mkview. When you next open the file, if you enter :loadview, it will restore your folds. If you want this to happen automatically, add this code to your vimrc

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

If you want more features, this plugin does the same thing http://www.vim.org/scripts/script.php?script_id=4021.

Update: sorry, my original code didn't work. It should work now.


Saving a file should definitely not cause Vim to reset folding. However, some autocmd on e.g. BufWritePost actions might trigger such behavior.

More specifically vim-go has an open bug which causes this issue with golang files. The bug's comments lists a couple of workarounds. Setting g:go_fmt_experimental = 1 works for me.


I am not a vim config ninja, but I hacked various solutions to achieve this, which works for me on nvim/Neo Vim without throwing errors.

augroup remember_folds
  autocmd!
  au BufWinLeave ?* mkview 1
  au BufWinEnter ?* silent! loadview 1
augroup END

Tags:

Vim