414

Depending on my task in Vim I have several tabs open.

How can I save different sessions for later use?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Jogusa
  • 5,530
  • 5
  • 24
  • 23
  • 18
    @ldigas I think ppl feel more comfortable finding the question here (with the large font, great formatting...) than on an old school forum or a terminal documentation, or, heaven forbid, a `man` page – puk Jan 10 '12 at 00:19
  • 1
    @puk - There isn't much formatting in it either. And you can change the font in Vim :) – Rook Jan 10 '12 at 20:44
  • 7
    @ldigas I personally have always been scared away by the man pages b/c they don't sufficiently dumb things down. Much like everything else in linux, it has a steep learning curve. – puk Jan 10 '12 at 22:35
  • 1
    @puk - Well, whatever suits you most ... – Rook Jan 11 '12 at 00:53
  • 47
    @Idigas - I think you are missing the point that between the collective smarts of us, google, and the stack overflow metaknowledge management - this is simply a better way of getting your answers - what you need, not a long list of esoteric options, also as this page illustrates real world experience of traps, and often really nifty shortcuts to make your life easier. This applies equally to almost any manual I've looked at (except *maybe* the php online manual). Viva stackoverflow! – ErichBSchulz Dec 31 '12 at 04:19
  • 2
    @ldigas and people can use it for future reference, since someone else might need it. – Mansuro Jan 07 '13 at 08:19
  • 4
    @idigas I think these questions are real in the sense, that a vim beginner doesn't know a lot about the help system and how to use it, but if they get more seasoned they will know how to find their way in vim. – Edgar Klerks Oct 24 '13 at 09:53
  • 2
    I didn't actually find this question by looking for "saving a session", but by googling how to save a bunch of open tabs. I've used sessions before, but I was having a mental block on what to look for, and vim's help doesn't really help if you only know *what* you want to do and not *exactly* what it's called. – stringsn88keys Jun 16 '14 at 16:39
  • 1
    It's an old discussion but my $0.02 - SO is great at providing answers to *use-cases*, backed up by a `man` reference where we can learn the details of *why*, and how it would adapt to something slightly different. – OJFord Jul 13 '15 at 00:06
  • Autosave / autoload version: http://stackoverflow.com/questions/5142099/auto-save-vim-session-on-quit-and-auto-reload-session-on-start – Ciro Santilli OurBigBook.com Mar 24 '16 at 11:39

14 Answers14

566

You want something like

:mksession ~/mysession.vim

Then later you can source that vim file and you'll have your old session back:

:source ~/mysession.vim

or open vim with the -S option:

$ vim -S ~/mysession.vim
jinowolski
  • 2,442
  • 3
  • 18
  • 25
Benj
  • 31,668
  • 17
  • 78
  • 127
  • 29
    Ooo, and I almost forgot you can load it back by typing: gvim -S ~/mysession.vim – Benj Oct 29 '09 at 10:01
  • 1
    Thanks @Benj. I'm new in vim. How can I 'source' in the command line? – Jogusa Oct 29 '09 at 10:17
  • 1
    Hi Jogusa, That's pretty much what the above comment was about. vim -S – Benj Oct 29 '09 at 10:31
  • 2
    Ooops! Sorry Benj, I meant command mode. I have already found it: ``:source ~/mysession.vim´´. – Jogusa Oct 29 '09 at 10:43
  • 9
    Short is :so ~/file. If you happen to want to source the current file a simple :so % will do the work for you. – Daniel Baulig Apr 27 '11 at 22:53
  • Thanks for the tip @Daniel. Very handy for refresh vimrc if changed. – Jogusa Jun 05 '11 at 10:37
  • A link to the Vim documentation (in case someone wants to read): http://vimdoc.sourceforge.net/htmldoc/usr_21.html#21.4 – Denilson Sá Maia Oct 27 '11 at 02:32
  • 1
    I've mapped the following to reinitialize session (in vimrc) using comma+s: `nmap s :source $HOME/mysession.vim` – Kevin Lee Jul 05 '13 at 14:57
  • hit `:help session` for help, or look at http://vimdoc.sourceforge.net/htmldoc/starting.html#session-file – Eduardo Santana Jan 16 '14 at 21:27
  • 19
    If you do not specify a session file name, it will default to writing to and reading from `Session.vim`. So if you only want to have only one session saved in your current directory, you can use `:mksession` or `:mks` from vim to save your current session, and just `vim -S` to open it back up. – anishpatel Mar 17 '15 at 17:03
  • if using gvim, is there a way to keep the size of the windowsplits? When i use the suggested, this enters not in fullscreen and my split sizes are all messed up – tobilocker Feb 16 '16 at 13:26
  • When I do this in MacVim, it doesn't honor the `colorscheme` I have set in my .vimrc file. I work around this by typing `color ` afterwards but I wish there was a more convenient solution. – user110857 Mar 07 '16 at 14:57
  • 1
    WOWWWWWWW how I was missing this – Andres Felipe Jul 10 '21 at 01:03
  • Upvoted for the third one (`vim -S ~/mysession.vim`), though `:so ~/vim_session_filename` is useful too – Nathan majicvr.com Mar 13 '23 at 18:20
  • How can I prevent `vim -S` from making noise? – Martin Braun Mar 15 '23 at 05:21
  • @MartinBraun `>/dev/null` ? – Benj Mar 16 '23 at 16:14
  • @Benj That's not what I meant, the noise is not from the command, but within Vim itself. Luckily, [I found a solution](https://vi.stackexchange.com/questions/41547/how-to-vim-s-silently), already. – Martin Braun Mar 16 '23 at 16:23
