Auto-saving sessions in Vim

Mon, 19 Jul 2010 17:42:00 -0700
vi, vim

Back when I used Textmate, I liked that you could save projects to a file so that you could quit Textmate and come back later, load the project file up, and have all the files and tabs set up and open the way you had them. Since switching to Vim, I've gotten the same functionality (and more!) using the :mksession command. One thing that's missing in Vim, however, is the ability to auto-save a session. There are a few add-ons that do this, but add a bunch of other functionality that I find unnecessary. Below is a little script I wrote that adds auto-saving sessions to Vim:

function! AutosaveSessionOn(session_file_path)
  augroup AutosaveSession
    au!
    exec "au VimLeave * mks! " . a:session_file_path
  augroup end
  let g:AutosaveSessionFilePath = a:session_file_path

  echo "Auto-saving sessions to \"" . a:session_file_path . "\""
endfunction

function! AutosaveSessionOff()
  if exists("g:AutosaveSessionFilePath")
    unlet g:AutosaveSessionFilePath
  endif

  augroup AutosaveSession
    au!
  augroup end
  augroup! AutosaveSession

  echo "Auto-saving sessions is off"
endfunction

command! -complete=file -nargs=1 AutosaveSessionOn call AutosaveSessionOn(<f-args>)
command! AutosaveSessionOff call AutosaveSessionOff()

augroup AutosaveSession
  au!
  au SessionLoadPost * if exists("g:AutosaveSessionFilePath") != 0|call AutosaveSessionOn(g:AutosaveSessionFilePath)|endif
augroup end

To begin auto-saving sessions, simply run:

:AutosaveSessionOn <session filename>

Your session will then be automatically saved to the given session filename when Vim exits. Also, if you have globals in your sessionoptions list, when you load the auto-saved session, auto-saving will continue to occur to that session file. To turn auto-saving to the session file off, run:

:AutosaveSessionOff

For the latest and greatest version, refer to my vimrc.