Basic text replacement

You can replace text using M-% (which runs the command query-replace). For example, to replace “foo” with “bar”, use M-x RET foo RET bar and then emacs will step through all the occurrences of “foo” asking if you want to replace them. You can hit y, n, to say yes or no to each, or ! to say yes to all.

Replacement runs from the current cursor position, so to run it everywhere in the buffer, you can jump to the start of the buffer first. Also, remember that when you have finished with your search and/or replace, you can jump back to where you started with C-u SPACE.

Note also, that if you highlight a region, then query-replace will only run on the selected region.

Later on we’ll come back to this topic to look at more advanced text replacement using regular expressions and other neat additions.