3

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
5

Your question is a duplicate of the following question on SO: https://stackoverflow.com/questions/3155461/how-to-delete-multiple-buffers-in-vim

The accepted answer being: use CTRL-A 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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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