72

You might want to set these session options in your vimrc. Especially options is annoying when you've changed your vimrc after you've saved the session.

set ssop-=options    " do not store global and local values in a session
set ssop-=folds      " do not store folds
RocketDonkey
  • 36,383
  • 7
  • 80
  • 84
Jan Christoph
  • 721
  • 4
  • 2
43

Note that :mksession will not save the changes to any files that you've made. I made this mistake of closing vim after saving the session assuming that I'll take up from there. But next time I opened the session, the changes I had made to the files were gone.

Deepanshu
  • 806
  • 6
  • 6
35

If you use NERDTree as your file explorer/dash, I would recommend xolox/vim-session plugin instead of the built-in :mksession command. For some reason, :mksession fails to restore NERDTree buffers. Your mileage may vary, but thought I'd share my experience.

gdso
  • 1,871
  • 2
  • 14
  • 7
  • For macvim, I need to ensure: `let g:nerdtree_tabs_open_on_gui_startup=0` and `let g:nerdtree_tabs_open_on_new_tab=0` to make xolox/vim-session works. – Nianliang Sep 01 '14 at 06:40
28

If you want to automate the process without using any plugins, you could use Go away and come back from Vim Tips Wiki.

Each time you exit Vim it will save the current session under ~/.vim/sessions and load it back again once Vim is opened. It's also based on you current path, so if you open Vim from different directories you will have different sessions, which is quite useful when working on different projects.

Just edit your ~/.vimrc file and add the following:

function! MakeSession()
  let b:sessiondir = $HOME . "/.vim/sessions" . getcwd()
  if (filewritable(b:sessiondir) != 2)
    exe 'silent !mkdir -p ' b:sessiondir
    redraw!
  endif
  let b:filename = b:sessiondir . '/session.vim'
  exe "mksession! " . b:filename
endfunction

function! LoadSession()
  let b:sessiondir = $HOME . "/.vim/sessions" . getcwd()
  let b:sessionfile = b:sessiondir . "/session.vim"
  if (filereadable(b:sessionfile))
    exe 'source ' b:sessionfile
  else
    echo "No session loaded."
  endif
endfunction

" Adding automatons for when entering or leaving Vim
au VimEnter * nested :call LoadSession()
au VimLeave * :call MakeSession()

Even for a beginner this script is somewhat easy to understand and customize.

Please note this script will only work properly for Unix systems (MacOS/Linux), it needs to be adapted to work on Windows.


UPDATE: Adding 0xc0de's suggestion, you may replace the VimEnter line for these ones if you want Vim to load session only if no arguments are provided:

if(argc() == 0)
  au VimEnter * nested :call LoadSession()
endif
Community
  • 1
  • 1
