Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all empty buffers in Vim?

Tags:

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?

like image 868
eeeeaaii Avatar asked Jul 01 '11 19:07

eeeeaaii


People also ask

How do I close all buffers in Vim?

Just put it to your . vim/plugin directory and then use :BufOnly command to close all buffers but the active one.

What is a Vim buffer?

A buffer is an area of Vim's memory used to hold text read from a file. In addition, an empty buffer with no associated file can be created to allow the entry of text. The :e filename command can edit an existing file or a new file.

How do I delete a register in Vim?

To clear the a register, for instance, I type q a q to set the a register to an empty string.


1 Answers

Since it is not allowed to affect the buffer list with a :bufdo-argument command (see :help :bufdo), we have to use a more wordy yet fairly straightforward Vim script.

The function below enumerates all existing buffer numbers and deletes those that do not have a name (displayed as [No Name] in the interface) nor any unsaved changes. The latter condition is guaranteed through the invocation of the :bdelete command without the trailing ! sign, in which case modified buffers are skipped.

function! DeleteEmptyBuffers()
    let [i, n; empty] = [1, bufnr('$')]
    while i <= n
        if bufexists(i) && bufname(i) == ''
            call add(empty, i)
        endif
        let i += 1
    endwhile
    if len(empty) > 0
        exe 'bdelete' join(empty)
    endif
endfunction

If you would like to delete empty buffers completely, including the unloaded ones, consider (with care!) replacing the exe 'bdelete' with exe 'bwipeout' (see :help :bd, :help :bw).

To test the contents of a buffer, use the getbufline() function. For instance, to be absolutely sure that the buffer contains no text in it, modify the if statement inside the while loop as follows:

        if bufloaded(i) && bufname(i) == '' && getbufline(i, 1, 2) == ['']

Note that bufexists() is changed to bufloaded() here. It is necessary because it is possible to get the contents only of those buffers that are loaded; for unloaded buffers getbufline() returns an empty list regardless of their contents.

like image 186
ib. Avatar answered Oct 06 '22 00:10

ib.