Emacs Search and Replace

Protesilaos Stavrou (Prot) has a really, really excellent video on the Emacs search/replace functionality. Except for a short section at the end, it doesn’t consider external packages; it’s about the default functionality. Although Prot says the video considers only the basics and is not meant to be comprehensive, it is, in fact, a fairly complete explanation of how you can search and replace out-of-the-box with Emacs.

Prot starts, of course, with isearch. You wouldn’t think there’s that much to know other than, say, being able to search in reverse but there’s much, much more. You can, for example, move forward and backwards within the matches using Ctrl+s / Ctrl+r (with the default bindings). That’s pretty well known but did you know that you can exit the search with any motion command? That’s really handy if you want to position the cursor at, say, the beginning of the target word. Just type Meta+b to exit the search and put the cursor at the start of the word. There’s plenty more functionality including putting the results in an occur buffer so take a look at the video for the details.

Of course, you can also do regular expression searches. I generally use swiper-isearch from the Swiper/Ivy package to do my searches and one of its features that I really like is that a single space in a regex is interpreted as .*?. That covers a surprisingly large fraction of the cases that you use more complex regexes for. It turns out, that you can configure isearch-forward-regexp (and its backward sibling) to the do same thing. See the video for the magic incantation.

The search commands all have corresponding search/replace variants and Prot covers those too. Most of the extra functionality that Prot describes for searching applies to those commands too.

Finally the video considers occur and wgrep and how you can move to these from any of the search commands. There’s a lot of material so you need to watch it to see everything that’s available. The video is just short of an hour (53 minutes, 2 seconds) so you’ll need to schedule it but believe me, it’s worth your time.

This entry was posted in General and tagged . Bookmark the permalink.