Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 479
Alan Turing Avatar asked Mar 17 '11 22:03

Alan Turing


People also ask

Is String replace case sensitive?

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.

How do I replace a string in Emacs?

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.

Is Javascript replace case sensitive?

replace method is case sensitive.


2 Answers

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))))
like image 55
jlf Avatar answered Oct 18 '22 20:10

jlf


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)
like image 44
dfan Avatar answered Oct 18 '22 21:10

dfan