Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim: Wiping Out Buffers Editing Nonexistent Files

Tags:

vim

editor

buffer

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!

like image 336
void-pointer Avatar asked Feb 22 '23 20:02

void-pointer


2 Answers

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.
like image 122
ZyX Avatar answered Feb 26 '23 18:02

ZyX


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"?

like image 41
romainl Avatar answered Feb 26 '23 17:02

romainl