Project wide search VIM word under cursor Arpit Jain, 2022-04-18 | 5 mins

This blog illustrates the trick to search word under the cursor throughout the project and not just current file.

Problem statement

We all know # and * can be used to search for word under cursor in current file. But how do we search for word under cursor in entire project ?! This is a fairly common use case when we want to check all usages of a method in our entire project OR just search for a string in project wide. Let us see how we can achieve the same.

Prerequisites

Vim has an awesome plugin FZF which we can be used with Ag (Silver searcher) OR Rg (Ripgrep) for fuzzy search. Using which we can setup project wide search.

Following the above documentation we should now have :Rg as a command available in vim.

Solution

However we still need to provide a pattern to it manually, which is slow and error prone. And obviously we being one of the laziest beings on the planet don’t want it to be manual, so how to automate searching word under cursor project wide ?

Vimscript is here to help, let us check it out.

nnoremap <leader>rg :execute ":Rg " . expand("<cword>")<cr>

Now all we need to do is, navigate to the word which we need to search throughout the project, and just preset <space> + rg.

Explanation

Adding above line of code to our vimconfig gets the job done, but how ? We have a new command so we need a mapping for it, which is what <leader>rg corresponds to.

:Rg as a command is already available through FZF setup but now we need to get the word under the cursor, this is where <cword> helps us out, it is a special keyword which gets us the word under the cursor. So we just provide it as an input to :Rg command

<cr> represents the return character that we need to provide once we have provided the input text in order to execute the command

Since we have dynamicallly built up the command, the expand is used to force the expansion of <cword> into actual string before executing the command.

No, suggestions available right now