I’ve been tinkering around with using Vim sessions recently. They allow you to save the state of Vim and reload it at a later point. It saves things like the files that you have open, the windows they’re in, the sizes of those windows and so on and so forth. Here I’m going to share a few lines in my .vimrc that should hopefully come in useful.

Prerequisite Knowledge: You should be a vim user that isn’t afraid to make changes to their .vimrc file.

The idea I wanted to implement was some sort of automatic session management for vim. Whenever I reopened vim, I wanted it to drop me into the last session I had in that directory without needing any interaction from me. To achieve this, I added the following to my .vimrc:

" Loads the session from the current directory if, and only if, no file names
" were passed in via the command line.
function! LoadSession()
    if argc() == 0
        exe LoadFile(".session.vim")
    endif
endfunction

" Auto session management commands
autocmd! VimLeave * mksession! .session.vim
autocmd! VimEnter * :call LoadSession()

The LoadSession() function looks for a file in the current directory called .session.vim and loads it, but only if no command line arguments were passed to vim. So this:

$ vim

Will load in your last session if it exists. This:

$ vim some/file/to/edit.rb

Will not load your last session.

Exiting Vim

I got into a bad habit where I would just use :q to exit out of vim. I would keep running it until there were no windows left and vim exited. I could just use :qall and get it over with in one command but old habits die hard.

Unfortunately, my mashing :q strategy doesn’t play nicely with session managing. I would only ever get the last window that was open, understandably. So I implemented this little hack to help me out:

" This abbreviation replaces the :q command with :qall.
cabbrev q <c-r>=(getcmdtype()==':' && getcmdpos()==1 ? 'qall' : 'q')<CR>

This simply replaces :q with :qall when you execute a command. Hacky, but it works. I wholeheartedly recommend not using this, I’m just putting it here because it’s what I do. Try and get yourself into the habit of properly exiting out of vim :)