tags:

views:

120

answers:

2

Assuming I have multiple files opened as buffers in Vim. The files have *.cpp, *.h and some are *.xml. I want to close all the xml files with :bd *.xml. However, Vim does not allow this (E93: More than one match...).

Is there any way to do this?

P.S. I know that :bd file1 file2 file3 ... works. So can I somehow evaluate *.xml to file1.xml file2.xml etc. ?

+1  A: 

You can use this.

:exe 'bd '. join(filter(map(copy(range(1, bufnr('$'))), 'bufname(v:val)'), 'v:val =~ "\.xml$"'), ' ')

It should be quite easy to add it to a command.

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>)
Luc Hermitte
I know next to nothing about Vimscript, but how about glob() function?
Thanh DK
`glob()` will only give you existing files (on your hard drive), and not opened buffers.
Luc Hermitte
A: 

Try the script below. The example is for "txt", change it as needed, e.g. to "xml". Modified buffers are not deleted. Press \bd to delete the buffers.

map <Leader>bd :bufdo call <SID>DeleteBufferByExtension("txt")

function!  <SID>DeleteBufferByExtension(strExt)
   if (matchstr(bufname("%"), ".".a:strExt."$") == ".".a:strExt )
      if (! &modified)
         bd
      endif
   endif
endfunction

[Edit] Same without :bufdo (as requested by Luc Hermitte, see comment below)

map <Leader>bd :call <SID>DeleteBufferByExtension("txt")

function!  <SID>DeleteBufferByExtension(strExt)
   let s:bufNr = bufnr("$")
   while s:bufNr > 0
       if buflisted(s:bufNr)
           if (matchstr(bufname(s:bufNr), ".".a:strExt."$") == ".".a:strExt )
              if getbufvar(s:bufNr, '&modified') == 0
                 execute "bd ".s:bufNr
              endif
           endif
       endif
       let s:bufNr = s:bufNr-1
   endwhile
endfunction
Habi
I don't like `:bufdo` as it messes the current window.
Luc Hermitte
o.k., I will rework it
Habi
Done. See [Edit] above.
Habi