Vim Recipes Editing Managing Sessions

Managing Sessions

Problem

Every time you work on a project you need to manually open all of the files it comprises, readjust the window size, etc. You'd like Vim to do all this automatically.

Solution

Use sessions.

To save a session: :mksession. Vim saves the session information as 'Session.vim' in the working directory; to specify your own filename execute :mksession file instead. To overwrite an existing session follow the command with an exclamation mark: :mksession!.

To restore a session invoke Vim with the -S flag from the same directory you saved Session.vim in: vim -S. If you used a different filename for your session: vim -S file. If you're already inside Vim, you can load a session by sourcing the session file, e.g. :source Session.vim.

Discussion

Applications such as Mozilla Firefox use the concept of a global session file which is overwritten every time you use the program. To make Vim work this way you simply use a fixed name for the session variable. For example, you could save it to $VIMHOME/Session.vim. You could add a mapping something like this to your vimrc.

nmap SQ <ESC>:mksession! ~/vim/Session.vim<CR>:wqa<CR>

(SQ for Session Quit). To automatically restore this session when Vim is called without arguments add the following:

function! RestoreSession()
  if argc() == 0 "vim called without arguments
    execute 'source ~/.vim/Session.vim'
  end
endfunction
autocmd VimEnter * call RestoreSession()

You can extend this in arbitrary ways to suit your working environment. One approach is to only restore a session if it exists in the current file's directory. Another is to simply hardcode a list of directories whereby if they are the file's current directory or parent directory, their session file is used. This is useful for one-project-per-directory organisation.

If you don't just want one global session file, as described above, a more granular approach is suggested below:

nmap SSA :wa<CR>:mksession! ~/sessions/
nmap SO :wa<CR>:so ~/sessions/

Session Save As saves the open files and prefills the command line with the command to save the current session in a ~/sessions/ directory. All you need to do is enter a name and hit <Enter>.

Session Open also saves the open files, then prefills the command line with the command to load a session file. Just type the name of the session you want to load and hit <Enter>.

You can use <Tab> completion in both cases. For example, you could save a session with SSAwork<Enter>. Later, when you want to restore the session but can't recall its name, just hit SO<Tab> to cycle through the saved sessions.

(Both mappings assume the ~/sessions/ directory already exists; create it if it doesn't).

Yuri Klubakov's sessionman plugin provides a more polished approach for session management, subsuming the functionality described above.