DEV Community

loading...

How to delete multiple buffers in Vim

serhatteker profile image Serhat Teker Originally published at tech.serhatteker.com on ・1 min read

Let assume that I have multiple files opened as buffers in Vim. The files are *.py, *.md and some *.html.

I want to close all the HTML files with :bd *.html. However, Vim does not allow this; It throws an error: E93: More than one match for *.md.

So how can we achieve this?

0. Basic Way

The basic way would be writing all file names and using :bd[elete]:

:bd file1.html file2.html file3.html
Enter fullscreen mode Exit fullscreen mode

1. Exe Way

You can use buffer numbers:

Execute :ls, which lists all buffers, then pick the buffers that you want to close. For instance:

:2,7bd[elete]
Enter fullscreen mode Exit fullscreen mode

deletes buffer range from 2 to 7.

2. Vim Way (Preferred method)

If you exe :bd *.html and then press <C-a> it completes all file matches.

3. Vim Script Way

If you usually execute :bd and don't want to use Vim Way then you can write a vim script:

function! s:DeleteBufferByExtension(ext)
  let buffers = filter(range(1, bufnr('$')), 'buflisted(v:val) && bufname(v:val) =~ "\.'.a:ext.'$"')
  if empty(buffers) |throw "no *.".a:ext." buffer" | endif
  exe 'bd '.join(buffers, ' ')
endfunction

command! -nargs=1 DeleteBufferByExtension :call s:DeleteBufferByExtension(<f-args>)
Enter fullscreen mode Exit fullscreen mode

This function takes file extenstion as an arg, find files with this
extension and execute :bd. It can be run like below:

:DeleteBufferByExtension html
Enter fullscreen mode Exit fullscreen mode

You can map this function to a key as well.

All done!

Discussion (0)

pic
Editor guide