How do I search the open buffers in Vim?

后端 未结 6 586
陌清茗
陌清茗 2020-12-23 16:36

I\'d like to search for text in all files currently open in vim and display all results in a single place. There are two problems, I guess:

  • I can\'t pass the li
6条回答
  •  无人及你
    2020-12-23 17:05

    I really liked romainl's answer, but there were a few sticky edges that made it awkward to use in practice.

    The following in your .vimrc file introduces a user command Gall (Grep all) that addresses the issues that I found irksome.

    funct! GallFunction(re)
      cexpr []
      execute 'silent! noautocmd bufdo vimgrepadd /' . a:re . '/j %'
      cw  
    endfunct
    
    command! -nargs=1 Gall call GallFunction()
    

    This will allow case-sensitive searches like this:

    :Gall Error\C
    

    and case-insensitive:

    :Gall error
    

    and with spaces:

    :Gall fn run
    

    Pros

    • It will only open the Quickfix window, nothing else.
    • It will clear the Quickfix window first before vimgrepadd-ing results from each buffer.
    • The Quickfix window will contain the locations of all matches throughout the open buffers, not just the last visited.
    • Use :Gall repeatedly without any special housekeeping between calls.
    • Doesn't wait on errors and displays results immediately.
    • Doesn't allow any autocmd to run, speeding up the overall operation.

    Ambivalent features

    • Doesn't preemptively jump to any occurrence in the list. :cn gets second result or CTRL-w b to get to the first result directly.

    Cons

    • If there's only one result, you'll have to navigate to it manually with CTRL-w b .

    To navigate to a result in any buffer quickly:

    :[count]cn
    

    or

    :[count]cp
    

    E.g. :6cn to skip 6 results down the list, and navigate to the correct buffer and line in the "main" window.

    Obviously, window navigation is essential:

    Ctrl-w w "next window (you'll need this at a bare minimum)
    
    Ctrl-w t Ctrl-w o "go to the top window then close everything else
    
    Ctrl-w c "close the current window, i.e. usually the Quickfix window
    
    :ccl "close Quickfix window
    

    If you close the Quickfix window, then need the results again, just use:

    :cw
    

    or

    :copen
    

    to get it back.

提交回复
热议问题