Lisp and Replace-Regexp

Álvaro Ramírez has a nice post that reminds us of one of those things you don’t need very often but when you do it’s exactly the right tool. Emacs has many ways of doing mass replacements but one of the most fundamental is replace-regexp. It and its sibling query-replace-regexp are generally the first method an Emacs n00b learns for performing find and replace operation.

Being Emacs, these functions are, of course, more powerful than their cousins from other editors and word processors. The first big advantage is that you can search for a regular expression rather than just a text string. Of course many other editors have this feature but Emacs allows you particular power in forming the replacement string.

As Ramírez points out in his blog post Emacs: smarter search and replace, you can do arbitrarily complex replacements because Emacs allows you to use Elisp to form the replacement string. That means you can transform the input string in just about any way you like. Ramírez use a recent question from Reddit as a test case: how can you apply a function to every number in a buffer?

The secret is to merely use \,(some Elisp) as the replacement string. To help out with forming the replacement, Emacs provide \& and \n as variables that contain the entire matched string and the \(n^{\textrm{th}}\) submatch. You can also specify those as \#& and \#n in which case the match is converted to a number before being passed to the Elisp. You can see all this in action by taking a look at Ramírez’s post.

I probably don’t use the \, replacement more than once a year but when I do I’m really happy to have it. Given how seldomly you’ll probably use it, you don’t have to memorize the details. Just knowing it exists is enough because it’s easy to look it up with describe function.

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