The question is not very clear. M-%
followed by !
replaces all occurrences (after the cursor). Just put the cursor at the beginning (M-<
) and then use M-%
followed by !
.
Now maybe what you mean is that you want to repeat the replacement (e.g. from the buffer beginning again) until no more such replacements are possible. That can of course lead to an infinite loop, depending on your replacement.
Anyway, here is a quick-and-dirty command to do that. The interactive
spec is essentially from query-replace
.
(defun foo (from-string to-string &optional delimited start end backward)
(interactive
(let ((common (query-replace-read-args
(concat "Query replace"
(if current-prefix-arg
(if (eq current-prefix-arg '-) " backward" " word")
"")
(if (and transient-mark-mode mark-active) " in region" ""))
nil)))
(list (nth 0 common) (nth 1 common) (nth 2 common)
(and transient-mark-mode mark-active (region-beginning))
(and transient-mark-mode mark-active (region-end))
(nth 3 common))))
(goto-char (point-min))
(while (save-excursion (re-search-forward from-string nil t))
(while (re-search-forward from-string nil t)) (replace-match to-string nil nil)
(goto-char (point-min))))
If you want to hit !
for each iteration, to obviate the problem of infinite looping, you can do something like this instead:
(defun foo (from-string to-string &optional delimited start end backward)
(interactive
(let ((common (query-replace-read-args
(concat "Query replace"
(if current-prefix-arg
(if (eq current-prefix-arg '-) " backward" " word")
"")
(if (and transient-mark-mode mark-active) " in region" ""))
nil)))
(list (nth 0 common) (nth 1 common) (nth 2 common)
(and transient-mark-mode mark-active (region-beginning))
(and transient-mark-mode mark-active (region-end))
(nth 3 common))))
(goto-char (point-min))
(while (perform-replace from-string to-string t nil delimited nil nil start end backward)
(goto-char (point-min))))
That just uses perform-replace
repeatedly, which gives you a chance (and the obligation) to act on each iteration.