So, I have the following buffer:


# colors


Now, if I run M-x replace-regexp I get odd results. If I have the search string: ^\(.+\)$ and the replacement string: example string:\1 I get the following output:

example string:1234
Example String:Red  
example string:blue
example string:green
example string:yellow

example string:# colors

example string:orange

As can be seen, I get Example String:Red instead of the expected example string:Red. What's the deal with this behavior?


2 Answers 2


C-h f replace-regexp says:

Preserve case in each match if case-replace and case-fold-search are non-nil and REGEXP has no uppercase letters.

Either set replace-case to nil before you run the replacement command or write a new command that binds case-replace to nil and then calls replace-regexp. Something like this:

(defun my-replace ()
 (let ((case-replace  nil))
   (replace-regexp "^\\(.+\\)$" "example string:\\1")))

See node Regexp Replace of the Emacs manual.

  • How do you pass an argument in the way you're describing to a command?
    – junius
    Commented Aug 17, 2017 at 21:39
  • I accepted this answer, but that doesn't really solve the problem for the general case though.
    – junius
    Commented Aug 17, 2017 at 21:52
  • What's the general case? You can use arbitrary Lisp code in the replacement string. With that, you can use function downcase. The possibilities, just like the number of "general cases", are endless.
    – Drew
    Commented Aug 17, 2017 at 21:56
  • Right, but is there a way to create a version of the replace M-x replace-regexp command where case-replace is bound to nil without having to re-implement the whole thing?
    – junius
    Commented Aug 17, 2017 at 21:59
  • You're not reimplementing "the whole thing". You're just binding a variable around "the whole thing". Alternatively, just set the variable before calling the command; then set it back again, if you want. A global variable controls this behavior - for your convenience. You can customize the variable, to get your preferred behavior by default in every Emacs session. Or you can set the variable temporarily. Or you can bind it in a particular command (use case). It all depends on just what you need/want to do.
    – Drew
    Commented Aug 17, 2017 at 22:02

This is caused by the case-replace option. If you disable that option, the replacement case will be as you entered it for all instances.

The purpose of the option is more to maintain the original case for replacements like red -> green in which case:


would become


If you disable that option, the replacements would be:


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.