How to delete multiple buffers in Vim?

后端 未结 8 1325
北恋
北恋 2021-01-29 18:51

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 w

8条回答
  •  礼貌的吻别
    2021-01-29 19:26

    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 bd :bufdo call DeleteBufferByExtension("txt")
    
    function!  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 bd :call DeleteBufferByExtension("txt")
    
    function!  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
    

提交回复
热议问题