Vim has a command called
:help :grep), which is used for searching plain text across the project. Internally it uses the *nix
grep utility to perform the search. However, the
grep utility is very slow, especially for larger projects, which means you might want to use something else like
ag (follow the instructions given in the official repo for installation).
When we execute let's say
:grep text_to_find in Vim, it will look at the value of the option called
:help 'grepprg'), replace
text_to_find, and then pass it to the shell for execution. We can change the value of
'grepprg' to use
ag instead of the default, which is
Add the following to your
if executable('ag') set grepprg=ag\ --vimgrep\ $* set grepformat^=%f:%l:%c:%m endif
Checking whether or not
ag is installed in the system (
:help executable()) before changing the value of
'grepprg' will allow us to safely copy the configuration to any other system where
ag might not be available, without the fear of breaking Vim.
--vimgrep option passed to
ag makes it print the matches to the standard output in the
%f:%l:%c:%m format (
:help errorformat). Vim doesn't recognise this format by default, so we need to tell it explicitly. This is done using another option called
:help 'grepformat') which already has a couple of defaults. We just need to add our own format at the very beginning using the
:help :set^=) assignment operator. The reason we add our format to the very beginning is because otherwise one of the default values (
%f:%l:%m) will match, resulting in Vim considering the column number and the actual match as part of
%m. We need Vim to recognise the column number separately so that it can use the information to place the cursor at the proper column while navigating the searches.
Navigating the searches
You can now use Vim's quickfix list (
:help quickfix.txt) to navigate your searches.