5

Can I close all buffers by regex, for instance all buffers that hold open .js files?

Effectively what I want is

:bd *.js

But even with ! if more than one .js is open I get,

E93: More than one match for *.js

2 Answers 2

9

Your question is answered on a duplicate from one on StackOverflow:

Use <C-A> to expand the *.js on the command line.

This way :bd *.js will become :bd file1.js file2.js file42.js.

My loop-free answer (in case more control is required) was:

function! s:BDExt(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 BDExt :call s:BDExt(<f-args>)
0

You could probably use a function to do this:

function! CloseByRegex(re)
    for b in range(1, bufnr('$'))
        if bufname(b) =~ re
            exec "bd" b
        endif
    endfor
endfunction

bufnr('$') is the number of the last buffer.

1
  • IIRC, range(bufnr('$')) will exclude the last buffer number, and it starts at 0, which is no valid buffer. Commented Jun 7, 2017 at 5:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.