How do you search all source code in Vim?

Viewed 29387

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

8 Answers

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

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

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

Or use ctags.

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

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.

Nobody's mentioned it, but I use tend nowadays to use ripgrep

Related