SwiftMango
SwiftMango

Reputation: 15294

How to delete a buffer when the window is closed?

When I have a new temporary buffer/window and I just do :q, it quits the window but do not clean the buffer. When I quit Vim, it will always popup and tell me there is No write since last change for buffer [No Name].

I have the option for hidden and bufhidden

set hidden
set bufhidden=wipe

It closes the window without warning, but still popup when closing the whole Vim program.

I tried to add an autocmd:

au BufLeave * bw

It works when I quit a window, but will clean the buffer when I want to just open a new window/tab (as it does not distinguish switch window and close window). I also tried BufWinLeave and WinLeave, I did not achieve what I need.


I came up with something like:

function! OnBufHidden()
  if expand("<afile>") == ""
    execute ":bw! " . expand("<abuf>")
  endif
endf


set hidden
autocmd BufHidden * call OnBufHidden()

It should work but it does not. The execute is executed because I tried with some echo inside, but not sure why bw! is not executed.

Upvotes: 2

Views: 574

Answers (2)

Ingo Karkat
Ingo Karkat

Reputation: 172738

With :set bufhidden=wipe, the buffer's contents are lost without confirmation, but only if it is hidden (e.g. via :hide) first; :set hidden doesn't do this, it just enables hiding. If you use :q and the buffer is still visible, you'll get the confirmation.

To get what you want, also :setlocal buftype=nofile (as in @romainl's answer). Then, you'll never get a confirmation.

Upvotes: 1

romainl
romainl

Reputation: 196816

You can create a scratch buffer in a vertical scratch window with this command:

command! SC vnew | setlocal nobuflisted buftype=nofile bufhidden=wipe noswapfile

Upvotes: 2

Related Questions