I want to replace all occurrences of a word in the whole buffer. What i do is:

M-x replace-string RET word-to-be-replaced RET new-word

The problem with this is that it also changes the word-to-be-replaced even if its only part of another word (for example wanting to change mod to off_mod results also changing set_mode to set_off_mode). How can i change it only in cases it exists exactly as a whole word and not also as parts of other words?

  • Have a look at regular expressions. – Dan May 14 '16 at 22:51

If you provide the universal argument to replace-string, that is by pressing C-u before M-x replace-string, it only replaces matches that are surrounded by word boundaries.

So, for example, a buffer containing


would be become after C-u M-x replace-string RET mod RET off_mod


You can find this information by looking in the manual: C-h i (to get the info index) m Emacs RET (to open the Emacs user manual section) and finding "replace-string" through the topic index by doing i replace-string RET.

Alternatively, you could look-up the function's documentation by doing C-h f replace-string

| improve this answer | |
  • 6
    +1, especially for teaching about the manual. Also: C-h r takes you to the Emacs manual, where i replace-string takes you directly to the doc about replace-string. i is your friend in Info. – Drew May 15 '16 at 0:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy