kotatsuyaki’s site

Re: Use 'M-x query-replace-regexp' to downcase matches

Published on

In reply to Use ‘M-x query-replace-regexp’ to downcase matches by Protesilaos Stavrou.

I was looking for a way to perform a regular expression replacement with case conversions (uppercase to lowercase in the particular case) and found the post. Emacs supports evaluating Lisp functions from the regexp in query-replace-regexp, and I should be able to do it with the \,(downcase \1):

M-x query-replace-regexp RET \(some_pattern_here\) RET "\,(downcase \1)" RET

The above downcase​s every matching strings and wraps each of them within a pair of parentheses. Except that it didn’t—it did add the parentheses for me, but the uppercase letters remain uppercase.

Several days later, I found the reason in an answer to a SO question: replace-regexp and its friends repect the case-replace variable by preserving the original case if it’s non-nil. Incidentally, this is actually documented in M-x describe-function query-replace-regexp, which is a reminder to always read the docs that come with Emacs:

Replacement transfers the case pattern of the old text to the new
text, if both ‘case-fold-search’ and ‘case-replace’ are non-nil
and REGEXP has no uppercase letters.  (Transferring the case pattern
means that if the old text matched is all caps, or all of its words
are capitalized, then its replacement is respectively upcased or
capitalized.  For more details about this, see ‘replace-match’.)

To disable this behavior, run (setq case-replace nil), problem solved.