Search code examples
emacsgrepdired

Emacs find-grep-dired then automatically isearch-forward on given regexp


I commonly do find-grep-dired to find an expression in a project directory. That gives me a nice dired view of all the files that contain that expression. But my next step is invariably to open one of those files and do an isearch-forward with the same search expression. How can I save myself from typing in the search words twice each time (or more than twice if there are multiple files I want to edit)?


Solution

  • This should work for you:

    1. Run find-grep-dired as usual
    2. Press * t (dired-toggle-marks) to mark all files.
    3. Press A to start dired-do-search. When prompted, instead of typing, press M-p, this will bring up your find-grep regexp since both functions use the same prompting history list
    4. You will be taken to the first match in the first file. Here's the fun part, simply press M-, to go to the next match spanning all of your matched files.
    5. Profit? (sorry, couldn't resist)

    And if you want it all in one shot, here you go:

    (defun find-grep-dired-do-search (dir regexp)
      "First perform `find-grep-dired', and wait for it to finish.
    Then, using the same REGEXP as provided to `find-grep-dired',
    perform `dired-do-search' on all files in the *Find* buffer."
      (interactive "DFind-grep (directory): \nsFind-grep (grep regexp): ")
      (find-grep-dired dir regexp)
      (while (get-buffer-process (get-buffer "*Find*"))
        (sit-for 1))
      (with-current-buffer "*Find*"
        (dired-toggle-marks)
        (dired-do-search regexp)))