1

I'd like to save my session before vim exits. Here's what I have so far:

function SaveSession()
    let l:new_session = trim(inputdialog("Enter new session name: ", v:this_session, -1))

    if l:new_session == -1
        return
    endif

    execute "mksession! " . l:new_session
endfunction

autocmd ExitPre * call SaveSession()

This usually works, but if mksession barfs vim exits without displaying the error and giving me a chance to react, causing me to lose my session.

According to :help ExitPre, it sounds like it's possible to prevent it from exiting:

ExitPre         When using `:quit`, `:wq` in a way it makes
                Vim exit, or using `:qall`, just after
                |QuitPre|.  Can be used to close any
                non-essential window.  Exiting may still be
                cancelled if there is a modified buffer that
                isn't automatically saved, use |VimLeavePre|
                for really exiting.

Is there an event I can raise or an exception I can throw? My only other idea is to create a new file with changes in it, but it feels hacky.

2
  • Welcome to Vi and Vim!
    – D. Ben Knoble
    Jun 25, 2021 at 18:26
  • My read on that help is that you cannot prevent vim from exiting, but an unsaved modified buffer will.
    – D. Ben Knoble
    Jun 25, 2021 at 18:26

1 Answer 1

0

I fiddled with it a bit more and came up with this:

function SaveSession()
    let l:new_session = trim(inputdialog("Enter new session name: ", v:this_session, -1))

    if l:new_session == -1
        return
    endif

    while 1
        try
            execute "mksession! " . l:new_session
            return
        catch
            echohl ErrorMsg | echo "\n" . v:exception | echohl None
            let l:choice = confirm("Try again?", "&Yes\n&No", 2)

            if l:choice != 1
                return
            endif
        endtry
    endwhile
endfunction

It works, but I'd prefer to cancel the event if possible unless there's a more elegant solution out there.

1
  • What if you get rid of the loop and return in the catch?
    – Biggybi
    Mar 22, 2022 at 7:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.