, , , ,

This is the second one in the series of posts in an effort to get to know Emacs better (it’s very hard for a vim person, you know!). In this post we will look into the search as well as search-and-replace options in Emacs.

1) Forward/backward search: (C-s and C-r)
press C-s and the minibuffer will ask you to enter the search phrase. Similarly, use C-r to search in the reverse direction. Press C-s again to move forward from one match to another, and C-r to move backward. Hit C-g to cancel search. The forward and backward search options wrap around the text.

2) Unconditional search and replace: (M-x replace-string)
Press M-x, and then enter replace-string. You may use tab-completion to save yourself from some typing. After entering the string hit enter and the minibuffer will present you with “Replace string: ”. Enter the string to be replaced (say, XXX) and hit enter again. The minibuffer will present you with “ Replace string XXX with: ”. Enter the the relevant string (say, YYY ) and hit enter and voila — all the occurrences of XXX will be replaced with YYY.
N.B. Substitute replace-string with replace-regex to use the power of regular expressions.

3) Queried search and replace: (M-%)
Press m-%. You will then be prompted for your search and replace strings. Emacs will find and display each occurrence of the search string and ask you for further instructions. You can respond with any of the following options:

  • Spacebar Replace text and find the next occurrence
  • Del Leave text as is and find the next occurrence
  • . (period) Replace text, then stop looking for occurrences
  • ! (exclamation point) Replace all occurrences without asking
  • ^(caret) Return the cursor to previously replaced text
  • e Edit the replacement string in the minibuffer. When you exit the minibuffer by typing RET, the minibuffer contents replace the current occurrence of the pattern. They also become the new replacement string for any further occurrences.

If you type any other character, Emacs will stop looking for occurrences and execute the character as a command.

To restart the queried search and replace, type:
C-x ESC ESC; this is generally used to repeat complex minibuffer commands. If you don’t see the correct command there, you can browse the the command history in the minibuffer using M-p (previous) and M-n (next), or search M-s (forward) and M-r (reverse). Once you reach the correct one, you can edit the command as well!

N.B. My experience shows that queried search-and-replace starts searching in the forward direction; so it’s better to put the cursor at the top with M-< first.

Reference: here.