Vim: reopen all previous files in a new session after restart

Viewed 1564

I usually have long lived vim session with dozens of files open. Once in a while, I need to restart vim, say to install a new plugin or apply some new config.

How can I reopen all the previous files after restart?

2 Answers

You can use builtin sessions, perhaps with vim-session plugin.

A Vim session contains all the information about what you are editing.

This includes things such as the file list, window layout, global variables, options and other information. (Exactly what is remembered is controlled by the 'sessionoptions' option.)

The command

:mksession mysession.vim

saves the current session into the named file. Next time you start vim you can load the session:

vim -S mysession.vim

or inside vim

:source mysession.vim

You can automate saving sessions on VimLeave autocommand and reload a session on VimEnter but be careful abut restoring a session when vim is called, e.g., from git.

Here is a basic setup of automatic session save / load extracted from my config:

let s:session_loaded = 1

augroup autosession
  " load last session on start
  " Note: without 'nested' filetypes are not restored.
  autocmd VimEnter * nested call s:session_vim_enter()
  autocmd VimLeavePre * call s:session_vim_leave()
augroup END

function! s:session_vim_enter()
    if bufnr('$') == 1 && bufname('%') == '' && !&mod && getline(1, '$') == ['']
        execute 'silent source ~/.vim/lastsession.vim'
    else
      let s:session_loaded = 0
    endif
endfunction

function! s:session_vim_leave()
  if s:session_loaded == 1
    let sessionoptions = &sessionoptions
    try
        set sessionoptions-=options
        set sessionoptions+=tabpages
        execute 'mksession! ~/.vim/lastsession.vim'
    finally
        let &sessionoptions = sessionoptions
    endtry
  endif
endfunction

It will only restore the session if you run vim without arguments, so if you do vim somefile.txt to do the quick edit, it will not touch the last session.

Bonus (this will restore cursor position inside files too):

" When editing a file, always jump to the last known cursor position.
" Don't do it when the position is invalid or when inside an event
" handler.
autocmd MyAutoCmd BufReadPost *
    \ if line("'\"") > 0 |
    \   if line("'\"") <= line("$") |
    \     exe("norm '\"") |
    \   else |
    \     exe "norm $" |
    \   endif|
    \ endif
Related