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

How do I save multiple different views of the same file with independent fold and cursor states?

Answer

:mkview 2 and :loadview 2

Explanation

Vim supports up to 9 numbered view slots per file. :mkview N saves the current window's folds, cursor position, local options, and manual fold definitions to slot N, while :loadview N restores that exact state. This lets you maintain multiple named perspectives on the same buffer simultaneously — for example, a fully-collapsed view for overview and a fully-expanded view for deep editing.

How it works

  • :mkview (no number) saves to slot 1 by default
  • :mkview 2 through :mkview 9 save to independent slots
  • :loadview 2 restores only that slot — other slots remain untouched
  • Views are stored in viewdir (typically ~/.vim/view/ or ~/.local/share/nvim/view/)
  • What is saved depends on viewoptions (default includes cursor, folds, options)

Example

You have a large file. Save a collapsed overview:

zM              " close all folds
:mkview 1       " save the collapsed state to slot 1

Now expand and navigate to a specific section:

zR              " open all folds
50G             " jump to line 50
:mkview 2       " save the expanded state at line 50 to slot 2

Later, switch between the two perspectives:

:loadview 1     " back to collapsed overview
:loadview 2     " back to expanded editing position

Tips

  • Use viewoptions to control what gets saved: :set viewoptions=cursor,folds,slash,unix
  • Automatically save and load the default slot with autocmds: autocmd BufWinLeave * mkview | autocmd BufWinEnter * silent! loadview
  • Slot 1 is equivalent to :mkview and :loadview without a number

Next

How do I control how many lines Ctrl-U and Ctrl-D scroll?