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

How do I make Vim sessions save global variables?

Answer

:set sessionoptions+=globals

Explanation

By default, :mksession restores windows, buffers, and many editor states, but it skips most global variables. If your workflow depends on global flags, toggles, or runtime metadata, this can make restored sessions inconsistent. Adding globals to sessionoptions tells Vim to include those values when writing session files.

How it works

  • sessionoptions controls what :mksession records
  • +=globals appends globals without overwriting your other existing options
  • After setting this, future session files include global variables in g: scope
  • This is especially useful when custom commands or mappings depend on shared session state

Example

Assume you maintain a project flag:

:let g:build_profile = 'staging'

Without globals in sessionoptions, reopening a saved session may lose that variable. After running:

:set sessionoptions+=globals
:mksession! Session.vim

Sourcing Session.vim restores both layout and relevant global values.

Tips

  • Prefer += over replacing the option to avoid dropping defaults
  • Keep truly machine-specific values out of sessions when sharing files across environments
  • Review :help sessionoptions to decide whether to include related items like options or folds

Next

How do I change the key that opens Vim's command-line window?