Search code examples
vimautocmd

is it possible to set BufLeave autocmd in vim on the fly?


What I want to do:

Inside a file/buffer in vim, especially an unnamed one (for example, created with :enew), sometimes I feel the content I'm writing is worth saving (say, I suddenly want to send it via an email), but don't feel the particular need to save it to a temp file, nor do I trust myself enough to "remember" to save it upon exit.

So I thought, what if I run

autocmd BufLeave * ggvG"+y

in the vim command line once and be free from the fear of losing this content.

But it doesn't work. When I exit vim, the system clipboard reminds intact.

My questions:

  • does it do anything if we run autocmd on the fly, as opposed to in vimrc?
  • is there a way to tell vim to "hey, when you exit, run these"?

Thanks a ton!


Solution

  • Two problems:

    1) You didn't leave the buffer to go to another buffer (BufLeave); you left Vim (VimLeave).

    2) autocmd expects a command, not normal mode keystrokes.

    With that in mind,

    autocmd VimLeave * normal gg"+yG