Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interactive Emacs Lisp function to swap two words with each other

Tags:

emacs

swap

elisp

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.

like image 676
EoghanM Avatar asked Oct 14 '22 16:10

EoghanM


1 Answers

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)

like image 125
scottfrazer Avatar answered Oct 20 '22 20:10

scottfrazer