How can I close all buffers that are not displayed in a window in vim?


I have a horde of buffers open in vim, with only a few of them open in split windows or on other tabs. Is there a way to close all but the ones that are currently visible in one of those splits or tabs?

Here's an alternative solution you can drop in your .vimrc:

function! Wipeout()
  " list of *all* buffer numbers
  let l:buffers = range(1, bufnr('$'))

  " what tab page are we in?
  let l:currentTab = tabpagenr()
    " go through all tab pages
    let l:tab = 0
    while l:tab < tabpagenr('$')
      let l:tab += 1

      " go through all windows
      let l:win = 0
      while l:win < winnr('$')
        let l:win += 1
        " whatever buffer is in this window in this tab, remove it from
        " l:buffers list
        let l:thisbuf = winbufnr(l:win)
        call remove(l:buffers, index(l:buffers, l:thisbuf))

    " if there are any buffers left, delete them
    if len(l:buffers)
      execute 'bwipeout' join(l:buffers)
    " go back to our original tab page
    execute 'tabnext' l:currentTab

Use :call Wipeout().