How can I execute a command when the buffer is closed in vim?
Is there something like closing the window in vim / vimscript so that I can call the function every time the window is closed?
I want to use it for the following scenario: I am using an additional scratch window to display file information, and when I close the file, I want the scratch window to close automatically, so that vim exits.
If you have any ideas on how to achieve this without a hook, that would be just as good.
edit: I know about :qa[ll]
, but I'm lazy and only want to print :q
or ZZ
.
edit2.71828183: I accepted the autocommand's answer as it was closest to the original question, but found another solution in using a preview window instead of a broken window. The preview window is automatically closed when the last "normal" window is closed.
source to share
auto teams are awesome! I'm sure this will BufLeave
do the job in this case , but you might want to BufWinLeave
? Look :help autocmd-events
for a complete list of events.
Another bit you'll take care of is this: you can have buffered local autocommands! ( :help autocmd-buflocal
)
You can define one for the current buffer using au BufLeave <buffer> ...
. My best guess is that you can run this on any command that creates a zero window. You should be able to cache the zero window buffer number in a global variable when you open window zero, then your autocommand can simply delete that buffer ( :help :bdelete
).
au BufLeave <buffer> bdelete g:scratch_buffer
call CreateScratchWindow()
function CreateScratchWindow() {
...
let g:scratch_buffer = bufnr("")
}
There is also a winbufnr function to get the buffer numbers for a window. You can use one of these - just make sure the window / scratch buffer is current when you use it! ("" Indicates the current window / buffer).
source to share
Ok, not exactly a new question, but I found it, which I now know is BufWinLeave
. However, the scenario that the author describes is in my vimrc
c NerdTree
, for example. when the last buffer is closed, I want vim to close the buffer NerdTree
"and then exit.
autocmd bufenter * if (winnr("$") == 1 && exists("b:NERDTree") && b:NERDTree.isTabTree()) | q | endif
Replace the specific material NerdTree
with how the buffer is identified scratch
.
source to share