【问题标题】:Interactive Emacs Lisp function to swap two words with each other交互式 Emacs Lisp 函数用于交换两个单词
【发布时间】:2009-04-20 13:27:22
【问题描述】:

我第一次进入古怪的 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 那样在页面上突出显示即将到来的匹配项。

【问题讨论】:

    标签: emacs elisp swap


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      regexp-quotealready mentioned

      至于确认,如果您想在每个更换之前询问用户,您可以选择query-replace-regexp,这正是您想要的。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多