2014-12-20 Grepping from within Emacs

It is a well-known fact that a hacker’s life without grep(1) would be rather terrible. It is extremely useful. It is a bit less known that a hacker’s life without Emacs is rather terrible. However, given two great tools, one wonders whether they could not be made to work together?

Oh yes, they could. Starting grep from within Emacs is not only possible, but also advisible, for reasons I will explain in a minute.

A quick C-h a grep RET shows (among others) the commands grep-find, grep, lgrep and rgrep. (There are more, but we will deal with these basic ones only.)

The most basic of them is just grep. It shows a prompt saying grep -nH -e, which means that the only thing you have to do is to type the search pattern (a regex) and a list of filenames (possibly with wildcard(s)). What is more Emacs-y than just running M-! grep ... is that the results are shown in a buffer put in grep-mode, which inherits from compilation-mode. This means that you can do all sorts of cool stuff there – just press C-h m to see for yourself. Two highlights are: M-n and M-p for the next and previous match (respectively), C-c C-c (or just RET) to jump to the file and position shown at point, and (probably the coolest trick) C-c C-f to enable next-error-follow-minor-mode, which shows the match in another window dynamically, i.e., just moving point in the *grep* buffer causes Emacs to show the match in context.

Now the disadvantage to this is that you have to remember to give the pattern first and the filename(s) next (which is kind of obvious, but anyway), and – which is more cumbersome – to quote things like backslashes properly. Both these problems are addressed by lgrep, which asks for the pattern to search (conveniently deriving the default from the word at point), then the filename(s) (conveniently deriving the default from the current file’s extension) and finally the directory (conveniently deriving the default from the current dir). Prefixed with C-u it even allows to modify the actual command line before execution. All that is really useful.

What is a real pain in the neck, however, is grepping recursively. Yes, there is grep -r, but for more complicated searches a combination of find and grep is needed, and anyone knows that the only thing worse than the syntax of find(1) is the syntax of tar(1). Yes, Emacs has grep-find, which gives a template for a find/grep combo, but one yearns for something more. And something more there is indeed: rgrep. Just like lgrep is a wrapper around grep itself, rgrep is a wrapper around a find/grep engine, with similar features.

As I said, there is more than that, but this covers at leasts the basics of searching files from within Emacs. Happy grepping!

CategoryEnglish, CategoryBlog, CategoryEmacs