Grep in Emacs

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

Two issues I have with the command: most of the times 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 problems, but I cannot get used to their interactive way of building the command.

The simplest solution is precompiling the query string with the right stuff, namely -r and the directory to start from … and, here it is, my small contribution to simplify searches with grep:

(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 precompiled with 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!

Get in touch