Search project for current word


You probably already know that pressing * on a word in Vim will jump to the next occurrence of that word in a file. Here’s a mapping for your .vimrc that will extend that functionality to search across your entire project.

We know from your feedback that not all of our readers can extend Vim with their own configurations either because they’re using Vim only on ephemeral remote systems or because they are using Vim mode in other environments. But for those of you who love to extend and trick out your Vim config, try this out:

map <leader>* :grep -R <cword> * --exclude-dir={.git,tmp,log}<CR><CR>

By adding this line to the .vimrc file in your home directory, you’re given a command that’s invoked with <leader>*, making it just one extra key press to search your entire project for the word under your cursor. (You may recall that the default <leader> key in Vim is \, so the default way to invoke this command would be \* on top of a word.)

The command uses your system grep command to do a recursive search through the entire directory, excluding the directories .git, tmp, and log. Feel free to extend that list to your liking or use a different search took. Two popular ones are ack and ag.

I myself don’t use any of those, but rather the :Ggrep command which comes with Fugitive, the Git plugin for Vim. Fugitive uses git grep to automatically search just the files in Git. I use this in conjunction with Unimpaired, and it allows me to rapidly move through the matching results with ]q and [q.

Here’s my mapping for <leader>* using :Ggrep:

map <leader>* :Ggrep --untracked <cword><CR><CR>

Watch this short screencast showing how effortless it is to find other occurrences of the current current word within the project:

First I press\* and the search instantly pulls up a list of results in the Quickfix window. Then I open that list with :cwin and from here I can page through with ]q and [q.

If you found this useful, would you mind tweeting about it? I’m trying to grow the Twitter following of @vim_tricks. Thanks! 🙏

How useful was this tip?

Average rating 3.3 / 5. Vote count: 493

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

105 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts