Emacs: Find Replace in Current File

By Xah Lee. Date: . Last updated: .

How to find replace?

Alt+x query-replace. Emacs will prompt you for the find string and replace string.

Once emacs found a match, press

To undo, cancel search first, then Ctrl+/ to undo existing replacement.

Find Replace Commands

Here are the most useful find replace commands for current file.

Alt+x query-replaceAlt+%
Interactive find replace on text selection, or cursor position to end of buffer.
Alt+x query-replace-regexpCtrl+Alt+%
Interactive find replace by Emacs: Regular Expression, on text selection, or cusor point to end of buffer.
Alt+x dired-do-query-replace-regexp (In dired, Q)
Interactive find replace on marked files in dired. See: Emacs: Interactive Find Replace Text in Directory.

Force Case Change on Matched Text in Regex Match

If you are doing a regex search, and you want to force the replacement to upper case or lower case, in the replace prompt, give \,(upcase \1) or \,(downcase \1).

For example, suppose you have this text:

once upon a time.
There is a dragon who lived in the river.
princess Tana is still waiting for her prince.

Suppose you want all paragraphs to start with a capital letter. So, you use a pattern that catches the first letter of each line, like this ^\([a-z]\).

To make your captured pattern upper case, give your replacement string this expression: ^\,(upcase \1). The \, tells emacs that what follows should be a lisp expression. The (upcase \1) is a lisp expression. The upcase is a lisp function and the \1 means the 1st captured string in your regex pattern.

For a more complex example in using the \, in replacement, see: Regex Replace with a Function in Emacs Lisp.

Search (Emacs Manual)

Emacs Find Replace