Subject: Re: bug#8252: Please add a function to get files in *grep*

From: Lennart Borgman <[email-masked]>
Date: Tue, 15 Mar 2011 10:31:40 +0100

On Tue, Mar 15, 2011 at 3:16 AM, Stefan Monnier
<[email-masked]> wrote:
> Could you motivate your request?

There can be a lot of uses for it. In my case I am using it for this:

(defun grep-get-buffer-files ()
  "Return list of files in a `grep-mode' buffer."
  (or (and (compilation-buffer-p (current-buffer))
           (derived-mode-p 'grep-mode))
      (error "Not in a grep buffer"))
  (let ((here (point))
        files)
    (font-lock-fontify-buffer)
    (goto-char (point-min))
    (while (not (eobp))
      (let ((file (grep-grepped-file (point))))
        (when file (add-to-list 'files file)))
      (forward-line))
    (goto-char here)
    ;;(message "files=%s" files)
    files))

(defun grep-query-replace(from to &optional delimited)
  "Do `query-replace-regexp' of FROM with TO, on all files in *grep*.
Third arg DELIMITED (prefix arg) means replace only word-delimited matches.
If you exit (\\[keyboard-quit], RET or q), you can resume the query replace
with the command \\[tags-loop-continue].

Must be called from a `grep-mode' buffer."
  (interactive
   (let ((common
          ;; Use the regexps that have been used in grep
          (let ((query-replace-from-history-variable 'grep-regexp-history)
                (query-replace-defaults (or grep-query-replace-defaults
                                            query-replace-defaults)))
            (unless (derived-mode-p 'grep-mode) (error "This command
must be used in a grep output buffer"))
            (query-replace-read-args
             "Query replace regexp in grepped files" t t))))
     (setq grep-query-replace-defaults (cons (nth 0 common)
                                             (nth 1 common)))
     (list (nth 0 common) (nth 1 common) (nth 2 common))))
  (unless (derived-mode-p 'grep-mode) (error "This command must be
used in a grep output buffer"))
  (dolist (file (grep-get-buffer-files))
    (let ((buffer (get-file-buffer file)))
      (if (and buffer (with-current-buffer buffer
			buffer-read-only))
	  (error "File `%s' is visited read-only" file))))
  (tags-query-replace from to delimited
		      '(grep-get-buffer-files)))