tags:

views:

463

answers:

3

My first foray into the quirky world of emacs lisp is a function which takes two strings and swaps them with eachother:

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

This works - but I'm stuck on the following:

  • how to prompt the user for confirmation before each replacement? (I can't get perform-replace to work)
  • how to escape the strings a and b so they don't get interpreted as regexes if they contain any regex characters?

Edit: The final copy-pastable code I've been using for some time is:

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

Unfortunately, it doesn't highlight upcoming matches on the page like I-search does.

+3  A: 

Use y-or-n-p for the first: (when (y-or-n-p "Swap?") do stuff

And regexp-quote for the second: (regexp-quote your-string)

scottfrazer
+1  A: 

regexp-quote is already mentioned.

As for the confirmation, if you want to ask the user before each replacement, you may choose query-replace-regexp that does exactly what you want.

(And you can still deal with Emacs's builtin transponse functions.)

Török Gábor
A: 

Found this that uses the built in query-replace: http://www.opensubscriber.com/message/[email protected]/2676079.html

Jimi Malcolm