[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
query-replace-regexp-swap ?
From: |
Bastien |
Subject: |
query-replace-regexp-swap ? |
Date: |
Thu, 24 Nov 2005 02:10:40 +0000 |
User-agent: |
Gnus/5.110004 (No Gnus v0.4) Emacs/22.0.50 (gnu/linux) |
I often come across this problem: how to swap two strings in a buffer?
For instance, say that you want to exchange #000 and #FFF in an HTML
page: all #000 should become #FFF and all #FFF should become #000.
How to do this with one *single* function ?
For now i use this:
==%<==================================================================
(defun query-replace-regexp-swap (regexp-a regexp-b beg end)
"Swap A and B strings in the selected region."
(interactive
(let ((regexp-a (read-string "Regexp A: "))
(regexp-b (read-string "Regexp B: ")))
(list regexp-a regexp-b (region-beginning) (region-end))))
(save-match-data
(save-excursion
(goto-char beg)
(let* ((regexp (concat "\\(" regexp-a "\\)\\|"
"\\(" regexp-b "\\)"))
(match-a (save-excursion
(re-search-forward regexp-a end t)
(match-string 0)))
(match-b (save-excursion
(re-search-forward regexp-b end t)
(match-string 0))))
(while (re-search-forward regexp nil t)
(cond ((match-string 1)
(when (y-or-n-p (format "Replace with %s? " match-b))
(replace-match match-b t t)))
((match-string 2)
(when (y-or-n-p (format "Replace with %s? " match-a))
(replace-match match-a t t)))))))))
======================================================================
... which is quite UGLY.
Any idea on how to use `perform-replace' to achieve this in a more
efficient way?
--
Bastien
- query-replace-regexp-swap ?,
Bastien <=