Alan Tam
Alan Tam

Reputation: 2057

Quit vim when all buffers are closed after :bd

I want to remap :q as :bd because I really don't want the buffer to stay around in a long-running vim session (where it can hold a .swp file conflicting with another vim session of the same file).

The only problem with that is :bd does not quit vim if it is the last buffer left. How can I achieve that?

Upvotes: 2

Views: 397

Answers (2)

Tom Hale
Tom Hale

Reputation: 46745

Two versions, one asking to save, and one quitting forcefully:

" Close the current buffer, quit vim if it's the last buffer
" Pass argument '!" to do so without asking to save
function! CloseBufferOrVim(force='')
  if len(filter(range(1, bufnr('$')), 'buflisted(v:val)')) == 1
    exec ("quit" . a:force)
    quit
  else
    exec ("bdelete" . a:force)
  endif
endfunction

nnoremap <silent> <Leader>q :call CloseBufferOrVim()<CR>
nnoremap <silent> <Leader>Q :call CloseBufferOrVim('!')<CR>

Upvotes: 1

Micah Elliott
Micah Elliott

Reputation: 10264

Something like this should work:

fun! s:quitiflast()
    bdelete
    let bufcnt = len(filter(range(1, bufnr('$')), 'buflisted(v:val)'))
    if bufcnt < 2
        echo 'shutting everything down'
        quit
    endif
endfun

command! Bd :call s:quitiflast()

cmap q Bd

Upvotes: 2

Related Questions