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 :bdelete
s the current buffer if the length/size of that buffer is zero?
Just put it to your . vim/plugin directory and then use :BufOnly command to close all buffers but the active one.
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.
To clear the a register, for instance, I type q a q to set the a register to an empty string.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With