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 shows a preview of the replacement while you type it: the matches visible in the window are displayed as they would look after the replacement, using the face query-replace-preview. This tells you what back-references like ‘\1’ (see Regexp Replacement) expand to before you commit to the replacement. However, replacements that use ‘\,’ or ‘\#’ are not previewed.