Previous: , Up: Replace   [Contents][Index]


12.7.4 Query Replace

M-% string RET newstring RET
M-x query-replace RET string RET newstring RET

Replace some occurrences of string with newstring.

M-x query-replace-regexp RET regexp RET newstring RET

Replace some matches for regexp with newstring.

If you want to change only some of the occurrences of ‘foo’ to ‘bar’, not all of them, you can use query-replace instead of M-%. This command finds occurrences of ‘foo’ one by one, displays each occurrence, and asks you whether to replace it. A numeric argument to query-replace tells it to consider only occurrences that are bounded by word-delimiter characters.

Aside from querying, query-replace works just like replace-string, and query-replace-regexp works just like replace-regexp.

The things you can type when you are shown an occurrence of string or a match for regexp are:

SPC

to replace the occurrence with newstring. This preserves case, just like replace-string, provided case-replace is non-nil, as it normally is.

DEL

to skip to the next occurrence without replacing this one.

, (Comma)

to replace this occurrence and display the result. You are then prompted for another input character. However, since the replacement has already been made, DEL and SPC are equivalent. At this point, you can type C-r (see below) to alter the replaced text. To undo the replacement, you can type C-x u. This exits the query-replace. If you want to do further replacement you must use C-x ESC ESC to restart (see Repetition).

ESC

to exit without doing any more replacements.

. (Period)

to replace this occurrence and then exit.

!

to replace all remaining occurrences without asking again.

^

to go back to the location of the previous occurrence (or what used to be an occurrence), in case you changed it by mistake. This works by popping the mark ring. Only one ^ in a row is allowed, because only one previous replacement location is kept during query-replace.

C-r

to enter a recursive editing level, in case the occurrence needs to be edited rather than just replaced with newstring. When you are done, exit the recursive editing level with C-M-c and the next occurrence will be displayed. See Recursive Edit.

C-w

to delete the occurrence, and then enter a recursive editing level as in C-r. Use the recursive edit to insert text to replace the deleted occurrence of string. When done, exit the recursive editing level with C-M-c and the next occurrence will be displayed.

C-l

to redisplay the screen and then give another answer.

C-h

to display a message summarizing these options, then give another answer.

If you type any other character, Emacs exits the query-replace, and executes the character as a command. To restart the query-replace, use C-x ESC ESC, which repeats the query-replace because it used the minibuffer to read its arguments. See C-x ESC ESC.


Previous: , Up: Replace   [Contents][Index]