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

时间:2009-04-20 13:27:22

标签: emacs elisp swap

我第一次进入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)))))

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

  • 每次更换前如何提示用户确认? (我无法让perform-replace工作)
  • 如何转义字符串ab,这样如果它们包含任何正则表达式字符,它们就不会被解释为正则表达式?

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

(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))))
      )))

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

2 个答案:

答案 0 :(得分:3)

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

第二个regexp-quote(regexp-quote your-string)

答案 1 :(得分:1)

regexp-quotealready mentioned

至于确认,如果您想在每次替换之前询问用户,您可以选择完全符合您要求的query-replace-regexp

(你仍然可以处理Emacs的内置transponse functions。)