How to delete all empty buffers in Vim?

Viewed 4716

I have something like 120 buffers open in Vim right now. About 50% of these buffers are empty files. I would like to somehow use the :bufdo! command to close all the buffers that are empty. Is there a way I can say:

:bufdo! ‹cmd›

Where ‹cmd› is a conditional command that :bdeletes the current buffer if the length/size of that buffer is zero?

3 Answers

I've been using the following function to do the job:

function! s:CleanEmptyBuffers()
    let buffers = filter(range(1, bufnr('$')), 'buflisted(v:val) && empty(bufname(v:val)) && bufwinnr(v:val)<0 && !getbufvar(v:val, "&mod")')
    if !empty(buffers)
        exe 'bw ' . join(buffers, ' ')
    endif
endfunction

It's very similar to ib's version except that it leaves the quickfix buffer alone (as long as any other empty buffer that is displayed in a window)

Related