mathielo
  • 6,725
  • 7
  • 50
  • 63
  • 3
    You might want to open session only if no argument is provided for vim eg. `if argc() == 0 au VimEnter * nested :call LoadSession() end` – 0xc0de Aug 17 '15 at 04:57
  • Thanks @0xc0de , great suggestion (I even started using it myself). I have updated the answer. – mathielo Aug 17 '15 at 22:19
  • how would i modify this so that if i open vim with arguments it also does not save that session – Dr Manhattan Jun 30 '16 at 12:59
  • very good, but ` exe 'source ' b:sessionfile` needs an dot there? and the problem is that the autoload session is depends on the current home directory (get by `pwd`) how can I set it be the last working directory before exit vim? so that it can load the last working session rather than the session under `~/`? – van abel May 24 '17 at 08:53
  • If you want to be able to have sessions but still open single files in the directory without overwriting it check out my modified version of this in the separate answer: https://stackoverflow.com/questions/1642611/how-to-save-and-restore-multiple-different-sessions-in-vim/47656092#47656092 – PMunch Dec 05 '17 at 14:35
  • To avoid having to manually delete sessions that I don't want to be saved or that need to be cleared for some reason I wrote this alias: `alias clearvim="/home/user/.vim/sessions\`pwd\`"`. It clears the session for the current directory – pascalwhoop Mar 19 '18 at 14:32
21

If you plan having only 1 session for the project just do

:mks

which will create a Session.vim file in the current directory, and then to open the session (from the same directory):

vim -S

If you change the session and want to save it:

:mks!

This saves the session, not the files themselves!

If you plan having multiple sessions, I prefer to save them in hidden files in the project's directory:

:mks .session-name.vim

To open it (from the same directory):

vim -S .session-name.vim

Save session:

:mks! .session-name.vim

Since the sessions are saved in hidden files, to view them don't forget -a

ls -a
cute_ptr
  • 1,103
  • 9
  • 12
11

Since this is the first hit on Google for me (and probably others) for how to work with sessions in Vim I've decided to add a little to @mathielo's answer on how to make this automatic.

I like his code, but the addition of the "only if without args" solution seemed to be a bit lacking. This is my modified version:

function! MakeSession(overwrite)
  let b:sessiondir = $HOME . "/.vim/sessions" . getcwd()
  if (filewritable(b:sessiondir) != 2)
    exe 'silent !mkdir -p ' b:sessiondir
    redraw!
  endif
  let b:filename = b:sessiondir . '/session.vim'
  if a:overwrite == 0 && !empty(glob(b:filename))
    return
  endif
  exe "mksession! " . b:filename
endfunction

function! LoadSession()
  let b:sessiondir = $HOME . "/.vim/sessions" . getcwd()
  let b:sessionfile = b:sessiondir . "/session.vim"
  if (filereadable(b:sessionfile))
    exe 'source ' b:sessionfile
  else
    echo "No session loaded."
  endif
endfunction

" Adding automatons for when entering or leaving Vim
if(argc() == 0)
  au VimEnter * nested :call LoadSession()
  au VimLeave * :call MakeSession(1)
else
  au VimLeave * :call MakeSession(0)
endif

The notable change here is the optional override. If you open Vim without options it will open any existing session and overwrite changes made when you leave. If Vim is opened with options it will only create a new session if none exist, this means that you can open single files in a directory that has a session without overwriting it. Then you can open Vim without options to run the session instead. If there doesn't exist a session then it creates a new one.

PMunch
  • 1,525
  • 11
  • 20
  • I just tried your above posted solution in Neovim 0.2.2 and placed your snippet in `$HOME/.vim/plugin/sessions.vim` but it's not saving the session files. ¯\\_(ツ)_/¯ – ipatch Mar 19 '18 at 14:43
  • This thread, and particularily the linked comment, might help: https://superuser.com/questions/404686/installing-plugins-in-vim#comment461757_404820 I have it in my .vimrc and that works fine. – PMunch Mar 19 '18 at 15:11
  • got it working, apparently I have to exit (n)vim in order for the session to be written _insert bad joke_ Thanks again for sharing – ipatch Mar 19 '18 at 16:13
7

There is a very useful plugin for this task vim-startify which handles many other things like recently opened files etc, it has a very easy interface too.

I am using it since couple of days and till now its working perfectly. Hope it helps you.

vivek
  • 2,807
  • 5
  • 31
  • 44
