DEV Community

Serhat Teker
Serhat Teker

Posted on • Originally published at tech.serhatteker.com on

Close All Buffers Except the Current in Vim

Vim has default :tabonly for tabs and :only for windows to close them all except curren one, but there is no :bufferonly command.

You can use BufOnly plugin; just put it to your .vim/plugin then execute :BufOnly.

However this can be achieved with a script:

" close all buffers except current one
command! BufCurOnly execute '%bdelete|edit#|bdelete#'
Enter fullscreen mode Exit fullscreen mode

The %bdelete command deletes all buffers.

The # means the alternate filename. From :h _#:

# Is replaced with the alternate file name.   *:_#* *c_#*
  This is remembered for every window.
Enter fullscreen mode Exit fullscreen mode

Put this script in you .vimrc/$MYVIMRC, and then execute :BufCurOnly.

You can map this command to any keys as always:

" Close all buffers but current
nnoremap <C-B>c :BufCurOnly<CR>
Enter fullscreen mode Exit fullscreen mode

All done!

Discussion (0)