Emacs Case Sensitive Replace String
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
开发者_如何学JAVA 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.
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)
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))))
精彩评论