Emacs: Find Replace in Current File
Interactive Find Replace in Current Buffer
query-replace
【Alt+%】Find replace from cursor position to end of buffer, or text selection.
Emacs prompts you for the find string and replace string.
Once emacs found a match, press
- y → replace
- n → skip
- ! → do all replacement without asking.
- Ctrl+g → cancel.
To undo, press Ctrl+g to cancel, then Ctrl+/ to undo existing replacement.
Find Replace in Current Buffer, by Regex Pattern
- Alt+x
query-replace-regexp
【Ctrl+Alt+%】 -
Find replace a Regular Expression pattern from cursor position to end of buffer, or text selection.
Find Replace with Word Boundary
say you want to change the word “red” to “blue”, but skip words containg “red” such as “redo”.
you need to use Emacs: Regular Expression with word boundary.
- Alt+x
query-replace-regexp
- then type
\bred\b
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.
Emacs Find Replace
- Emacs: Search Text in Current File
- Emacs: Search Current Word 💠
- Emacs: Highlight Word, Line
- Emacs: List Matching Lines
- Emacs: Search Text in Directory
- Emacs: Find Replace in Current File
- Emacs: Find Replace Text in Directory
- Emacs: Xah Find Replace (xah-find.el) 📦
- Emacs: Regular Expression
- Emacs Init: isearch Whitespace Regex
- Emacs Init: isearch by Arrow Keys