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

前端 未结 8 667
孤城傲影
孤城傲影 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 04:59

    I have a muscle-memory habit of typing ":q!", which I haven't been able to shake. This gets very tedious, if I've got multiple buffers open in a vi session. So - what I needed was a way of simply recovering where I was when I accidentally shot myself in the foot. Again.

    This is slightly complicated by the fact that I might have multiple ssh sessions open at any one time, each with a different set of buffers/windows open in vi. I needed a way of saving the session separately for each different ssh session.

    The solution I came up with builds on 2ck's answer, and is as follows. In your ~/.vimrc:

    " tty is unique to the ssh session
    let my_full_tty=$SSH_TTY
    " scoop the number off the end of it
    let my_tty_num = matchstr(my_full_tty, '\d\{1,}$')
    " create a unique filename
    let g:my_vim_session = "~/vim_session." . my_tty_num
    
    fu! SaveSess()
        execute 'mksession! ' . g:my_vim_session
    endfunction
    
    fu! RestoreSess()
        let file = expand(g:my_vim_session)
        if filereadable(file)
            execute 'source ' . g:my_vim_session
        endif
    endfunction
    
    autocmd VimLeave * call SaveSess()
    " only restore the session if the user has -not- requested a specific filename
    autocmd VimEnter * if !argc() | call RestoreSess() | endif
    

    But, of course, I don't want loads of ~/vim_session.? lying around, so I periodically cleanup. (I may re-think this, actually, because what happens if my ssh disconnects unexpectedly? hmmm)

    In your .bashrc:

    trap ~/bash_exit_script.pl EXIT
    

    and in bash_exit_script.pl:

    #! /usr/bin/perl
    
    use warnings;
    use strict;
    
    my $ssh_tty = $ENV{SSH_TTY};
    $ssh_tty =~ /(\d{1,}$)/; 
    my $my_tty_number = $1;
    
    my $filename = "/home/dominic.pain/vim_session.$my_tty_number";
    if(-e $filename) {
        print "tried to remove $filename...\n";
        system("rm $filename");
    }      
    else {
        print "Couldn't find $filename\n";
    }
    

提交回复
热议问题