Emacs M-x query-replace wrap around the document?

query-replace is a very important function, so I'm reluctant to change it globally. What I've done instead is to copy this to a new function, my-query-replace, which initially has the same behaviour. Then I advise this function to repeat the query-replace search at the beginning of the buffer once it reaches the end. This might be overly cautious - you could modify the advice to apply to query-replace instead of my-query-replace, and enable this behaviour globally.

;; copy the original query-replace-function 
(fset 'my-query-replace 'query-replace)

;; advise the new version to repeat the search after it 
;; finishes at the bottom of the buffer the first time:    
(defadvice my-query-replace 
  (around replace-wrap 
          (FROM-STRING TO-STRING &optional DELIMITED START END))
  "Execute a query-replace, wrapping to the top of the buffer 
   after you reach the bottom"
  (save-excursion
    (let ((start (point)))
      ad-do-it
      (beginning-of-buffer)
      (ad-set-args 4 (list (point-min) start))
      ad-do-it)))

;; Turn on the advice    
(ad-activate 'my-query-replace)

Once you have evaluated this code, you can call the wrapped search with M-x my-query-replace, or bind it to something convenient for you:

(global-set-key "\C-cq" 'my-query-replace)

Tags:

Emacs