Vim Sessions

After you've opened several files across three or four directories, changed the colour scheme to suit the project, and folded up those sections you want to ignore, it's annoying to close vim and know you'll have to do that setup again. I haven't felt the lack when it comes to a single file, but recently when working on Ansible and needing to open not just the YML file but also this and that role file and the group_vars ... I decided there had to be a better way. Happily, Vim has the concept of both "views" (for a single file) and "sessions" (for multiple files). I'm just covering sessions: I think it entirely subsumes "views" so it seems a better place to start.

So you have those multiple files open and you want to be able to re-open to the same setup. Type :mksession or just :mks. vim will store the session restore information in the current working directory in a file called Session.vim. To re-open a session, just type vim -S. It can also be opened from within vim via ~so Session.vim.

If you want to have more than one session per folder, you can use :mksession <filename>. The filename should have a .vim extension, but can be stored wherever: the local folder is the most obvious location, but not required. To re-open a session from within vim, simply source the file: :so <filename>. Or - better from my point of view - open it from the command line: vim -S <filename>. If you change the view, save it again (if you want the changes to be remembered): this requires :mks! <filename> since you're overwriting an existing session file.

The stored session file turns out to be nothing more or less than a series of vim commands to replicate your setup. It doesn't have to have a .vim extension, but might cause confusion if it doesn't have.

Something to consider would be adding Session.vim or *.vim to your .gitignore file if you're a git user. I have a separate git repo of my Vim configurations.