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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With