Emacs区分大小写替换字符串

13

我刚刚问了一个相关的问题(设置问题),但是它明显不同,所以我决定用这个问题分支。

在我的.emacs文件中,我定义了一个键绑定到replace-string命令:

(define-key global-map "\C-r" 'replace-string)

replace-string可以进行基本的查找和替换。假设搜索字符串的第一个字母是小写字母,如果case-fold-searchnil,则replace-string执行区分大小写的搜索,否则执行不区分大小写的搜索。

问题在于case-fold-search控制了“搜索”的“大小写敏感性”(例如像search-forward命令这样的搜索),以及“搜索和替换”的“大小写敏感性”(例如像replace-string命令这样的搜索和替换)。

问题是如何使只有replace-string命令(或任何绑定到C-r的命令)区分大小写,使得search-forward保持默认的不区分大小写。

也许我需要仅针对replace-string命令设置case-fold-searchnil,但我不确定该如何做到这一点。

2个回答

11

把这段代码放入你的 .emacs 文件中:

(defadvice replace-string (around turn-off-case-fold-search)
  (let ((case-fold-search nil))
    ad-do-it))

(ad-activate 'replace-string)

这正好实现了你所说的,只是针对replace-stringcase-fold-search设置为nil
事实上,这几乎就是Emacs Lisp参考手册中的例子。 2021年11月2日编辑: 正如上面链接所示,defadvice不再是推荐的实现方式。新的推荐实现方式是:
(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)

7

尝试这种不需要建议的方法:

(global-set-key (kbd "C-r") 
    (lambda () 
      (interactive) 
      (let ((case-fold-search nil)) 
        (call-interactively 'replace-string))))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接