Emacs tip: Using lisp expressions in replace-regexp

Miscellaneous tip of the day, mostly putting it here so I'll remember it later!

In recent versions of Emacs, you can use lisp expressions to process the replacement result when running a search/replace regexp command (e.g. replace-regexp).

The syntax for that is:

\,(expression ...)

The real handy part is that \0, \1, …, \9 work even inside the expression, allowing you to run an expression on the result of your search.

As a contrived example, if you wanted to change every vowel in the buffer to upper case, you could replace-regexp with the following search regexp and replacement regexp:

[aeiou]
\,(upcase \0)

In a real use case, I wanted to convert words like “m11”, “m12”, “m23”, etc. to “m00”, “m01”, “m12” — subtracting one from each digit in the name. Here are the search and replacement regexps I used:

m([1-9])([1-9])
m\,(- (string-to-int \1) 1)\,(- (string-to-int \2) 1)

Pretty handy!

Previous post: Nonogram Game Next post: Music Toy Idea