A.J.Mechelynck wrote:

Yes, using the :vimgrep command (Vim 7 and some versions of Vim 6) or the external "grep" command (earlier versions):

    :vimgrep /pattern/g ./**/*.[ch] " search the list of files
                                    " for the /pattern/
    :copen                          " open quickfix window

The second command above splits the Vim screen horizontally, with at bottom a window containing one line per match. Hit <Enter> on any line and the corresponding file is opened above the quickfix window, with the cursor on the corresponding match. Or use the commands

    :cfirst
    :cnext
    :cprevious
    :clast

to navigate the list of matches, with or without opening the quickfix window. When done, use

    :cclose

(regardless of which window is current at the time) to close the quickfix window.
As mentioned in :h vimgrep

           Without the 'j' flag Vim jumps to the first match.
           With 'j' only the quickfix list is updated.
           With the [!] any changes in the current buffer are
           abandoned.

I found it rather annoying that the initial search automatically jumped
to the first match, especially if one expects to get many results for
review.  So executing

:vimgrep /pattern/gj ./**/*

will leave the current buffer as it is, after which doing a :copen, one
can check all the different matches and go from there.

To expand on Tony's tip, I have made a quick-n-dirty function to search
your current directory for a pattern, as below.

" Grep function {{{
function! SearchCurrentDirectory()
   let s:pat=input("Grep: ")
   let s:path=input("Path to search (ENTER for pwd): ", "", "dir")
   let s:ext=input("File extension (ENTER for all files): ")
   if s:ext==""
       let s:ext="*"
   endif
   if s:path==""
       let s:path="."
   endif
   if s:pat!=""
       execute("vimgrep /".s:pat."/gj ".s:path."/**/*.".s:ext)
       copen
   endif
endfunction

nmap <silent> <F10> :execute SearchCurrentDirectory()<CR>
" }}} End Grep


Put the above in your vimrc file to load it on startup.

Another note to consider: in the quickfix window, you might want to open
a specific hit in a new window.  Pressing ENTER on the current line will
open the hit in the current window.  Pressing Ctrl-W ENTER, however,
opens a new window with the cursor on the selected instance of your
search pattern.

I can see I will be using this functionality extensively in the near future.

Happy Vimming!
--
Albie Janse van Rensburg (neonpill)

Registered Linux User 438873 | <http://counter.li.org>

Reply via email to