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
andb
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.