unofficial mirror of help-gnu-emacs@gnu.org
 help / color / mirror / Atom feed
* query-replace-regexp-swap ?
@ 2005-11-24  2:10 Bastien
  2005-11-26  2:03 ` rgb
  2005-11-26  6:22 ` David Kastrup
  0 siblings, 2 replies; 7+ messages in thread
From: Bastien @ 2005-11-24  2:10 UTC (permalink / raw)


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

^ permalink raw reply	[flat|nested] 7+ messages in thread

end of thread, other threads:[~2005-11-28 13:54 UTC | newest]

Thread overview: 7+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2005-11-24  2:10 query-replace-regexp-swap ? Bastien
2005-11-26  2:03 ` rgb
2005-11-26  3:54   ` Bastien
2005-11-26  6:22 ` David Kastrup
2005-11-28 12:59   ` Bastien
2005-11-28 13:35     ` David Kastrup
2005-11-28 13:54       ` Bastien

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for read-only IMAP folder(s) and NNTP newsgroup(s).