views:

712

answers:

6

When using Vim, and given a directory filled with code (e.g. ~/trunk/) with a number of sub-directories, is there a way to grep/search for instances of text/regexes across the entire source code?

At the moment I use:

:lcd ~/trunk
:grep "pattern" *.py */*.py */*/*.py */*/*/*.py

(Obviously I'm limiting this to Python files, which is a different issue, but it's noteworthy that ideally I'd like to limit the searches to files with specific extensions.)

Any suggestions would be appreciated. Thank you.

A: 

You could use :vimgrep i.e.:

  :vimgrep /pattern/ **/*.py

Check this Vim Tip:

Also give a look to grep.vim, it's a plugin that integrates the grep, fgrep, egrep, and agrep tools with Vim and allows you to search for a pattern in one or more files and jump to them...

CMS
+7  A: 
:vimgrep "pattern" ~/trunk/**/*.py
:copen 20

If you have quite a big project I'd recommend to you to use cscope and vim plugins. Here is one designed to handle big projects: SourceCodeObedience

There is a brief description of how to grep text using SourceCodeObedience.

Mykola Golubyev
This has saved me oodles of time. Oodles! Thanks!
Brian M. Hunt
Which one? vimgrep or .sco?
Mykola Golubyev
+2  A: 

I use grep directly for that.

grep -IirlZ "pattern" .|xargs -0 vim

-I: ignore binary
-i: ignore case
-r: recursive
-l: print file name only
-Z: print \0 after each file name
soulmerge
+1  A: 

You may want to check out :vimgrep and :grep in the vim documentation. :vimgrep uses vim's own pattern searching functionality and reads all files into vim buffers. :grep by default links to an external 'grep' utlity on your system, but you can change the behavior by setting the 'grepprg' option. Here's a link to the online docs:

http://vimdoc.sourceforge.net/htmldoc/quickfix.html#grep

There's more info on that and also some other options in the tip on "Find in files within Vim" at the Vim Tips Wiki:

http://vim.wikia.com/wiki/Find_in_files_within_Vim

Herbert Sitz
A: 

You can generate a source code index using ctags and then VIM can use this to navigate seamlessly through your code base. It's source code aware in that you can jump directly to method declarations etc.

You need to regenerate the ctags files every so often, but you can do that as part of your make process. It should be pretty fast unless your code base is sizeable.

Brian Agnew
How does this help to find symbol reference?
Mykola Golubyev
ctags will index your source code (in most languages). VIM has the capability to navigate via the ctags index, so you can position yourself over whatever symbol and then jump directly to the definition. Ctrl + ], I think.
Brian Agnew
A: 

Set grepprg to Ack, then use :grep to search with Ack.

Or use ctags.

George V. Reilly