Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to grep in Vim

📅 2017-Sep-14 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

  When you are editing files in Vim, you might feel like finding out which other files have a certain text. Vim has such grep features built into it to support this usage. There are many popular Vim plugins that offer similar features, but you might want to first examine what Vim grep offers. In my opinion, most users should find the grep features built inside Vim to be quite adequate for their use.

Right off the bat, you need to know that there are two types of grep that are available in Vim: internal grep and external grep.

And you should remember that all grep operations operate from the present working directory (PWD) of Vim. You can check what is the PWD using the command :pwd. So, it is to your advantage to invoke Vim from the base directory of a code base.

Internal grep

This is the grep feature that is implemented inside Vim. Not surprisingly, this internal grep is far easier to use compared to Unix grep. However, it is also noticeably slower compared to Unix grep, for obvious reasons. However, the ease of use of internal grep is so high that I tend to prefer it over external grep.

The command to invoke internal grep is :vimgrep. But, you can use the short form :vim. Yeah this is the one command that won the Vim lottery to have the same name as the editor! 😄

This command in its most common form takes two arguments: the pattern to search for and which files to search for.

External grep

External grep is nothing but Vim invoking the commandline grep in a shell child process. This is super dumb: Vim just invokes whatever you pass it verbatim and grabs the grep output, parses it and fills it in the Quickfix window.

Quickfix window trick to browse code

No matter whether you use internal or external grep, its results are filled in the Quickfix window. As you do new searches, new Quickfix windows are created and the latest one is displayed at the bottom. You can move through this list of Quickfix windows using the :colder and :cnewer commands.

With these grep features and Quickfix window history Vim can be used as an rudimentary IDE to examine a code base: use the grep commands to search for text (variables, methods or classes) and jump to them. And you can move back and forth in this investigation using the Quickfix window commands described above.

Tried with: Vim 7.4 and Kubuntu 16.04