交互式Emacs Lisp函数可以互相交换两个单词

Eog*_*anM 5 emacs swap elisp

我第一次进入emacs lisp的古怪世界是一个函数,它需要两个字符串并互相交换它们:

(defun swap-strings (a b)
  "Replace all occurances of a with b and vice versa"
  (interactive "*sFirst Swap Word: \nsSecond Swap Word: ")
  (save-excursion
    (while (re-search-forward (concat a "\\|" b) nil t)
      (if (equal (match-string 0) a)
      (replace-match b)
    (replace-match a)))))
Run Code Online (Sandbox Code Playgroud)

这有效 - 但我坚持以下几点:

  • 如何在每次更换前提示用户确认?(我无法perform-replace上班)
  • 如何转义字符串a,b所以如果它们包含任何正则表达式字符,它们不会被解释为正则表达式?

编辑:我用了一段时间的最终拷贝可用代码是:

(defun swap-words (a b)
  "Replace all occurances of a with b and vice versa"
  (interactive "*sFirst Swap Word: \nsSecond Swap Word: ")
  (save-excursion
    (while (re-search-forward (concat (regexp-quote a) "\\|" (regexp-quote b)))
      (if (y-or-n-p "Swap?") 
      (if (equal (match-string 0) a)
          (replace-match (regexp-quote b))
        (replace-match (regexp-quote a))))
      )))
Run Code Online (Sandbox Code Playgroud)

不幸的是,它没有像I-search那样突出显示页面上的即将到来的匹配.

sco*_*zer 3

用于y-or-n-p第一个:(when (y-or-n-p "Swap?") do stuff

对于regexp-quote第二个:(regexp-quote your-string)