Grep in Emacs


M-x grep in Emacs is a great command and I use it quite often.

Most of the time, however, I need to explicitly specify -r and I am never sure what directory grep will start searching from.

Functions and packages, such as rgrep and igrep, help mitigate these nuisances, but I cannot get used to their interactive way of building the command.

I thus ended up writing my wrapper around grep which ensures -r is always present and starts searching from the “obvious” directory:

(defun mygrep ()
  "Run grep recursively from the directory of the current buffer or the default directory"
  (let ((dir (file-name-directory (or load-file-name buffer-file-name default-directory))))
    (let ((command (read-from-minibuffer "Run grep (like this): "
                                         (cons (concat "grep -nH -r  " dir) 13))))
          (grep command))))

The command is run on the directory of the current buffer or Emacs’ default directory, if the current buffer is not associated to any directory.

Add the previous code to your .emacs, invoke M-x mygrep, specify the search term and, in many cases, you are ready to go!