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

How do I save and automatically restore a buffer's fold state and cursor position across Vim sessions?

Answer

:mkview / :loadview

Explanation

:mkview saves a snapshot of the current window — its fold states, cursor position, and local option values — to a view file on disk. :loadview restores it. Paired with autocommands, this gives you automatic fold preservation every time you open a file, without needing a session file.

How it works

  • :mkview — saves view to the default file (view file 0, stored in viewdir)
  • :mkview {n} — saves to a numbered slot (0–9), allowing multiple saved views per file
  • :loadview — restores from view file 0
  • :loadview {n} — restores from numbered slot n
  • :set viewoptions — controls what is saved (folds, cursor, options, etc.)

Example

Add to your vimrc to auto-save and restore folds for every file:

autocmd BufWinLeave * silent! mkview
autocmd BufWinEnter * silent! loadview

Now every time you leave a buffer, its fold state is saved; when you return (even in a new session), the folds are exactly as you left them.

Tips

  • :set viewoptions=folds,cursor,curdir limits what gets saved for faster, focused snapshots
  • Use numbered views (:mkview 1) to save different "perspectives" of a file — e.g., one with all folds closed, another with a specific region open
  • The view directory defaults to ~/.vim/view/ — ensure it exists or set :set viewdir=~/.vim/view
  • Combine with silent! in autocommands to suppress errors when no view file exists yet

Next

How do I get just the filename without its path or extension to use in a command?