2009-04-20 83 views
5

我首次涉足的Emacs Lisp的离奇世界是一个函数,它接受两个字符串,并与海誓山盟交换他们:互动的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))))) 

这工作 - 但我m卡在以下内容:

  • 如何在每次更换前提示用户确认? (我不能得到perform-replace工作)
  • 如何逃避字符串ab所以他们不会被解释为正则表达式,如果他们包含任何正则表达式字符?

编辑:我已经使用了一段时间的最后复制pastable代码:

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

不幸的是,它并不突出像我搜索确实在页面上即将开始的比赛。

回答

3

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

而且regexp-quote第二:(regexp-quote your-string)

1

regexp-quotealready mentioned

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

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