How do I close all buffers that aren't shown in a window in vim?

后端 未结 5 1667
野趣味
野趣味 2020-12-23 16:23

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 i

5条回答
  •  失恋的感觉
    2020-12-23 17:28

    Add this to your .vimrc:

    function! CloseHiddenBuffers()
      let i = 0
      let n = bufnr('$')
      while i < n
        let i = i + 1
        if bufloaded(i) && bufwinnr(i) < 0
          exe 'bd ' . i
        endif
      endwhile
    endfun
    

    Then you can do this to close hidden buffers:

    :call CloseHiddenBuffers()
    

    (You'll probably want to bind a key or a command to it.)

    Update:

    Here's a version updated to support tab pages. (I don't use tab pages myself, so I hadn't realized that bufwinnr only works for windows on the current page).

    function! CloseHiddenBuffers()
      " figure out which buffers are visible in any tab
      let visible = {}
      for t in range(1, tabpagenr('$'))
        for b in tabpagebuflist(t)
          let visible[b] = 1
        endfor
      endfor
      " close any buffer that's loaded and not visible
      for b in range(1, bufnr('$'))
        if bufloaded(b) && !has_key(visible, b)
          exe 'bd ' . b
        endif
      endfor
    endfun
    

提交回复
热议问题