Searching and Replacement
Like other editors, Emacs has commands to search for occurrences of a string. Emacs also has commands to replace occurrences of a string with a different string. There are also commands that do the same thing, but search for patterns instead of fixed strings. You can also search multiple files under the control of xref (Identifier Search) or through the Dired A command (Operating on Files), or ask the grep program to do it (Grep Searching).
Incremental Search
The principal search command in Emacs is incremental: it begins searching as soon as you type the first character of the search string. As you type in the search string, Emacs shows you where the string (as you have typed it so far) would be found. When you have typed enough characters to identify the place you want, you can stop. Depending on what you plan to do next, you may or may not need to terminate the search explicitly with RET.
-
C-s - Incremental search forward (
isearch-forward). -
C-r - Incremental search backward (
isearch-backward).
You can also invoke incremental search from the menu bar's Edit->Search menu.
Basics of Incremental Search
-
C-s - Begin incremental search (
isearch-forward). -
C-r - Begin reverse incremental search (
isearch-backward).
C-s (isearch-forward) starts a forward incremental search. It reads characters from the keyboard, and moves point just past the end of the next occurrence of those characters in the buffer. For instance, if you type C-s and then F, that puts the cursor after the first F that occurs in the buffer after the starting point. If you then type O, the cursor moves to just after the first FO; the F in that FO might not be the first F previously found. After another O, the cursor moves to just after the first FOO. At each step, Emacs highlights the current match—the buffer text that matches the search string—using the isearch face (Faces). Search Customizations, for various options that customize this highlighting. The current search string is also displayed in the echo area. If you make a mistake typing the search string, type DEL (isearch-delete-char). Each DEL cancels the last input item entered during the search. Emacs records a new input item whenever you type a command that changes the search string, the position of point, the success or failure of the search, the direction of the search, the position of the other end of the current search result, or the "wrappedness" of the search. Error in Isearch, for more about dealing with unsuccessful search. When you are satisfied with the place you have reached, type RET (isearch-exit). This stops searching, leaving the cursor where the search brought it. Also, any command not specially meaningful in searches stops the searching and is then executed. Thus, typing C-a exits the search and then moves to the beginning of the line; typing one of the arrow keys exits the search and performs the respective movement command; etc. RET is necessary only if the next command you want to type is a printing character, DEL, RET, or another character that is special within searches (C-q, C-w, C-r, C-s, C-y, M-y, M-r, M-c, M-e, and some others described below). You can fine-tune the commands that exit the search; see Not Exiting Isearch. As a special exception, entering RET when the search string is empty launches nonincremental search (Nonincremental Search). (This can be customized; see Search Customizations.) To abandon the search and return to the place where you started, type ESC ESC ESC (isearch-cancel) or C-g C-g (isearch-abort). When you exit the incremental search, it adds the original value of point to the mark ring, without activating the mark; you can thus use C-u C-SPC or C-x C-x to return to where you were before beginning the search. Mark Ring. (Emacs only does this if the mark was not already active; if the mark was active when you started the search, both C-u C-SPC and C-x C-x will go to the mark.) To search backwards, use C-r (isearch-backward) instead of C-s to start the search. A backward search finds matches that end before the starting point, just as a forward search finds matches that begin after it.
Repeating Incremental Search
Suppose you search forward for FOO and find a match, but not the one you expected to find: the FOO you were aiming for occurs later in the buffer. In this event, type another C-s (isearch-repeat-forward) to move to the next occurrence of the search string, or C-r (isearch-repeat-backward) to move to the previous occurrence. You can repeat these commands any number of times. Alternatively, you can supply a numeric prefix argument of n to C-s and C-r to find the n/th next or previous occurrence. If you overshoot, you can cancel some C-s commands with DEL. Similarly, each C-r (isearch-repeat-backward) in a backward incremental search repeats the backward search. If you pause for a little while during incremental search, Emacs highlights all the other possible matches for the search string that are present on the screen. This helps you anticipate where you can get to by typing C-s or C-r to repeat the search. The other matches are highlighted differently from the current match, using the customizable face lazy-highlight (Faces). If you don't like this feature, you can disable it by setting isearch-lazy-highlight to nil. For other customizations related to highlighting matches, see Search Customizations. After exiting a search, you can search for the same string again by typing just C-s C-s. The first C-s is the key that invokes incremental search, and the second C-s means to search again for the last search string. Similarly, C-r C-r searches backward for the last search string. In determining the last search string, it doesn't matter whether that string was searched for with C-s or C-r. If you are searching forward but you realize you were looking for something before the starting point, type C-r to switch to a backward search, leaving the search string unchanged. Similarly, C-s in a backward search switches to a forward search. When you change the direction of a search, the first command you type will, by default, remain on the same match, and the cursor will move to the other end of the match. To move to another match immediately, customize the variable isearch-repeat-on-direction-change to t. If a search is failing and you ask to repeat it by typing another C-s, it starts again from the beginning of the buffer. Repeating a failing reverse search with C-r starts again from the end. This is called /wrapping around, and Wrapped appears in the search prompt once this has happened. If you keep on going past the original starting point of the search, it changes to Overwrapped, which means that you are revisiting matches that you have already seen. You can control what happens when there are no more matches by customizing the isearch-wrap-pause user option. If it is t (the default), signal an error. (Repeating the search will wrap around.) If no, issue a ding and wrap immediately after reaching the last match. If no-ding, wrap immediately, but don't ding. With the values no and no-ding the search will try to wrap around also on typing a character. Finally, if nil, never wrap, but just stop at the last match. To reuse earlier search strings, use the search ring. The commands M-p (isearch-ring-retreat) and M-n (isearch-ring-advance) move through the ring to pick a search string to reuse. These commands leave the selected search ring element in the minibuffer, where you can edit it. Type C-s=/=C-r or RET to accept the string and start searching for it. The number of most recently used search strings saved in the search ring is specified by the variable search-ring-max, 16 by default. To edit the current search string in the minibuffer without replacing it with items from the search ring, type M-e (isearch-edit-string) or click mouse-1 in the minibuffer. Type RET, C-s or C-r to finish editing the string and search for it. Type C-f or RIGHT to add to the search string characters following point from the buffer from which you started the search.
Isearch Yanking
In many cases, you will want to use text at or near point as your search string. The commands described in this subsection let you do that conveniently. C-w (isearch-yank-word-or-char) appends the next character or word at point to the search string. This is an easy way to search for another occurrence of the text at point. (The decision of whether to copy a character or a word is heuristic.) With a prefix numeric argument of n, append the next n characters or words. C-M-w (isearch-yank-symbol-or-char) appends the next character or symbol at point to the search string. This is an easy way to search for another occurrence of the symbol at point. (The decision of whether to copy a character or a symbol is heuristic.) With a prefix numeric argument of n, append the next n characters or symbols. M-s C-e (isearch-yank-line) appends the rest of the current line to the search string. If point is already at the end of a line, it appends the next line. With a prefix argument n, it appends the next n lines. Similarly, C-M-z (isearch-yank-until-char) appends to the search string everything from point until the next occurrence of a specified character (not including that character). This is especially useful for keyboard macros, for example in programming languages or markup languages in which that character marks a token boundary. With a prefix numeric argument of n, the command appends everything from point to the /n/th occurrence of the specified character. Within incremental search, C-y (isearch-yank-kill) appends the current kill to the search string. M-y (isearch-yank-pop), if called after C-y during incremental search, replaces that appended text with an earlier kill, similar to the usual M-y (yank-pop) command. Clicking mouse-2 in the echo area appends the current X selection (Primary Selection) to the search string (isearch-yank-x-selection). C-M-d (isearch-del-char) deletes the last character from the search string, and C-M-y (isearch-yank-char) appends the character after point to the search string. An alternative method to add the character after point is to enter the minibuffer with M-e (Repeat Isearch) and type C-f or RIGHT at the end of the search string in the minibuffer. Each C-f or RIGHT you type adds another character following point to the search string. Normally, when the search is case-insensitive, text yanked into the search string is converted to lower case, so that the search remains case-insensitive (case folding). However, if the value of the variable search-upper-case (search-upper-case) is other than not-yanks, that disables this down-casing. To begin a new incremental search with the text near point yanked into the initial search string, type M-s M-., which runs the command isearch-forward-thing-at-point. If the region was active, then it yanks the text from the region into the search string. Otherwise, it tries to yank a URL, a symbol or an expression found near point. What to yank is defined by the user option isearch-forward-thing-at-point.
Errors in Incremental Search
If your string is not found at all, the echo area says Failing I-Search, and the cursor moves past the place where Emacs found as much of your string as it could. Thus, if you search for FOOT, and there is no FOOT, you might see the cursor after the FOO in FOOL. In the echo area, the part of the search string that failed to match is highlighted using the face isearch-fail. At this point, there are several things you can do. If your string was mistyped, use DEL to cancel a previous input item (Basic Isearch), C-M-d to erase one character at a time, or M-e to edit it. If you like the place you have found, you can type RET to remain there. Or you can type C-g, which removes from the search string the characters that could not be found (the T in FOOT), leaving those that were found (the FOO in FOOT). A second C-g at that point cancels the search entirely, returning point to where it was when the search started. The quit command, C-g, does special things during searches; just what it does depends on the status of the search. If the search has found what you specified and is waiting for input, C-g cancels the entire search, moving the cursor back to where you started the search. If C-g is typed when there are characters in the search string that have not been found—because Emacs is still searching for them, or because it has failed to find them—then the search string characters which have not been found are discarded from the search string. With them gone, the search is now successful and waiting for more input, so a second C-g will cancel the entire search.
Special Input for Incremental Search
In addition to characters described in the previous subsections, some of the other characters you type during incremental search have special effects. They are described here. To toggle lax space matching (lax space matching), type M-s SPC. To toggle case sensitivity of the search, type M-c or M-s c. case folding. If the search string includes upper-case letters, the search is case-sensitive by default. To toggle whether or not the search will consider similar and equivalent characters as a match, type M-s '. character folding. If the search string includes accented characters, that disables character folding during that search. To toggle whether or not the search will find text made invisible by overlays, type M-s i (isearch-toggle-invisible). Outline Search. To make all incremental searches find matches inside invisible text, whether due to text properties or overlay properties, customize search-invisible to the value t. To toggle between non-regexp and regexp incremental search, type M-r or M-s r (isearch-toggle-regexp). Regexp Search. To toggle symbol mode, type M-s _. Symbol Search. To search for a newline character, type C-j as part of the search string. To search for non-ASCII characters, use one of the following methods during incremental search:
- Type
C-q(isearch-quote-char), followed by a non-graphic character or a sequence of octal digits. This adds a character to the search string, similar to inserting into a buffer usingC-q(Inserting Text). For example,C-q C-sduring incremental search adds thecontrol-Scharacter to the search string. - Use an input method (Input Methods). If an input method is enabled in the current buffer when you start the search, the same method will be active in the minibuffer when you type the search string. While typing the search string, you can toggle the input method with
C-\(isearch-toggle-input-method). You can also turn on a non-default input method withC-^(isearch-toggle-specified-input-method), which prompts for the name of the input method. When an input method is active during incremental search, the search prompt includes the input method mnemonic, like this: I-search [/im/]: where im is the mnemonic of the active input method. Any input method you enable during incremental search remains enabled in the current buffer afterwards. Finally, you can temporarily enable a transient input method (transient input method) withC-x \(isearch-transient-input-method) to insert a single character to the search string using an input method, and automatically disable the input method afterwards. - Type
C-x 8 RET(isearch-char-by-name), followed by a Unicode name or code-point in hex. This adds the specified character into the search string, similar to the usualinsert-charcommand (Inserting Text).
You can also include Emoji sequences in the search string. Type C-x 8 e RET (isearch-emoji-by-name), followed by the Unicode name of an Emoji (for example, smiling face or heart with arrow). This adds the specified Emoji to the search string. If you don't know the name of the Emoji you want to search for, you can use C-x 8 e l (emoji-list) and C-x 8 e d (emoji-describe) (Input Methods). Typing M-s o in incremental search invokes isearch-occur, which runs occur with the current search string. occur. Typing M-% (isearch-query-replace) in incremental search invokes query-replace or query-replace-regexp (depending on search mode) with the current search string used as the string to replace. A negative prefix argument means to replace backward. Query Replace. Typing C-M-% (isearch-query-replace-regexp) invokes query-replace-regexp with the current search string used as the regexp to replace. Typing M-TAB in incremental search invokes isearch-complete, which attempts to complete the search string using the search ring (the previous search strings you used) as a list of completion alternatives. Completion. In many operating systems, the M-TAB key sequence is captured by the window manager; you then need to rebind isearch-complete to another key sequence if you want to use it (Rebinding). You can exit the search while leaving the matches highlighted by typing M-s h r (isearch-highlight-regexp). This runs highlight-regexp (Highlight Interactively), passing it the regexp derived from the search string and prompting you for the face to use for highlighting. To highlight whole lines containing matches (rather than just the matches), type M-s h l (isearch-highlight-lines-matching-regexp). In either case, to remove the highlighting, type M-s h u (unhighlight-regexp). When incremental search is active, you can type C-h C-h (isearch-help-map) to access interactive help options, including a list of special key bindings. These key bindings are part of the keymap isearch-mode-map (Keymaps). When incremental search is active, typing M-s M-> will go to the last occurrence of the search string, and M-s M-< will go to the first occurrence. With a prefix numeric argument of n, these commands will go to the /n/th occurrence of the search string counting from the beginning or end of the buffer, respectively.
Not Exiting Incremental Search
This subsection describes how to control whether typing a command not specifically meaningful in searches exits the search before executing the command. It also describes three categories of commands which you can type without exiting the current incremental search, even though they are not themselves part of incremental search. Normally, typing a command that is not bound by the incremental search exits the search before executing the command. Thus, the command operates on the buffer from which you invoked the search. However, if you customize the variable search-exit-option to append, the characters which you type that are not interpreted by the incremental search are simply appended to the search string. This is so you could include in the search string control characters, such as C-a, that would normally exit the search and invoke the command bound to them on the buffer.
- Prefix Arguments
- In incremental search, when you type a command that specifies a prefix argument (Arguments), by default it will apply either to the next action in the search or to the command that exits the search. In other words, entering a prefix argument will not by itself terminate the search. In previous versions of Emacs, entering a prefix argument always terminated the search. You can revert to this behavior by setting the variable
isearch-allow-prefixtonil. Whenisearch-allow-scrollis non-nil(see below), prefix arguments always have the default behavior described above, i.e., they don't terminate the search, even ifisearch-allow-prefixisnil. - Scrolling Commands
- Normally, scrolling commands exit incremental search. But if you change the variable
isearch-allow-scrollto a non-nilvalue, that enables the use of the scroll-bar, as well as keyboard scrolling commands likeC-v,M-v, andC-l(Scrolling), which have a non-nilscroll-commandproperty, without exiting the search. This applies only to calling these commands via their bound key sequences—typingM-xwill still exit the search. You can give prefix arguments to these commands in the usual way. This feature normally won't let you scroll the current match out of visibility; but if you customizeisearch-allow-scrollto the special valueunlimited, that restriction is lifted. Theisearch-allow-scrollfeature also affects some other commands, such asC-x 2(split-window-below) andC-x ^(enlarge-window), which don't exactly scroll but do affect where the text appears on the screen. In fact, it affects any command that has a non-nilisearch-scrollproperty. So you can control which commands are affected by changing these properties. For example, to makeC-h lusable within an incremental search in all future Emacs sessions, useC-h cto find what command it runs (Key Help), which isview-lossage. Then you can put the following line in your init file (Init File): (put 'view-lossage 'isearch-scroll t) This feature can be applied to any command that doesn't permanently change point, the buffer contents, the match data, the current buffer, or the selected window and frame. The command must not itself attempt an incremental search. This feature is disabled ifisearch-allow-scrollisnil(which it is by default). Likewise, if you change the variableisearch-allow-motionto a non-nilvalue, this enables the use of the keyboard motion commandsM-<,M->,C-vandM-v, to move respectively to the first occurrence of the current search string in the buffer, the last one, the first one after the current window, and the last one before the current window. The search direction does not change when these motion commands are used, unless you change the variableisearch-motion-changes-directionto a non-nilvalue, in which case the search direction is forward afterM-<andC-v, and backward afterM->andM-v. - Motion Commands
- When
isearch-yank-on-moveis customized toshift, you can extend the search string by holding down the shift key while typing cursor motion commands. It will yank text that ends at the new position after moving point in the current buffer. Whenisearch-yank-on-moveist, you can extend the search string without using the shift key for cursor motion commands, but it applies only for certain motion command that have theisearch-moveproperty on their symbols.
Searching the Minibuffer
If you start an incremental search while the minibuffer is active, Emacs searches the contents of the minibuffer, as in any other buffer. Unlike searching an ordinary buffer, the search string is not shown in the echo area, because that is used to display the minibuffer. If an incremental search in the minibuffer fails to find a match, it tries searching the minibuffer history. Minibuffer History. Emacs pretends that the minibuffer and its history are a series of pages, with the earliest history element on the first page and the current minibuffer on the last page. A forward search, C-s, searches forward to later pages; a reverse search, C-r, searches backwards to earlier pages. Like in ordinary buffer search, a failing search can wrap around, going from the last page to the first page or vice versa. When an incremental search in the minibuffer finds a match that is part of a history element, that history element is pulled into the minibuffer and displayed. If you exit the incremental search normally (e.g., by typing RET), it remains in the minibuffer afterwards. Canceling the search, with C-g, restores the contents of the minibuffer to what it was when you began the search.
Nonincremental Search
Emacs also has conventional nonincremental search commands, which require you to type the entire search string before searching begins.
-
C-s RET string RET - Search for string.
-
C-r RET string RET - Search backward for string.
To start a nonincremental search, first type C-s RET. This enters the minibuffer to read the search string; terminate the string with RET, and then the search takes place. If the string is not found, the search command signals an error. When you type C-s RET, the C-s invokes incremental search as usual. That command is specially programmed to invoke the command for nonincremental search, if the string you specify is empty. (Such an empty argument would otherwise be useless.) C-r =RET= does likewise, invoking the nonincremental backward-searching command. Nonincremental search can also be invoked from the menu bar's Edit->Search menu. You can also use two simpler commands, M-x search-forward and M-x search-backward. These commands look for the literal strings you specify, and don't support any of the lax-search features (Lax Search) except case folding.
Word Search
A word search finds a sequence of words without regard to the type of punctuation between them. For instance, if you enter a search string that consists of two words separated by a single space, the search matches any sequence of those two words separated by one or more spaces, newlines, or other punctuation characters. This is particularly useful for searching text documents, because you don't have to worry whether the words you are looking for are separated by newlines or spaces. Note that major modes for programming languages or other specialized modes can modify the definition of a word to suit their syntactic needs.
-
M-s w - If incremental search is active, toggle word search mode (
isearch-toggle-word); otherwise, begin an incremental forward word search (isearch-forward-word). -
M-s w RET words RET - Search for words, using a forward nonincremental word search.
-
M-s w C-r RET words RET - Search backward for words, using a nonincremental word search.
-
M-s M-w - Search the Web for the text in region.
To begin a forward incremental word search, type M-s w. If incremental search is not already active, this runs the command isearch-forward-word. If incremental search is already active (whether a forward or backward search), M-s w runs the command isearch-toggle-word, which switches to a word search while keeping the direction of the search and the current search string unchanged. You can toggle word search back off by typing M-s w again. To begin a nonincremental word search, type M-s w RET for a forward search, or M-s w C-r RET for a backward search. These run the commands word-search-forward and word-search-backward respectively. Incremental and nonincremental word searches differ slightly in the way they find a match. In a nonincremental word search, each word in the search string must exactly match a whole word. In an incremental word search, the matching is more lax: while you are typing the search string, its first and last words need not match whole words. This is so that the matching can proceed incrementally as you type. This additional laxity does not apply to the lazy highlight (Incremental Search), which always matches whole words. While you are typing the search string, Pending appears in the search prompt until you use a search repeating key like C-s. The word search commands don't perform character folding, and toggling lax whitespace matching (lax space matching) has no effect on them. To search the Web for the text in region, type M-s M-w. This command performs an Internet search for the words in region using the search engine whose URL is specified by the variable eww-search-prefix (EWW). If the region is not active, or doesn't contain any words, this command prompts the user for a URL or keywords to search. You can also search for definitions of a word by querying dictionary servers via the @sc{dict} protocol defined by RFC 2229. Emacs includes a client for this protocol. Type M-x dictionary-search =RET= to connect to a @sc{dict} server and ask it to provide the available definitions of a word. This command prompts for the word to look up, using the word at point as the default, then asks the @sc{dict} server to provide the definitions of that word in one or more dictionaries. By default, the command first tries to connect to the @sc{dict} server installed on the local host, and if that fails, it tries dict.org after asking for confirmation; customize the variable dictionary-server to specify, as a string, the URL of a single server to use (use localhost if you want to query only the local server). Normally, dictionary-search tells the server to look up the word in all the dictionaries available to the server, but if you invoke the command with a prefix argument, it will prompt for a single dictionary to use. The list of dictionaries available to a server can be displayed by pressing the Select dictionary button shown in the *Dictionary* buffer, described below. The first time you use dictionary-search, it creates a new *Dictionary* buffer and turns on a special mode in it. The buffer shows buttons for selecting a dictionary, searching a definition of another word, etc. Subsequent dictionary-search commands reuse this buffer. To create another such buffer (e.g., to look up other words, perhaps in another dictionary), type M-x dictionary =RET=. If you turn on dictionary-tooltip-mode in a buffer, Emacs will look up the definitions of the word at mouse pointer and show those definitions in a tool tip. This is handy when you are reading text with many words about whose meaning you are unsure. For other options of dictionary-search, see the dictionary customization group (Specific Customization).
Symbol Search
A symbol search is much like an ordinary search, except that the boundaries of the search must match the boundaries of a symbol. The meaning of symbol in this context depends on the major mode, and usually refers to a source code token, such as a Lisp symbol in Emacs Lisp mode. For instance, if you perform an incremental symbol search for the Lisp symbol forward-word, it would not match isearch-forward-word. This feature is thus mainly useful for searching source code.
-
M-s _ - If incremental search is active, toggle symbol search mode (
isearch-toggle-symbol); otherwise, begin an incremental forward symbol search (isearch-forward-symbol). -
M-s . - Start a symbol incremental search forward with the symbol found near point added to the search string initially.
-
M-s _ RET symbol RET - Search forward for symbol, nonincrementally.
-
M-s _ C-r RET symbol RET - Search backward for symbol, nonincrementally.
To begin a forward incremental symbol search, type M-s _ (or M-s . if the symbol to search is near point). If incremental search is not already active, M-s _ runs the command isearch-forward-symbol and M-s . runs the command isearch-forward-symbol-at-point. With a numeric prefix argument of n, M-s . will search for the n/the next occurrence of the symbol at point; negative values of /n search backwards. If incremental search is already active, M-s _ switches to a symbol search, preserving the direction of the search and the current search string; you can disable symbol search by typing M-s _ again. In incremental symbol search, while you are typing the search string, only the beginning of the search string is required to match the beginning of a symbol, and Pending appears in the search prompt until you use a search repeating key like C-s. To begin a nonincremental symbol search, type M-s _ RET for a forward search, or M-s _ C-r RET or a backward search. In nonincremental symbol searches, the beginning and end of the search string are required to match the beginning and end of a symbol, respectively. The symbol search commands don't perform character folding, and toggling lax whitespace matching (lax space matching) has no effect on them.
Regular Expression Search
A regular expression (or regexp for short) is a pattern that denotes a class of alternative strings to match. Emacs provides both incremental and nonincremental ways to search for a match for a regexp. The syntax of regular expressions is explained in the next section.
-
C-M-s - Begin incremental regexp search (
isearch-forward-regexp). -
C-M-r - Begin reverse incremental regexp search (
isearch-backward-regexp).
Incremental search for a regexp is done by typing C-M-s (isearch-forward-regexp), by invoking C-s with a prefix argument (whose value does not matter), or by typing M-r within a forward incremental search. This command reads a search string incrementally just like C-s, but it treats the search string as a regexp rather than looking for an exact match against the text in the buffer. Each time you add text to the search string, you make the regexp longer, and the new regexp is searched for. To search backward for a regexp, use C-M-r (isearch-backward-regexp), C-r with a prefix argument, or M-r within a backward incremental search. All of the special key sequences in an ordinary incremental search (Special Isearch) do similar things in an incremental regexp search. For instance, typing C-s immediately after starting the search retrieves the last incremental search regexp used and searches forward for it. Incremental regexp and non-regexp searches have independent defaults. They also have separate search rings, which you can access with M-p and M-n. The maximum number of search regexps saved in the search ring is determined by the value of regexp-search-ring-max, 16 by default. Unlike ordinary incremental search, incremental regexp search does not use lax space matching by default. To toggle this feature use M-s SPC (isearch-toggle-lax-whitespace). Then any SPC typed in incremental regexp search will match any sequence of one or more whitespace characters. The variable search-whitespace-regexp specifies the regexp for the lax space matching. Special Isearch. Also unlike ordinary incremental search, incremental regexp search cannot use character folding (Lax Search). (If you toggle character folding during incremental regexp search with M-s ', the search becomes a non-regexp search and the search pattern you typed is interpreted as a literal string.) In some cases, adding characters to the regexp in an incremental regexp search can make the cursor move back and start again. For example, if you have searched for foo and you add \|bar, the cursor backs up in case the first bar precedes the first foo. (The prompt will change to say "Pending" to notify the user that this recalculation has happened.) Regexps. Forward and backward regexp search are not symmetrical, because regexp matching in Emacs always operates forward, starting with the beginning of the regexp. Thus, forward regexp search scans forward, trying a forward match at each possible starting position. Backward regexp search scans backward, trying a forward match at each possible starting position. These search methods are not mirror images. Nonincremental search for a regexp is done with the commands re-search-forward and re-search-backward. You can invoke these with M-x, or by way of incremental regexp search with C-M-s RET and C-M-r RET. When you invoke these commands with M-x, they search for the exact regexp you specify, and thus don't support any lax-search features (Lax Search) except case folding. If you use the incremental regexp search commands with a prefix argument, they perform ordinary string search, like isearch-forward and isearch-backward. Incremental Search.
Syntax of Regular Expressions
This section (and this manual in general) describes regular expression features that users typically use. Regular Expressions, for additional features used mainly in Lisp programs. Regular expressions have a syntax in which a few characters are special constructs and the rest are ordinary. An ordinary character matches that same character and nothing else. The special characters are $^.*+?[\. The character ] is special if it ends a bracket expression (see below). The character - is special inside a bracket expression. Any other character appearing in a regular expression is ordinary, unless a \ precedes it. (When you use regular expressions in a Lisp program, each \ must be doubled, see the example near the end of this section.) For example, f is not a special character, so it is ordinary, and therefore f is a regular expression that matches the string f and no other string. (It does not match the string ff.) Likewise, o is a regular expression that matches only o. (When case distinctions are being ignored, these regexps also match F and O, but we consider this a generalization of "the same string", rather than an exception.) Any two regular expressions a and b can be concatenated. The result is a regular expression which matches a string if a matches some amount of the beginning of that string and b matches the rest of the string. As a trivial example, concatenating the regular expressions f and o gives the regular expression fo, which matches only the string fo. To do something less trivial, you need to use one of the special characters. Here is a list of them.
-
.(Period) - is a special character that matches any single character except a newline. For example, the regular expressions
a.bmatches any three-character string that begins withaand ends withb. -
* - is not a construct by itself; it is a postfix operator that means to match the preceding regular expression repetitively any number of times, as many times as possible. Thus,
o*matches any number ofo=s, including no =o=s. =*always applies to the smallest possible preceding expression. Thus,fo*has a repeatingo, not a repeatingfo. It matchesf,fo,foo, and so on. The matcher processes a*construct by matching, immediately, as many repetitions as can be found. Then it continues with the rest of the pattern. If that fails, backtracking occurs, discarding some of the matches of the*-modified construct in case that makes it possible to match the rest of the pattern. For example, in matchingca*aragainst the stringcaaar, thea*first tries to match all threea=s; but the rest of the pattern is =arand there is onlyrleft to match, so this try fails. The next alternative is fora*to match only two =a=s. With this choice, the rest of the regexp matches successfully. -
+ - is a postfix operator, similar to
*except that it must match the preceding expression at least once. Thus,ca+rmatches the stringscarandcaaaarbut not the stringcr, whereasca*rmatches all three strings. -
? - is a postfix operator, similar to
*except that it can match the preceding expression either once or not at all. Thus,ca?rmatchescarorcr, and nothing else. -
*?,+?,?? - are non-greedy variants of the operators above. The normal operators
*,+,?match as much as they can, as long as the overall regexp can still match. With a following?, they will match as little as possible. Thus, bothab*andab*?can match the stringaand the stringabbbb; but if you try to match them both against the textabbb,ab*will match it all (the longest valid match), whileab*?will match justa(the shortest valid match). Non-greedy operators match the shortest possible string starting at a given starting point; in a forward search, though, the earliest possible starting point for match is always the one chosen. Thus, if you search fora.*?$against the textabbabfollowed by a newline, it matches the whole string. Since it can match starting at the firsta, it does. -
[ ... ] - is a bracket expression (a.k.a. set of alternative characters), which matches one of a set of characters. In the simplest case, the characters between the two brackets are what this set can match. Thus,
[ad]matches either oneaor oned, and[ad]*matches any string composed of justa=s and =d=s (including the empty string). It follows that =c[ad]*rmatchescr,car,cdr,caddaar, etc. You can also include character ranges in a character set, by writing the starting and ending characters with a-between them. Thus,[a-z]matches any lower-case ASCII letter. Ranges may be intermixed freely with individual characters, as in[a-z$%.], which matches any lower-case ASCII letter or$,%or period. As another example,[α-ωί]matches all lower-case Greek letters. You can also include certain special character classes in a character set. A[:and balancing:]enclose a character class inside a bracket expression. For instance,[[:alnum:]]matches any letter or digit. Char Classes, for a list of character classes. To include a]in a character set, you must make it the first character. For example,[]a]matches]ora. To include a-, write-as the last character of the set, tho you can also put it first or after a range. Thus,[]-]matches both]and-. To include^in a set, put it anywhere but at the beginning of the set. (At the beginning, it complements the set—see below.) When you use a range in case-insensitive search, you should write both ends of the range in upper case, or both in lower case, or both should be non-letters. The behavior of a mixed-case range such asA-zis somewhat ill-defined, and it may change in future Emacs versions. To search for raw bytes (International Chars) using regular expressions, specify their codepoints in the bracket expression, as inC-M-s [ C-x 8 =RET3fff80RET- C-x 8RET3fffffRET]=. Emacs will show the equivalent Regexp I-search: [\200-\377] in the echo area. -
[^ ... ] [^begins a complemented character set, which matches any character except the ones specified. Thus,[^a-z0-9A-Z]matches all characters except ASCII letters and digits.^is not special in a character set unless it is the first character. The character following the^is treated as if it were first (in other words,-and]are not special there). A complemented character set can match a newline, unless newline is mentioned as one of the characters not to match. This is in contrast to the handling of regexps in programs such asgrep.-
^ - is a special character that matches the empty string, but only at the beginning of a line in the text being matched. Otherwise it fails to match anything. Thus,
^foomatches afoothat occurs at the beginning of a line. For historical compatibility reasons,^can be used with this meaning only at the beginning of the regular expression, or after\(or\|. -
$ - is similar to
^but matches only at the end of a line. Thus,x+$matches a string of onexor more at the end of a line. For historical compatibility reasons,$can be used with this meaning only at the end of the regular expression, or before\)or\|. -
\ - has two functions: it quotes the special characters (including
\), and it introduces additional special constructs. Because\quotes special characters,\$is a regular expression that matches only$, and\[is a regular expression that matches only[, and so on. See the following section for the special constructs that begin with\.
Note: for historical compatibility, special characters are treated as ordinary ones if they are in contexts where their special meanings make no sense. For example, *foo treats * as ordinary since there is no preceding expression on which the * can act. It is poor practice to depend on this behavior; it is better to quote the special character anyway, regardless of where it appears. As a \ is not special inside a bracket expression, it can never remove the special meaning of -, ^ or ]. You should not quote these characters when they have no special meaning. This would not clarify anything, since backslashes can legitimately precede these characters where they have special meaning, as in [^\] ("[^\\]" for Lisp string syntax), which matches any single character except a backslash.
Backslash in Regular Expressions
For the most part, \ followed by any character matches only that character. However, there are several exceptions: two-character sequences starting with \ that have special meanings. The second character in the sequence is always an ordinary character when used on its own. Here is a table of \ constructs.
-
\| - specifies an alternative. Two regular expressions a and b with
\|in between form an expression that matches some text if either a matches it or b matches it. It works by trying to match a, and if that fails, by trying to match b. Thus,foo\|barmatches eitherfooorbarbut no other string.\|applies to the largest possible surrounding expressions. Only a surrounding\( ... \)grouping can limit the grouping power of\|. Full backtracking capability exists to handle multiple uses of\|. -
\( ... \) - is a grouping construct that serves three purposes:
- ?
- :: To enclose a set of
\|alternatives for other operations. Thus,\(foo\|bar\)xmatches eitherfooxorbarx. - ?
- :: To enclose a complicated expression for the postfix operators
*,+and?to operate on. Thus,ba\(na\)*matchesbananana, etc., with any (zero or more) number ofnastrings. - ?
- :: To record a matched substring for future reference. This last application is not a consequence of the idea of a parenthetical grouping; it is a separate feature that is assigned as a second meaning to the same
\( ... \)construct. In practice there is usually no conflict between the two meanings; when there is a conflict, you can use a shy group, described below. -
\(?: ... \) - specifies a shy group that does not record the matched substring; you can't refer back to it with
\/d/(see below). This is useful in mechanically combining regular expressions, so that you can add groups for syntactic purposes without interfering with the numbering of the groups that are meant to be referred to. -
\d - matches the same text that matched the d/th occurrence of a
\( ... \)construct. This is called a /back reference. After the end of a\( ... \)construct, the matcher remembers the beginning and end of the text matched by that construct. Then, later on in the regular expression, you can use\followed by the digit d to mean "match the same text matched the /d/th\( ... \)construct". The strings matching the first nine\( ... \)constructs appearing in a regular expression are assigned numbers 1 through 9 in the order that the open-parentheses appear in the regular expression. So you can use\1through\9to refer to the text matched by the corresponding\( ... \)constructs. For example,\(.*\)\1matches any newline-free string that is composed of two identical halves. The\(.*\)matches the first half, which may be anything, but the\1that follows must match the same exact text. If a particular\( ... \)construct matches more than once (which can easily happen if it is followed by*), only the last match is recorded. -
\@{m\@} - is a postfix operator specifying m repetitions—that is, the preceding regular expression must match exactly m times in a row. For example,
x\@{4\@}matches the stringxxxxand nothing else. -
\@{m,n\@} - is a postfix operator specifying between m and n repetitions—that is, the preceding regular expression must match at least m times, but no more than n times. If n is omitted, then there is no upper limit, but the preceding regular expression must match at least m times.
\@{0,1\@}is equivalent to?.\@{0,\@}is equivalent to*.\@{1,\@}is equivalent to+. -
\` - matches the empty string, but only at the beginning of the string or buffer (or its accessible portion) being matched against.
-
\' - matches the empty string, but only at the end of the string or buffer (or its accessible portion) being matched against.
-
\= - matches the empty string, but only at point.
-
\b - matches the empty string, but only at the beginning or end of a word. Thus,
\bfoo\bmatches any occurrence offooas a separate word.\bballs?\bmatchesballorballsas a separate word.\bmatches at the beginning or end of the buffer regardless of what text appears next to it. -
\B - matches the empty string, but not at the beginning or end of a word.
-
\< - matches the empty string, but only at the beginning of a word.
\<matches at the beginning of the buffer only if a word-constituent character follows. -
\> - matches the empty string, but only at the end of a word.
\>matches at the end of the buffer only if the contents end with a word-constituent character. -
\w - matches any word-constituent character. The syntax table determines which characters these are. Syntax Tables.
-
\W - matches any character that is not a word-constituent.
-
\_< - matches the empty string, but only at the beginning of a symbol. A symbol is a sequence of one or more symbol-constituent characters. A symbol-constituent character is a character whose syntax is either
wor_.\_<matches at the beginning of the buffer only if a symbol-constituent character follows. As with words, the syntax table determines which characters are symbol-constituent. -
\_> - matches the empty string, but only at the end of a symbol.
\_>matches at the end of the buffer only if the contents end with a symbol-constituent character. -
\sc - matches any character whose syntax is c. Here c is a character that designates a particular syntax class: thus,
wfor word constituent,-or= for whitespace, =.for ordinary punctuation, etc. Syntax Class Table. -
\Sc - matches any character whose syntax is not c.
-
\cc - matches any character that belongs to the category c. For example,
\ccmatches Chinese characters,\cgmatches Greek characters, etc. For the description of the known categories, typeM-x describe-categories RET. -
\Cc - matches any character that does not belong to category c.
The constructs that pertain to words and syntax are controlled by the setting of the syntax table. Syntax Tables.
Regular Expression Example
Here is an example of a regexp—similar to the regexp that Emacs uses, by default, to recognize the end of a sentence, not including the following space (i.e., the variable sentence-end-base):
@verbatim [.?!][]\"')}]* @end verbatim
This contains two parts in succession: a character set matching period, ?, or !, and a character set matching close-brackets, quotes, or parentheses, repeated zero or more times.
Lax Matching During Searching
Normally, you'd want search commands to disregard certain minor differences between the search string you type and the text being searched. For example, sequences of whitespace characters of different length are usually perceived as equivalent; letter-case differences usually don't matter; etc. This is known as character equivalence. This section describes the Emacs lax search features, and how to tailor them to your needs. By default, search commands perform lax space matching: each space, or sequence of spaces, matches any sequence of one or more whitespace characters in the text. More precisely, Emacs matches each sequence of space characters in the search string to a regular expression specified by the user option search-whitespace-regexp. The default value of this option considers any sequence of spaces and tab characters as whitespace. Hence, foo bar matches foo bar, foo@ @ bar, foo@ @ @ bar, and so on (but not foobar). If you want to make spaces match sequences of newlines as well as spaces and tabs, customize the option to make its value be the regular expression [ \t\n]+. (The default behavior of the incremental regexp search is different; see Regexp Search.) If you want whitespace characters to match exactly, you can turn lax space matching off by typing M-s SPC (isearch-toggle-lax-whitespace) within an incremental search. Another M-s SPC turns lax space matching back on. To disable lax whitespace matching for all searches, change search-whitespace-regexp to nil; then each space in the search string matches exactly one space. Searches in Emacs by default ignore the case of the text they are searching through, if you specify the search string in lower case. Thus, if you specify searching for foo, then Foo and fOO also match. Regexps, and in particular character sets, behave likewise: [ab] matches a or A or b or B. This feature is known as case folding, and it is supported in both incremental and non-incremental search modes. An upper-case letter anywhere in the search string makes the search case-sensitive. Thus, searching for Foo does not find foo or FOO. This applies to regular expression search as well as to literal string search. The effect ceases if you delete the upper-case letter from the search string. The variable search-upper-case controls this: if it is non-nil, an upper-case character in the search string makes the search case-sensitive; setting it to nil disables this effect of upper-case characters. The default value of this variable is not-yanks, which makes search case-sensitive if there are upper-case letters in the search string, and also causes text yanked into the search string (Isearch Yank) to be down-cased, so that such searches are case-insensitive by default. If you set the variable case-fold-search to nil, then all letters must match exactly, including case. This is a per-buffer variable; altering the variable normally affects only the current buffer, unless you change its default value. Locals. This variable applies to nonincremental searches also, including those performed by the replace commands (Replace) and the minibuffer history matching commands (Minibuffer History). Typing M-c or M-s c (isearch-toggle-case-fold) within an incremental search toggles the case sensitivity of that search. The effect does not extend beyond the current incremental search, but it does override the effect of adding or removing an upper-case letter in the current search. Several related variables control case-sensitivity of searching and matching for specific commands or activities. For instance, tags-case-fold-search controls case sensitivity for find-tag. To find these variables, do M-x apropos-variable =RET case-fold-search RET=. Case folding disregards case distinctions among characters, making upper-case characters match lower-case variants, and vice versa. A generalization of case folding is character folding, which disregards wider classes of distinctions among similar characters. For instance, under character folding the letter a matches all of its accented cousins like @"a and @'a, i.e., the match disregards the diacritics that distinguish these variants. In addition, a matches other characters that resemble it, or have it as part of their graphical representation, such as U+00AA @sc{feminine ordinal indicator} and U+24D0 @sc{circled latin small letter a} (which looks like a small a inside a circle). Similarly, the ASCII double-quote character " matches all the other variants of double quotes defined by the Unicode standard. Finally, character folding can make a sequence of one or more characters match another sequence of a different length: for example, the sequence of two characters ff matches U+FB00 @sc{latin small ligature ff} and the sequence (a) matches U+249C @sc{parenthesized latin small letter a}. Character sequences that are not identical, but match under character folding are known as equivalent character sequences. Generally, search commands in Emacs do not by default perform character folding in order to match equivalent character sequences. You can enable this behavior by customizing the variable search-default-mode to char-fold-to-regexp. Search Customizations. Within an incremental search, typing M-s ' (isearch-toggle-char-fold) toggles character folding, but only for that search. (Replace commands have a different default, controlled by a separate option; see Replacement and Lax Matches.) By default, typing an explicit variant of a character, such as @"a, as part of the search string doesn't match its base character, such as a. But if you customize the variable char-fold-symmetric to t, then search commands treat equivalent characters the same and use of any of a set of equivalent characters in a search string finds any of them in the text being searched, so typing an accented character @"a matches the letter a as well as all the other variants like @'a. You can add new foldings using the customizable variable char-fold-include, or remove the existing ones using the customizable variable char-fold-exclude. You can also customize char-fold-override to t to disable all the character equivalences except those you add yourself using char-fold-include.
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 (Mark). 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 (Expanding Abbrevs).
Unconditional Replacement
-
M-x replace-string RET string RET newstring RET - Replace every occurrence of string with newstring.
To replace every instance of foo after point with bar, use the command M-x replace-string with the two arguments foo and bar. Replacement happens only in the text after point, so if you want to cover the whole buffer you must go to the beginning first. All occurrences up to the end of the buffer are replaced; to limit replacement to part of the buffer, activate the region around that part. When the region is active, replacement is limited to the region (Mark). When replace-string exits, it leaves point at the last occurrence replaced. It adds the prior position of point (where the replace-string command was issued) to the mark ring, without activating the mark; use C-u C-SPC to move back there. Mark Ring. A prefix argument restricts replacement to matches that are surrounded by word boundaries. Replacement and Lax Matches, for details about case-sensitivity and character folding in replace commands.
Regexp Replacement
The M-x replace-string command replaces exact matches for a single string. The similar command M-x replace-regexp replaces any match for a specified regular expression pattern (Regexps).
-
M-x replace-regexp RET regexp RET newstring RET - Replace every match for regexp with newstring.
In replace-regexp, the newstring need not be constant: it can refer to all or part of what is matched by the regexp. \& in newstring stands for the entire match being replaced. \/d/ in newstring, where d is a digit starting from 1, stands for whatever matched the d/th parenthesized grouping in /regexp. (This is called a "back reference".) \# refers to the count of replacements already made in this command, as a decimal number. In the first replacement, \# stands for 0; in the second, for 1; and so on. For example,
M-x replace-regexp @key{RET} c[ad]+r @key{RET} \&-safe @key{RET}
replaces (for example) cadr with cadr-safe and cddr with cddr-safe.
M-x replace-regexp @key{RET} \(c[ad]+r\)-safe @key{RET} \1 @key{RET}
performs the inverse transformation. To include a \ in the text to replace with, you must enter \\. If you want to enter part of the replacement string by hand each time, use \? in the replacement string. Each replacement will ask you to edit the replacement string in the minibuffer, putting point where the \? was. The remainder of this subsection is intended for specialized tasks and requires knowledge of Lisp. Most readers can skip it. You can use Lisp expressions to calculate parts of the replacement string. To do this, write \ followed by the expression in the replacement string. Each replacement calculates the value of the expression and converts it to text without quoting (if it's a string, this means using the string's contents), and uses it in the replacement string in place of the expression itself. If the expression is a symbol, one space in the replacement string after the symbol name goes with the symbol name, so the value replaces them both. Inside such an expression, you can use some special sequences. \& and \/d/ refer here, as usual, to the entire match as a string, and to a submatch as a string. d may be multiple digits, and the value of \/d/ is nil if the d'th parenthesized grouping did not match. You can also use \#& and \#/d/ to refer to those matches as numbers (this is valid when the match or submatch has the form of a numeral). \# here too stands for the number of already-completed replacements. For example, we can exchange x and y this way:
M-x replace-regexp @key{RET} \(x\)\|y @key{RET}
\,(if \1 "y" "x") @key{RET}
For computing replacement strings for \, the format function is often useful (Formatting Strings). For example, to add consecutively numbered strings like ABC00042 to columns 73 to 80 (unless they are already occupied), you can use
M-x replace-regexp @key{RET} ^.\@{0,72\@}$ @key{RET}
\,(format "%-72sABC%05d" \& \#) @key{RET}
Replace Commands and Lax Matches
This subsection describes the behavior of replace commands with respect to lax matches (Lax Search) and how to customize it. In general, replace commands mostly default to stricter matching than their search counterparts. Unlike incremental search, the replacement commands do not use lax space matching (lax space matching) by default. To enable lax space matching for replacement, change the variable replace-lax-whitespace to non-nil. (This only affects how Emacs finds the text to replace, not the replacement text.) A companion variable replace-regexp-lax-whitespace controls whether query-replace-regexp uses lax whitespace matching when searching for patterns. If the first argument of a replace command is all lower case, the command ignores case while searching for occurrences to replace—provided case-fold-search is non-nil and search-upper-case is also non-nil. If search-upper-case (search-upper-case) is nil, whether searching ignores case is determined by case-fold-search alone, regardless of letter-case of the command's first argument. If case-fold-search is set to nil, case is always significant in all searches. In addition, when the second argument of a replace command is all or partly lower case, replacement commands try to preserve the case pattern of each occurrence. Thus, the command
M-x replace-string @key{RET} foo @key{RET} bar @key{RET}
replaces a lower case foo with a lower case bar, an all-caps FOO with BAR, and a capitalized Foo with Bar. (These three alternatives—lower case, all caps, and capitalized, are the only ones that replace-string can distinguish.) Note that Emacs decides whether to up-case or capitalize the replacement text by analyzing each word in the text being replaced, and will preserve the letter-case of the replaced text only if all of its words use the same letter-case. Thus, the command
M-x replace-string @key{RET} foo bar @key{RET} baz quux @key{RET}
replaces Foo Bar with Baz Quux because both words in Foo Bar are capitalized. By contrast, the same command replaces Foo bar with baz quux, i.e. it leaves the letter-case of the replacement text unchanged, since the two words in Foo bar use different capitalization. What exactly is considered a "word" depends on the syntax tables that are in effect in the current buffer (Syntax Tables); thus, Foo_Bar is two words in Text mode, but could be a single word in some major mode that supports a programming language. If upper-case letters are used in the replacement string, they remain upper case every time that text is inserted. If upper-case letters are used in the first argument, the second argument is always substituted exactly as given, with no case conversion. Likewise, if either case-replace or case-fold-search is set to nil, replacement is done without case conversion. The replacement commands by default do not use character folding (character folding) when looking for the text to replace. To enable character folding for matching in query-replace and replace-string, set the variable replace-char-fold to a non-nil value. (This setting does not affect the replacement text, only how Emacs finds the text to replace. It also doesn't affect replace-regexp.)
Query Replace
-
M-% string RET newstring RET - Replace some occurrences of string with newstring.
-
C-M-% 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, use M-% (query-replace). This command finds occurrences of foo one by one, displays each occurrence and asks you whether to replace it. Aside from querying, query-replace works just like replace-string (Unconditional Replace). In particular, it preserves case provided that case-replace is non-nil, as it normally is (Replacement and Lax Matches). A numeric argument means to consider only occurrences that are bounded by word-delimiter characters. A negative prefix argument replaces backward. C-M-% performs regexp search and replace (query-replace-regexp). It works like replace-regexp except that it queries like query-replace. You can reuse earlier replacements with these commands. When query-replace or query-replace-regexp prompts for the search string, use M-p and M-n to show previous replacements in the form /from/ -> /to/, where from is the search pattern, to is its replacement, and the separator between them is determined by the value of the variable query-replace-from-to-separator. Type RET to select the desired replacement. If the value of this variable is nil, replacements are not added to the command history, and cannot be reused. These commands highlight the current match using the face query-replace. You can disable this highlight by setting the variable query-replace-highlight to nil. They highlight other matches using lazy-highlight just like incremental search (Incremental Search); this can be disabled by setting query-replace-lazy-highlight to nil. By default, query-replace-regexp will show the substituted replacement string for the current match in the minibuffer. If you want to keep special sequences \& and \/n/ unexpanded, customize query-replace-show-replacement variable. Like search-highlight-submatches highlights subexpressions in incremental search (Search Customizations), the variable query-replace-highlight-submatches defines whether to highlight subexpressions in the regexp replacement commands. The variable query-replace-skip-read-only, if set non-nil, will cause replacement commands to ignore matches in read-only text. The default is not to ignore them. The characters you can type when you are shown a match for the string or regexp are:
-
SPC,y - to replace the occurrence with newstring.
-
DEL,Delete,BACKSPACE,n - to skip to the next occurrence without replacing this one.
-
,(Comma) - to replace this occurrence and display the result. You are then asked for another input character to say what to do next. Since the replacement has already been made,
DELandSPCare equivalent in this situation; both move to the next occurrence. You can typeC-rat this point (see below) to alter the replaced text. You can also undo the replacement with theundocommand (e.g., typeC-x u; Undo); this exits thequery-replace, so if you want to do further replacement you must useC-x ESC ESC RETto restart (Repetition). -
RET,q - to exit without doing any more replacements.
-
.(Period) - to replace this occurrence and then exit without searching for more occurrences.
-
! - to replace all remaining occurrences without asking again.
-
^ - to go back to the position of the previous occurrence (or what used to be an occurrence), in case you changed it by mistake or want to reexamine it.
-
u - to undo the last replacement and go back to where that replacement was made.
-
U - to undo all the replacements and go back to where the first replacement was made.
-
d - to show the diff buffer that changes all occurrences to their replacements.
-
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-cto proceed to the next occurrence. 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 withC-M-cto proceed to the next occurrence. -
e - to 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. -
E - is like
e, but the next replacement will be done with exact case. I.e., if you have aquery-replacefromfootobar, a text likeFoowill be normally be replaced withBar. Use this command to do the current replacement with exact case. -
C-l - to redisplay the screen. Then you must type another character to specify what to do with this occurrence.
-
Y(Upper-case) - to replace all remaining occurrences in all remaining buffers in multi-buffer replacements (like the Dired
Qcommand that performs query replace on selected files). It answers this question and all subsequent questions in the series with "yes", without further user interaction. -
N(Upper-case) - to skip to the next buffer in multi-buffer replacements without replacing remaining occurrences in the current buffer. It answers this question "no", gives up on the questions for the current buffer, and continues to the next buffer in the sequence.
-
C-h,?,F1 - to display a message summarizing these options. Then you must type another character to specify what to do with this occurrence.
Aside from this, any other character exits the query-replace, and is then reread as part of a key sequence. Thus, if you type C-k, it exits the query-replace and then kills to end of line. In particular, C-g simply exits the query-replace. To restart a query-replace once it is exited, use C-x =ESC ESC=, which repeats the query-replace because it used the minibuffer to read its arguments. C-x ESC ESC. The option search-invisible determines how query-replace treats invisible text. Outline Search. Operating on Files, for the Dired Q command which performs query replace on selected files. See also Transforming File Names, for Dired commands to rename, copy, or link files by replacing regexp matches in file names.
Other Search-and-Loop Commands
Here are some other commands that find matches for regular expressions. They all ignore case in matching, if the pattern contains no upper-case letters and case-fold-search is non-nil. Aside from multi-occur and multi-occur-in-matching-buffers, which always search the whole buffer, all of the commands operate on the text from point to the end of the buffer, or on the region if it is active.
-
M-x multi-isearch-buffers - Prompt for one or more buffer names, ending with
RET; then, begin a multi-buffer incremental search in those buffers. (If the search fails in one buffer, the nextC-stries searching the next specified buffer, and so forth.) With a prefix argument, prompt for a regexp and begin a multi-buffer incremental search in buffers matching that regexp. -
M-x multi-isearch-buffers-regexp - This command is just like
multi-isearch-buffers, except it performs an incremental regexp search. -
M-x multi-isearch-files - Prompt for one or more file names, ending with
RET; then, begin a multi-file incremental search in those files. (If the search fails in one file, the nextC-stries searching the next specified file, and so forth.) With a prefix argument, prompt for a regexp and begin a multi-file incremental search in files matching that regexp. -
M-x multi-isearch-files-regexp - This command is just like
multi-isearch-files, except it performs an incremental regexp search. In some modes that set the buffer-local variablemulti-isearch-next-buffer-function(e.g., in Change Log mode) a multi-file incremental search is activated automatically. -
M-x occur,M-s o - Prompt for a regexp, and display a list showing each line in the buffer that contains a match for it. If you type
M-nat the prompt, you can reuse search strings from previous incremental searches. The text that matched is highlighted using thematchface. A numeric argument n specifies that n lines of context are to be displayed before and after each matching line. The default number of context lines is specified by the variablelist-matching-lines-default-context-lines. Whenlist-matching-lines-jump-to-current-lineis non-nilthe current line is shown highlighted with facelist-matching-lines-current-line-faceand the point is set at the first match after such line. You can also runM-s owhen an incremental search is active; this uses the current search string. Note that matches for the regexp you type are extended to include complete lines, and a match that starts before the previous match ends is not considered a match. The*Occur*buffer uses the Occur mode as its major mode. You can use thenandpkeys to move to the next or previous match; with prefix numeric argument, these commands move that many matches. Digit keys are bound todigit-argument, so5 nmoves to the fifth next match (you don't have to typeC-u).SPCandDELscroll the*Occur*buffer up and down. Clicking on a match or moving point there and typingRETvisits the corresponding position in the original buffer that was searched.oandC-odisplay the match in another window;C-odoes not select that window. Alternatively, you can use theM-g M-n(next-error) command to visit the occurrences one by one (Compilation Mode). Finally,qquits the window showing the*Occur*buffer and buries the buffer. Typingein the*Occur*buffer makes the buffer writable and enters the Occur Edit mode, in which you can edit the matching lines and have those edits reflected in the text in the originating buffer. TypeC-c C-cto leave the Occur Edit mode and return to the Occur mode. The commandM-x list-matching-linesis a synonym forM-x occur. -
M-x multi-occur - This command is just like
occur, except it is able to search through multiple buffers. It asks you to specify the buffer names one by one. -
M-x multi-occur-in-matching-buffers - This command is similar to
multi-occur, except the buffers to search are specified by a regular expression that matches visited file names. With a prefix argument, it uses the regular expression to match buffer names instead. -
M-x how-many - Prompt for a regexp, and print the number of matches for it in the buffer after point. If the region is active, this operates on the region instead.
-
M-x flush-lines - Prompt for a regexp, and delete each line that contains a match for it, operating on the text after point. When the command finishes, it prints the number of deleted matching lines. This command deletes the current line if it contains a match starting after point. If the region is active, it operates on the region instead; if a line partially contained in the region contains a match entirely contained in the region, it is deleted. If a match is split across lines,
flush-linesdeletes all those lines. It deletes the lines before starting to look for the next match; hence, it ignores a match starting on the same line at which another match ended. -
M-x keep-lines - Prompt for a regexp, and delete each line that does not contain a match for it, operating on the text after point. If point is not at the beginning of a line, this command always keeps the current line. If the region is active, the command operates on the region instead; it never deletes lines that are only partially contained in the region (a newline that ends a line counts as part of that line). If a match is split across lines, this command keeps all those lines.
-
M-x kill-matching-lines - Like
flush-lines, but also add the matching lines to the kill ring. The command adds the matching lines to the kill ring as a single string, including the newlines that separated the lines. -
M-x copy-matching-lines - Like
kill-matching-lines, but the matching lines are not removed from the buffer.
Tailoring Search to Your Needs
This section describes miscellaneous search-related customizations not described elsewhere. The default search mode for the incremental search is specified by the variable search-default-mode. It can be nil, t, or a function. If it is nil, the default mode is to do literal searches without character folding, but with case folding and lax-whitespace matches as determined by case-fold-search and search-whitespace-regexp, respectively (Lax Search). If the value is t, incremental search defaults to regexp searches. The default value specifies a function that only performs case folding and lax-whitespace matching. The current match of an on-going incremental search is highlighted using the isearch face. This highlighting can be disabled by setting the variable search-highlight to nil. When searching for regular expressions (with C-M-s, for instance), subexpressions receive special highlighting depending on the search-highlight-submatches variable. If this variable's value is nil, no special highlighting is done, but if the value is non-nil, text that matches \( ... \) constructs (a.k.a. "subexpressions") in the regular expression will be highlighted with distinct faces. By default, two distinct faces are defined, named isearch-group-1 and isearch-group-2. With these two faces, odd-numbered subexpressions will be highlighted using the isearch-group-1 face and even-numbered subexpressions will be highlighted using the isearch-group-2 face. For instance, when searching for foo-\([0-9]+\)\([a-z]+\), the part matched by [0-9]+ will be highlighted with the isearch-group-1 face, and the part matched by [a-z]+ will be highlighted using isearch-group-2. If you define additional faces using the same numbering scheme, i.e. isearch-group-3, isearch-group-4, …, then the face isearch-group-M will be used to highlight the M'th, N+M'th, 2N+M'th, … subexpressions, where N is the total number of faces of the form isearch-group-M. The other matches for the search string that are visible on display are highlighted using the lazy-highlight face. Setting the variable isearch-lazy-highlight to nil disables this highlighting. Here are some other variables that customize the lazy highlighting: @vtable @code - lazy-highlight-initial-delay Time in seconds to wait before highlighting visible matches. Applies only if the search string is less than lazy-highlight-no-delay-length characters long. - lazy-highlight-no-delay-length For search strings at least as long as the value of this variable, lazy highlighting of matches starts immediately. - lazy-highlight-interval Time in seconds between highlighting successive matches. - lazy-highlight-max-at-a-time The maximum number of matches to highlight before checking for input. A large number can take some time to highlight, so if you want to continue searching and type C-s or C-r during that time, Emacs will not respond until it finishes highlighting all those matches. Thus, smaller values make Emacs more responsive. - isearch-lazy-count Show the current match number and the total number of matches in the search prompt. - lazy-count-prefix-format - lazy-count-suffix-format These two variables determine the format of showing the current and the total number of matches for isearch-lazy-count. - lazy-highlight-buffer If non-nil, lazy highlighting highlights the matches in the entire buffer, not only those visible on display of the current window (so, for example, they will also become visible in other windows showing the same buffer). - lazy-highlight-buffer-max-at-a-time Like lazy-highlight-max-at-a-time, but used for highlighting matches not currently visible in the window when lazy-highlight-buffer is non-nil. It defaults to 200; set to nil to highlight all the matches in a buffer without checking for input. Warning: this could make Emacs not responsive when searching large buffers. @end vtable Normally, entering RET within incremental search when the search string is empty launches a nonincremental search. (Actually, it lets you edit the search string, and the next RET does the search.) However, if you customize the variable search-nonincremental-instead to nil, typing RET will always exit the incremental search, even if the search string is empty. By default, incremental search and query-replace commands match invisible text, but hide any such matches as soon as the current match moves off the invisible text. If you customize the variable isearch-hide-immediately to nil, any invisible text where matches were found stays on display until the search or the replace command exits. Searching incrementally on slow terminals, such as displays connected to remote machines over slow connection, could be annoying due to the need to redraw large portions of the display as the search proceeds. Emacs provides a special display mode for slow terminals, whereby search pops up a separate small window and displays the text surrounding the match in that window. Small windows display faster, so the annoying effect of slow speed is alleviated. The variable search-slow-speed determines the baud rate threshold below which Emacs will use this display mode. The variable search-slow-window-lines controls the number of lines in the window Emacs pops up for displaying the search results; the default is 1 line. Normally, this window will pop up at the bottom of the window that displays the buffer where you start searching, but if the value of search-slow-window-lines is negative, that means to put the window at the top and give it the number of lines that is the absolute value of search-slow-window-lines.