17.10 Replacement Commands

Emacs provides several commands for performing search-and-replace operations. In addition to the simple M-x replace-string command, there is M-% (query-replace), which presents each occurrence of the search pattern and asks you whether to replace it.

The replace commands normally operate on the text from point to the end of the buffer. When the region is active, they operate on it instead (see The Mark and the Region). The basic replace commands replace one search string (or regexp) with one replacement string. It is possible to perform several replacements in parallel, using the command expand-region-abbrevs (see Controlling Abbrev Expansion).

If you set query-replace-show-preview to a non-nil value, the replace commands show a preview of the replacement while you type it: the matches visible in the window are displayed as they would look after the replacement. This tells you what back-references like ‘\1’ (see Regexp Replacement) expand to before you commit to the replacement. The preview also appears at the prompt that reads the text to replace, as soon as its input holds both halves separated by an arrow, which is what M-p recalls from the history. However, replacements that use ‘\,’ or ‘\#’ are not previewed.

Only the matches that the command will replace are previewed: those after point, or those before it when replacing backward (see Query Replace). The other ones are still highlighted, to show that the buffer has more of them. When the region is active, the preview covers all of it, as the replacement does.

Possible values for query-replace-show-preview are replacement-only to display the replacement alone and both to display the match next to its replacement separated by an arrow. In the case of replacement-only, then if the replacement is empty, instead of showing nothing at all, displays a thin bar to mark the place of the match. You can also use a custom function that takes the match and the replacement and should return a string to display in place of the match, or nil to leave that match alone. It may be helpful to reference the functions replace-preview-replacement-only and replace-preview-both when writing a custom function value for this option.

The preview uses the faces query-replace-preview and query-replace-preview-match.