del bao
del bao

Reputation: 1164

Emacs: how to have query-replace cycle through the buffer?

if I am starting at some position in the buffer, i can only perform query-replace for the rest of buffer in one run. Is there any way to let query-replace cycle through the buffer?

Upvotes: 2

Views: 317

Answers (2)

James Yang
James Yang

Reputation: 1416

I've using below for work with Emacs 24+:

;; query replace all from buffer start
(fset 'my-query-replace-all 'query-replace)
(advice-add 'my-query-replace-all
            :around
            #'(lambda(oldfun &rest args)
               "Query replace the whole buffer."
               ;; set start pos
               (unless (nth 3 args)
                 (setf (nth 3 args)
                       (if (region-active-p)
                           (region-beginning)
                         (point-min))))
               (unless (nth 4 args)
                 (setf (nth 4 args)
                       (if (region-active-p)
                           (region-end)
                         (point-max))))
               (apply oldfun args)))
(global-set-key "\C-cr" 'my-query-replace-all)

Regard the region replace case, and any START and END args passed.

Upvotes: 0

Drew
Drew

Reputation: 30699

Use M-< to go to the beginning of the buffer, before you use M-% to query-replace.

If you want a command that does that, write it:

(defun my-qr ()
  "..."
  (interactive)
  (goto-char (point-min))
  (call-interactively #'query-replace))

And if you want to return to where you started when done, then wrap the code in save-excursion.

(defun my-qr ()
  "..."
  (save-excursion
   (interactive)
   (goto-char (point-min))
   (call-interactively #'query-replace)))

Upvotes: 2

Related Questions