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

前端 未结 8 669
孤城傲影
孤城傲影 2020-12-13 04:35

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 aut

相关标签:
8条回答
  • 2020-12-13 05:16

    tpope's vim-obsession is the best thing for this now, released after the question was originally asked.

    Use :Obsess (with optional file/directory name) to start recording to a session file and :Obsess! to stop and throw it away. That's it. Load a session in the usual manner: vim -S, or :source it.

    • Instead of making me remember to capture the session immediately before exiting Vim, allow me to do it at any time, and automatically re-invoke :mksession immediately before exit.
    • Also invoke :mksession whenever the layout changes (in particular, on BufEnter), so that even if Vim exits abnormally, I'm good to go.
    • If I load an existing session, automatically keep it updated as above.
    • If I try to create a new session on top of an existing session, don't refuse to overwrite it. Just do what I mean.
    0 讨论(0)
  • 2020-12-13 05:19

    I modified 2ck's script slightly to save a .session.vim in your current working directory instead of the directory where your current open file is in.

    Also, it checks if the file exists before sourcing it.

    fu! SaveSess()
        execute 'mksession! ' . getcwd() . '/.session.vim'
    endfunction
    
    fu! RestoreSess()
    if filereadable(getcwd() . '/.session.vim')
        execute 'so ' . getcwd() . '/.session.vim'
        if bufexists(1)
            for l in range(1, bufnr('$'))
                if bufwinnr(l) == -1
                    exec 'sbuffer ' . l
                endif
            endfor
        endif
    endif
    endfunction
    
    autocmd VimLeave * call SaveSess()
    autocmd VimEnter * nested call RestoreSess()
    
    0 讨论(0)
提交回复
热议问题