How do I search the open buffers in Vim?

Viewed 21733

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 list of open files to :grep/:vim, especially the names of files that aren't on the disk;
  • The result of :grep -C 1 text doesn't look good in the quickfix window.

Here is a nice example of multiple file search in Sublime Text 2:enter image description here

Any ideas?

6 Answers

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(<q-args>)

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 <enter> 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 <enter>.

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.

Related