EmacsWiki: Query Exchange (original) (raw)

(defun query-exchange (string-1 string-2) "Exchange string-1 and string-2 interactively. The user is prompted at each instance like query-replace." (interactive "sString 1: \nsString 2: ") (perform-replace (concat "\(" string-1 "\)\|" string-2) '(replace-eval-replacement replace-quote (if (match-string 1) string-2 string-1)) t t nil))

I use a hybrid of above code and the source of query-replace-regexp from replace.el (emacs source) to be able to do query exchange only within a region if one is selected.

(defun query-exchange (string-1 string-2 &optional delimited start end) "Exchange string-1 and string-2 interactively. The user is prompted at each instance like query-replace." (interactive (let ((common (query-replace-read-args (concat "Query replace" (if current-prefix-arg " word" "") " regexp" (if (and transient-mark-mode mark-active) " in region" "")) t))) (list (nth 0 common) (nth 1 common) (nth 2 common)

   (if (and transient-mark-mode mark-active)
       (region-beginning))
   (if (and transient-mark-mode mark-active)
       (region-end)))))

(perform-replace (concat "\(" string-1 "\)\|" string-2) '(replace-eval-replacement replace-quote (if (match-string 1) string-2 string-1)) t t delimited nil nil start end))