Often when I'm editing in Vim, I end up restoring a Vim session that refers to a some files in a directory that was moved. The problem occurs after I use :n
to open all of the files located in the new directory. Now, when I use :b <buffer-name>
to switch to the buffer editing a particular file located in the new directory, there is an ambiguity: two buffers are opened on files with the same name, and one of these files does not exist. So I'm forced to use :ls
, manually search for the indices of buffers that are editing nonexistent files, and call :bw
on each one of them. Is there some simple command that will automatically wipe out the buffers editing nonexistent files for me?
Also, after manually wiping out the offending buffers, there are abrupt breaks in the indices between consecutive buffers, which makes switching between buffers using :<n>b
more difficult. Is there a command that will re-index the buffers for me so that the set of indices is some contiguous range?
Thanks for your help!
Try the following command:
function s:WipeBuffersWithoutFiles()
let bufs=filter(range(1, bufnr('$')), 'bufexists(v:val) && '.
\'empty(getbufvar(v:val, "&buftype")) && '.
\'!filereadable(bufname(v:val))')
if !empty(bufs)
execute 'bwipeout' join(bufs)
endif
endfunction
command BWnex call s:WipeBuffersWithoutFiles()
Usage:
:BWnex<CR>
Note some tricks:
filter(range(1, bufnr('$')), 'bufexists(v:val)')
will present you a list of all buffers (buffer numbers) that vim currently has.empty(getbufvar(v:val, '&buftype'))
checks whether buffer actually should have a file. There are some plugins opening buffers that are never supposed to be represented in filesystem: for example, buffer with a list of currently opened buffers emitted by plugins such as minibufexplorer. These buffers always have &buftype
set to something like nofile
, normal buffers have empty buftype.Aren't buffers supposed to be unique?
After this sequence of commands:
:e .bashrc
:e .profile
:e .bashrc
:e .profile
:e .bashrc
:e .profile
:e .bashrc
:e .profile
:e .bashrc
I still have only two buffers available as shown by :buffers
or :ls
: .bashrc
and .profile
. Even if I use multiple windows and tabs.
Are you confusing "buffers" with "windows"?
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