Reputation: 27043
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:
perform-replace
to work)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.
Upvotes: 5
Views: 1625
Reputation: 26322
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.)
Upvotes: 1
Reputation: 17337
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)
Upvotes: 3