cfrost
cfrost

Reputation: 13

Emacs grep-find on selection

It is quite common that when I use grep-find in emacs I want to search for the text I have selected. My current workaround to this is to select the text, then M-x grep-find and paste the selection. How do I make a keybinding that does this automatically?

Upvotes: 1

Views: 814

Answers (1)

abo-abo
abo-abo

Reputation: 20342

Here's a modified grep-find - if the region is active, search of region contents. It seems to work on my system:

(defun grep-find (command-args)
  "Run grep via find, with user-specified args COMMAND-ARGS.
Collect output in a buffer.
While find runs asynchronously, you can use the \\[next-error] command
to find the text that grep hits refer to.

This command uses a special history list for its arguments, so you can
easily repeat a find command."
  (interactive
   (progn
     (grep-compute-defaults)
     (if grep-find-command
         (list
          (read-shell-command
           "Run find (like this): "
           (if (region-active-p)
               (let ((str
                      (buffer-substring-no-properties
                       (region-beginning)
                       (region-end))))
                 (cons (replace-regexp-in-string
                        " {}"
                        (concat str " {}")
                        (car grep-find-command))
                       (+ (cdr grep-find-command)
                          (length str))))
             grep-find-command) 'grep-find-history))
       ;; No default was set
       (read-string
        "compile.el: No `grep-find-command' command available. Press RET.")
       (list nil))))
  (when command-args
    (let ((null-device nil))
      (grep command-args)))) 

Upvotes: 1

Related Questions