Here’s a Find-Replace which swaps values:
Find: right\|left
Repl: \,(if (equal "right" \&) "left" "right")
Here’s an attempt to convert it into interactive function:
(defun swaps (rit lft)
"Swaps rit to lft."
(interactive "sChange this:
sTo this: ")
(save-excursion
(goto-char (region-beginning))
(while (search-forward-regexp ("%s\\|%s" rit lft) nil t)
(replace-match (if (equal rit \\&) lft rit) t nil))))
I also tried rit\\|lft and rit\|lft instead of ("%s\\|%s" rit lft)…
Edit:
The answer is:
(defun swaps (rit lft)
"Swaps rit to lft."
(interactive "sChange this:
sTo this: ")
(save-excursion
(goto-char (region-beginning))
(while (search-forward-regexp (format "%s\\|%s"
(regexp-quote rit)
(regexp-quote lft)) (region-end) t)
(replace-match (if (equal rit (match-string 0)) lft rit) t nil))))
("%s\\|%s" rit lft)isn’t a valid Lisp expression: when it’s evaluated Emacs will complain that"%s\\|%s"isn’t a function. You probably want to doand it would be better to use
regexp-quotein case your strings contain regexp special characters:Alternatively, you could also use the
regexp-optfunction, which constructs an efficient regexp to match any one of a list of strings:\\&only represents the matched string within a replacement argument toreplace-regexp,replace-matchand similar functions. In other Lisp code you need to use(match-string 0).Finally, if you only want this to work on the region you should probably supply
(region-end)as the second argument tosearch-forward-regexp.