Tuesday, February 22, 2011

Vim Usage: use session

Many software has a function that it will restart the last status when you launch the program again. For example, eclipse will restore the layout, perspective, files opened when you launch it again.

Question: Does vim contain this function?
Answer: Yes for sure, otherwise, there are lots of people complaining it. To archive this function, we need to use session to store the status before you exit and restore it when launching.

When we are developing a project, this is not a short-period job. If you exit vim and launch it again from scratch, I think you will pull your hair out and want to kill vim immediately as this is a troublesome work!

Session is a good tool that store windows layout. For example, you may have many tabs and splitting windows. You can store them into session so that when you launch it, you can have such layout again.

To create a session, you can use ":mksession [filename]".  If filename is omitted, vim will create a file named session.vim. In fact, session is a vim script and you can edit it if you like. You also can view the session file so that you can have better understanding how session works.

Which value is stored depends on 'sessionoptions'. By default, 'sessionoptions' is set to be "blank,buffers,curdir,folds,help,options,tabpages,winsize". You can check this with ":set sessionoptions" command in vim. That means vim will store current blank windows, buffers, current directory, folding, help windows, current options, tabs and windows size when you make a session file.

Remark: if you are using windows version vim and you want this session file can be execute under windows and vim, you need to add two more 'sessionoptions'. They are "slash" and "unix". "slash" is to replace back slash with slash and "unix" is to store the line break in unix format (There is some different between dos format and unix format, if you want to know more, you can read my previous post).

If you don't want to store current directory path, you want to set the current directory is same as location of session file. To do that, you need to modify 'sessionoptions' that to remove "curdir" and add "sesdir". After that, when you load the session file, the location of session will be set to be current working directory. Also, after this setting, all path in the session file will become relative path instead of absolute path.

Ok, we talked a lot of advantage of using session and how to create a session. How can we use it? The answer is that it is easy, you can use ":source [sessionfile]" to load the session, or you can use in this command in terminal
$ vim -S [session file]

No comments:

Post a Comment