3

There is this wonderful plugin call vim-session. It's very powerful. To install it:

cd ~/.vim/bundle
git clone https://github.com/xolox/vim-session.git

I have mapped its functionality in my .vimrc file like this:

nnoremap <leader>so :OpenSession 
nnoremap <leader>ss :SaveSession 
nnoremap <leader>sd :DeleteSession<CR>
nnoremap <leader>sc :CloseSession<CR>

Now in normal mode just type <leader>ss and you will see a command like this

:SaveSession 

Now add the name of your session

 :SaveSession namesession

and that's all.

When you close Vim and reopen it just do

 :OpenSession

and you will see your session open.

There is a lot of other configuration to add in your .vimrc file see the documentation for examples:

let g:session_directory = "~/.vim/tmp/session"  // the directory must be created before the sessions will be saved there
let g:session_autoload = "no"                   // automatic reload sessions
let g:session_autosave = "no"                   // autosave
let g:session_command_aliases = 1

There is a good tutorial on YouTube.

jsouthwo
  • 15
  • 4
WALID BELRHALMIA
  • 441
  • 5
  • 12
2

Personally i just wrap over Tim Pope' s Obsession plugin to allow defining a sessiondir and avoid typing the path:

let g:sessiondir = $HOME . ".vim/sessions"

command! -nargs=1 MkSession call MkSession(<f-args>)
function! MkSession(sessionfile)
  if !isdirectory(g:sessiondir)
    call mkdir(g:sessiondir, "p")
  endif
  exe 'Obsession' g:sessiondir . '/' . a:sessionfile
endfunction

command! -nargs=1 LoadSession call LoadSession(<f-args>)
function! LoadSession(sessionfile)

  let a:sessionpath = g:sessiondir . a:sessionfile
  if (filereadable(a:sessionpath))
    exe 'source ' a:sessionpath
  else
    echo "No session loaded."
  endif
endfunction
archf
  • 181
  • 1
  • 3
  • i had specific problems with the Airline plugin and sessions. Switching to using Obsession fixed the issues, it was an amazing find after weeks of struggling. See https://github.com/vim-airline/vim-airline/issues/1505#issuecomment-316848122 – icc97 May 28 '18 at 00:50
1

Thanks @mathielo Following example from @mathielo, I added the below line to .vimrc to save the active session (if any):

au VimLeave * if this_session != "" | exe "mksession! ".this_session

If you want to put more lines, you need to use endif:

au VimLeave * if v:this_session != ""
au VimLeave *   exe "mksession! ".this_session
au VimLeave * endif

You only need to save a new session in vim with

:mks [Session filename]

and after start with

$ vim -S [Session filename]

vim will start the session and you don't need to worry to save the session every time you close vim.

If you don't have an active session .vimrc won't do anything. As before.

That's what I was looking for! Thanks again @mathielo!

oml
  • 115
  • 2
  • 8
  • This is what I was looking for too. Great ! I can't remember how many times I've lost my session doing `:q` instead of `:bd`... Thanks ! – Joel.O Sep 20 '16 at 17:40
  • For Neovim `au VimLeave * if !empty(v:this_session) | exe "mksession! ".(v:this_session) ` – Sumomo Jun 28 '21 at 14:03
0

You can store session wherever you want.

Ex:

:mksession! D:/session.ses

This stores the session in D drive.

This can be opened by typing

:so D:/session.ses

in any of the vim files.

Sagar Jain
  • 7,475
  • 12
  • 47
  • 83
0

Below is the only conf. that really worked for me. I took it from here, where you can also take a more complete/complex version.

set viewoptions+=cursor,folds,slash,unix
set viewoptions-=options

augroup vimrc
    autocmd BufWritePost *
    \   if expand('%') != '' && &buftype !~ 'nofile'
    \|      mkview
    \|  endif
    autocmd BufRead *
    \   if expand('%') != '' && &buftype !~ 'nofile'
    \|      silent loadview
    \|  endif
augroup END
JohnTortugo
  • 6,356
  • 7
  • 36
  • 69
0

For managing multiple sessions (on a per directory/repo basis), I've recently switched from the vim-session plugin to vim-workspace. Its session management is relatively simple and works pretty well.

jaybay
  • 31
  • 2