2

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?

Community
  • 1
  • 1
Alan Tam
  • 2,027
  • 1
  • 20
  • 33
  • 1
    Have you looked at [BBye](https://github.com/moll/vim-bbye)? It does state this, however, which may not satisfy your question: "Shows an empty file if you've got no other files open." – Micah Elliott Jul 24 '15 at 21:28
  • Thanks Micah. I actually don't need the fancy `BBye` features. I want `:q` to mean `:bd`, but just do `:q` (i.e. quitting `vim`) if this is the last buffer. – Alan Tam Jul 24 '15 at 21:39
  • 1
    Try this one: http://superuser.com/questions/668528/vim-quit-if-buffer-list-is-empty/930871#930871. – ryuichiro Jul 25 '15 at 20:57

2 Answers2

2

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
Micah Elliott
  • 9,600
  • 5
  • 51
  • 54
  • Plain `cmap q Bd` is a really bad idea, you won't be able to write any word containing "q" on the command line after that. See the [wiki](http://vim.wikia.com/wiki/Mapping_to_enter_colon_commands) for a better way to do it. – Sato Katsura Jul 25 '15 at 08:26
0

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>
Tom Hale
  • 40,825
  • 36
  • 187
  • 242