I just asked a related question (setq question) but it's distinctly different, so I decided to branch off with this question.
In my .emacs file, I define a key binding to the replace-string command:
(define-key global-map "\C-r" 'replace-string)
replace-string does basic search and replace. Assuming the first letter of the search string is lowercase, if the case-fold-search is nil then replace-string does case-sensitive search, otherwise it does case-insensitive search.
The problem is that case-fold-search controls the "case-sensitiveness" of both "search" (like the search-forward command) and "search and replace" (like the replace-string command).
The question is how do I make JUST the replace-string command (or anything C-r is bound to) case-sensitive, leaving the search-forward case-insensitive as it is by default.
Perhaps I would need to set case-fold-search to nil just for the replace-string command, but I'm not sure how to do that.
Replace() method allows you to easily replace a substring with another substring, or a character with another character, within the contents of a String object. This method is very handy, but it is always case-sensitive. So I thought it would be interesting to create a case-insensitive version of this method.
When you want to replace every instance of a given string, you can use a simple command that tells Emacs to do just that. Type ESC x replace-string RETURN, then type the search string and press RETURN. Now type the replacement string and press RETURN again.
replace method is case sensitive.
Try this method, which does not require advice:
(global-set-key (kbd "C-r")
(lambda ()
(interactive)
(let ((case-fold-search nil))
(call-interactively 'replace-string))))
Put this in your .emacs:
(defadvice replace-string (around turn-off-case-fold-search)
(let ((case-fold-search nil))
ad-do-it))
(ad-activate 'replace-string)
This does exactly what you said, set case-fold-search to nil just for replace-string.
In fact this is almost exactly the example in the Emacs Lisp reference manual.
Edit on 2021-11-02: as the link above indicates, defadvice is no longer the recommended way to implement this. The new recommended implementation would be
(defun with-case-fold-search (orig-fun &rest args)
(let ((case-fold-search t))
(apply orig-fun args)))
(advice-add 'replace-string :around #'with-case-fold-search)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With