Vim sessions and map leader

So a common use case when you’re hacking away at a project in an IDE is that you’ve got several files open in tabs in different locations. You can have this using Vim by opening tabs or split window views, and it’s really nice especially when you’ve got full 1080p worth of screen space to exploit. The problem is when you exit Vim, you have to close all your tabs and you lose all of your context, especially when you put the project away for a little while, it can be annoying to open up all the files. There’s a simple fix for that, and it’s the mksession command.

Just running :mksession in Vim will create a snapshot of your tab and window layout etc. and save it in a session file. You can check the help on the command for the exact details. Here’s a convenient mapping that lets me hit ,wq and have all files written and tabs saved in a session file.

let mapleader=","
:map <leader>wq :wa:mksession!:qa
:map <leader>ls :source Session.vim

So my map leader is the comma. Hitting that puts Vim in a mode where if you complete one of the map rules, the corresponding command will be executed.

The first command executes three commands. First, it writes all files that are open. Then it creates a session file into Session.vim in the current working directory. The exclamation mark means overwrite Session.vim if it exists already. Last, it exits out of Vim by closing all open tabs.

The second command sets up Vim from the Session.vim in the current working directory. You run this the very first thing you do when you open Vim in the directory where your work is at, and your workspace is restored to exactly the way you left it.

I guess having the map leader is what makes this effective because it opens up a whole new range of keystrokes for defining new mappings. Some other ideas: toggle paste mode when pasting from the system clipboard. I always have to type :set paste and :set nopaste whenever I need to bring stuff into Vim through the clipboard without having the indentation go haywire, but you now I’ve got this in my rc file:

set pastetoggle=pp

Any other ideas people have? Did you already know about this? I’m constantly learning new stuff about Vim – that is, whenever I’m not just using it to do work and actually poking about the documentation and configuration.

Advertisement

Post a Comment

Required fields are marked *

*
*

Follow

Get every new post delivered to your Inbox.