Hackernoon logoSessions: The Vim feature no one talks about! by@claudio.santos.ribeiro

Sessions: The Vim feature no one talks about!

Cláudio Ribeiro Hacker Noon profile picture

@claudio.santos.ribeiroCláudio Ribeiro

Software Engineer

Vim is an awesome editor. Right there, I said it!

But having said that, and after having worked with it for some time now, we always get to that spot, after days or even weeks of continuous work, countless tabs open, countless settings in place, we need to restart the computer.

It’s always a huge pain having to reconfigure everything after restarting.

Of course, this situation doesn’t happen in most modern text/code editors. And it doesn’t have to happen in Vim either. That’s the reason Vim has sessions!

Sessions allow us to save our current state in Vim, working directory, your windows, splits, and buffers, and any options you’ve set with :set get saved. Sessions are based in the Vim :mksession command. If we check the help file on the mksession command we can see the following:

:mks[ession][!] [file] 
Write a Vim script that restores the current editing session. When [!] is included an existing file is overwritten. When [file] is omitted “Session.vim” is used.

So basically our current state gets saved into a file. I personally like to use the ~/.vim/sessions folder and then have either a general session file that I always override or a particular file for a specific role. For example ~/.vim/sessions/article.vim for an article I’m currently writing or ~/.vim/sessions/javascript.vim for a Javascript workflow.

Vim also allows several state files to be saved, so we can have multiple workflows saved if we want.

Courtesy of Unsplash

So, to save the state we can use :mks ~/.vim/sessions/article.vim. (:mks is the abbreviature for :mksession, and both of them can be used).

When we’re ready to restore that state we can either use:

:source ~/.vim/sessions/article.vim

from within Vim, or we can start our Vim session with the state already loaded. For that, we can use

vim -S ~/.vim/sessions/article.vim

Dead simple! Just a quick note, sessions don’t store the command history nor the marks we might have. Register content also doesn’t get saved. While this is normally not an important thing, it might be relevant sometimes.

There are also some plugins that help managing sessions, like vim-session. But all in all, managing sessions is an innocuous functionality that is overlooked sometimes but is super useful and really straightforward to use. Vim definitely got us covered on that.

Having trouble with Vim? Don’t know what to put into your .vimrc file? Want to use it for programming? Check out my new book “An IDE Called Vim”. It goes through all the basics of Vim, from installing to using it as an IDE.


Join Hacker Noon

Create your free account to unlock your custom reading experience.