0

This question already has an answer here:

I can do M-x query-replace and replace all strings with another one. But it only replaces ones below the current cursor position. Is there any way to replace all the occurrences regardless the position of the cursor?

marked as duplicate by Kaushal Modi, Drew, erikstokes, tarsius, Jordon Biondo Aug 26 '16 at 19:29

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • Do M-< to go to the beginning of the buffer. In elisp do (goto-char (point-min)) or use the optional arguments in search-forward-re?. – rasmus Aug 2 '16 at 9:16
2

You could use this function for replacing strings

(defun replace-in-buffer ()
"Replace text in whole buffer. Change OLD string to NEW string"
  (interactive)
  (save-excursion
    (replace-string (read-string "OLD string:")
                    (read-string "NEW string:")
                    nil
                    (point-min)
                    (point-max))))

and bind it to key with (global-set-key (kbd "C-c r") 'replace-in-buffer)

Thanks @rasmus, you could use: M-<, M-x query-replace <from> RET <to> RET, then press ! for replacing all occurences and C-u C-SPC twice to return point into the initial position.

Since query-replace bound to M-%, this could be helpfil when replace regexps too How to search and replace in the entire buffer?

1

M-x replace-string is what I use, unless I did not understand your question.

  • 1
    Worth noting that replace-string operates on the region and if no region is set then it defaults to the entire buffer. – Tephra Aug 2 '16 at 12:23
  • Using formatting could make you answer looks better. Try put "M-x replace-string" into "`". – Konstantin Morenko Aug 2 '16 at 19:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.