Search code examples
sessionconfigurationvim

How to auto save vim session on quit and auto reload on start including split window state?


I like to split my vim screen in 3. one :vsplit and one :split. I want these windows and the files I worked on to be saved when I close vim. I also want these windows to automatically load when I start vim.

I tried to install gsessions (just added the file to the plugin folder), but nothing happend. I am new to vim so I don't know exactly how the configuration works.


Solution

  • You can do per directory sessions with this is your vimrc:

    fu! SaveSess()
        execute 'call mkdir(%:p:h/.vim)'
        execute 'mksession! %:p:h/.vim/session.vim'
    endfunction
    
    fu! RestoreSess()
    execute 'so %:p:h/.vim/session.vim'
    if bufexists(1)
        for l in range(1, bufnr('$'))
            if bufwinnr(l) == -1
                exec 'sbuffer ' . l
            endif
        endfor
    endif
    endfunction
    
    autocmd VimLeave * call SaveSess()
    autocmd VimEnter * call RestoreSess()
    

    That will litter your directories with .vim s, but you can easily modify that. Also, change sbuffer to badd if you don't want new windows for each file and add ssop-=buffers to your vimrc.