XEmacs 21.2-b1
[chise/xemacs-chise.git.1] / lisp / replace.el
1 ;;; replace.el --- search and replace commands for XEmacs.
2
3 ;; Copyright (C) 1985-7, 1992, 1994, 1997 Free Software Foundation, Inc.
4
5 ;; Maintainer: XEmacs Development Team
6 ;; Keywords: dumped, matching
7
8 ;; This file is part of XEmacs.
9
10 ;; XEmacs is free software; you can redistribute it and/or modify it
11 ;; under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; XEmacs is distributed in the hope that it will be useful, but
16 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18 ;; General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with XEmacs; see the file COPYING.  If not, write to the Free
22 ;; Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
23 ;; 02111-1307, USA.
24
25 ;;; Synched up with: FSF 19.34 [Partially].
26
27 ;;; Commentary:
28
29 ;; This file is dumped with XEmacs.
30
31 ;; This package supplies the string and regular-expression replace functions
32 ;; documented in the XEmacs Reference Manual.
33
34 ;; All the gettext calls are for XEmacs I18N3 message catalog support.
35 ;; (This is hopelessly broken and we should remove it. -sb)
36
37 ;;; Code:
38
39 (defvar case-replace t "\
40 *Non-nil means `query-replace' should preserve case in replacements.
41 What this means is that `query-replace' will change the case of the
42 replacement text so that it matches the text that was replaced.
43 If this variable is nil, the replacement text will be inserted
44 exactly as it was specified by the user, irrespective of the case
45 of the text that was replaced.
46
47 Note that this flag has no effect if `case-fold-search' is nil,
48 or if the replacement text has any uppercase letters in it.")
49
50 (defvar query-replace-history nil)
51
52 (defvar query-replace-interactive nil
53   "Non-nil means `query-replace' uses the last search string.
54 That becomes the \"string to replace\".")
55
56 (defun query-replace-read-args (string regexp-flag)
57   (let (from to)
58     (if query-replace-interactive
59         (setq from (car (if regexp-flag regexp-search-ring search-ring)))
60       (setq from (read-from-minibuffer (format "%s: " (gettext string))
61                                        nil nil nil
62                                        'query-replace-history)))
63     (setq to (read-from-minibuffer (format "%s %s with: " (gettext string)
64                                            from)
65                                    nil nil nil
66                                    'query-replace-history))
67     (list from to current-prefix-arg)))
68
69 ;; As per suggestion from Per Abrahamsen, limit replacement to the region
70 ;; if the region is active.
71 (defun query-replace (from-string to-string &optional delimited)
72   "Replace some occurrences of FROM-STRING with TO-STRING.
73 As each match is found, the user must type a character saying
74 what to do with it.  For directions, type \\[help-command] at that time.
75
76 If `query-replace-interactive' is non-nil, the last incremental search
77 string is used as FROM-STRING--you don't have to specify it with the
78 minibuffer.
79
80 Preserves case in each replacement if `case-replace' and `case-fold-search'
81 are non-nil and FROM-STRING has no uppercase letters.
82 \(Preserving case means that if the string matched is all caps, or capitalized,
83 then its replacement is upcased or capitalized.)
84
85 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
86 only matches surrounded by word boundaries.
87
88 To customize possible responses, change the \"bindings\" in `query-replace-map'."
89   (interactive (query-replace-read-args "Query replace" nil))
90   (perform-replace from-string to-string t nil delimited))
91
92 (defun query-replace-regexp (regexp to-string &optional delimited)
93   "Replace some things after point matching REGEXP with TO-STRING.
94 As each match is found, the user must type a character saying
95 what to do with it.  For directions, type \\[help-command] at that time.
96
97 If `query-replace-interactive' is non-nil, the last incremental search
98 regexp is used as REGEXP--you don't have to specify it with the
99 minibuffer.
100
101 Preserves case in each replacement if `case-replace' and `case-fold-search'
102 are non-nil and REGEXP has no uppercase letters.
103 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
104 only matches surrounded by word boundaries.
105 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
106 and `\\=\\N' (where N is a digit) stands for
107  whatever what matched the Nth `\\(...\\)' in REGEXP."
108   (interactive (query-replace-read-args "Query replace regexp" t))
109   (perform-replace regexp to-string t t delimited))
110
111 ;;#### Not patently useful
112 (defun map-query-replace-regexp (regexp to-strings &optional arg)
113   "Replace some matches for REGEXP with various strings, in rotation.
114 The second argument TO-STRINGS contains the replacement strings, separated
115 by spaces.  This command works like `query-replace-regexp' except
116 that each successive replacement uses the next successive replacement string,
117 wrapping around from the last such string to the first.
118
119 Non-interactively, TO-STRINGS may be a list of replacement strings.
120
121 If `query-replace-interactive' is non-nil, the last incremental search
122 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
123
124 A prefix argument N says to use each replacement string N times
125 before rotating to the next."
126   (interactive
127    (let (from to)
128      (setq from (if query-replace-interactive
129                     (car regexp-search-ring)
130                   (read-from-minibuffer "Map query replace (regexp): "
131                                         nil nil nil
132                                         'query-replace-history)))
133      (setq to (read-from-minibuffer
134                (format "Query replace %s with (space-separated strings): "
135                        from)
136                nil nil nil
137                'query-replace-history))
138      (list from to current-prefix-arg)))
139   (let (replacements)
140     (if (listp to-strings)
141         (setq replacements to-strings)
142       (while (/= (length to-strings) 0)
143         (if (string-match " " to-strings)
144             (setq replacements
145                   (append replacements
146                           (list (substring to-strings 0
147                                            (string-match " " to-strings))))
148                   to-strings (substring to-strings
149                                        (1+ (string-match " " to-strings))))
150           (setq replacements (append replacements (list to-strings))
151                 to-strings ""))))
152     (perform-replace regexp replacements t t nil arg)))
153
154 (defun replace-string (from-string to-string &optional delimited)
155   "Replace occurrences of FROM-STRING with TO-STRING.
156 Preserve case in each match if `case-replace' and `case-fold-search'
157 are non-nil and FROM-STRING has no uppercase letters.
158 \(Preserving case means that if the string matched is all caps, or capitalized,
159 then its replacement is upcased or capitalized.)
160
161 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
162 only matches surrounded by word boundaries.
163
164 If `query-replace-interactive' is non-nil, the last incremental search
165 string is used as FROM-STRING--you don't have to specify it with the
166 minibuffer.
167
168 This function is usually the wrong thing to use in a Lisp program.
169 What you probably want is a loop like this:
170   (while (search-forward FROM-STRING nil t)
171     (replace-match TO-STRING nil t))
172 which will run faster and will not set the mark or print anything."
173   (interactive (query-replace-read-args "Replace string" nil))
174   (perform-replace from-string to-string nil nil delimited))
175
176 (defun replace-regexp (regexp to-string &optional delimited)
177   "Replace things after point matching REGEXP with TO-STRING.
178 Preserve case in each match if `case-replace' and `case-fold-search'
179 are non-nil and REGEXP has no uppercase letters.
180 \(Preserving case means that if the string matched is all caps, or capitalized,
181 then its replacement is upcased or capitalized.)
182
183 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
184 only matches surrounded by word boundaries.
185 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
186 and `\\=\\N' (where N is a digit) stands for
187  whatever what matched the Nth `\\(...\\)' in REGEXP.
188
189 If `query-replace-interactive' is non-nil, the last incremental search
190 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
191
192 This function is usually the wrong thing to use in a Lisp program.
193 What you probably want is a loop like this:
194   (while (re-search-forward REGEXP nil t)
195     (replace-match TO-STRING nil nil))
196 which will run faster and will not set the mark or print anything."
197   (interactive (query-replace-read-args "Replace regexp" t))
198   (perform-replace regexp to-string nil t delimited))
199
200 \f
201 (defvar regexp-history nil
202   "History list for some commands that read regular expressions.")
203
204 (define-function 'keep-lines 'delete-non-matching-lines)
205 (defun delete-non-matching-lines (regexp)
206   "Delete all lines except those containing matches for REGEXP.
207 A match split across lines preserves all the lines it lies in.
208 Applies to all lines after point."
209   (interactive (list (read-from-minibuffer
210                       "Keep lines (containing match for regexp): "
211                       nil nil nil 'regexp-history)))
212   (save-excursion
213     (or (bolp) (forward-line 1))
214     (let ((start (point)))
215       (while (not (eobp))
216         ;; Start is first char not preserved by previous match.
217         (if (not (re-search-forward regexp nil 'move))
218             (delete-region start (point-max))
219           (let ((end (save-excursion (goto-char (match-beginning 0))
220                                      (beginning-of-line)
221                                      (point))))
222             ;; Now end is first char preserved by the new match.
223             (if (< start end)
224                 (delete-region start end))))
225         (setq start (save-excursion (forward-line 1)
226                                     (point)))
227         ;; If the match was empty, avoid matching again at same place.
228         (and (not (eobp)) (= (match-beginning 0) (match-end 0))
229              (forward-char 1))))))
230
231 (define-function 'flush-lines 'delete-matching-lines)
232 (defun delete-matching-lines (regexp)
233   "Delete lines containing matches for REGEXP.
234 If a match is split across lines, all the lines it lies in are deleted.
235 Applies to lines after point."
236   (interactive (list (read-from-minibuffer
237                       "Flush lines (containing match for regexp): "
238                       nil nil nil 'regexp-history)))
239   (save-excursion
240     (while (and (not (eobp))
241                 (re-search-forward regexp nil t))
242       (delete-region (save-excursion (goto-char (match-beginning 0))
243                                      (beginning-of-line)
244                                      (point))
245                      (progn (forward-line 1) (point))))))
246
247 (define-function 'how-many 'count-matches)
248 (defun count-matches (regexp)
249   "Print number of matches for REGEXP following point."
250   (interactive (list (read-from-minibuffer
251                       "How many matches for (regexp): "
252                       nil nil nil 'regexp-history)))
253   (let ((count 0) opoint)
254     (save-excursion
255      (while (and (not (eobp))
256                  (progn (setq opoint (point))
257                         (re-search-forward regexp nil t)))
258        (if (= opoint (point))
259            (forward-char 1)
260          (setq count (1+ count))))
261      (message "%d occurrences" count))))
262
263 \f
264 (defvar occur-mode-map ())
265 (if occur-mode-map
266     ()
267   (setq occur-mode-map (make-sparse-keymap))
268   (set-keymap-name occur-mode-map 'occur-mode-map) ; XEmacs
269   (define-key occur-mode-map 'button2 'occur-mode-mouse-goto) ; XEmacs
270   (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence)
271   (define-key occur-mode-map "\C-m" 'occur-mode-goto-occurrence))
272
273 (defvar occur-buffer nil)
274 (defvar occur-nlines nil)
275 (defvar occur-pos-list nil)
276
277 (defun occur-mode ()
278   "Major mode for output from \\[occur].
279 \\<occur-mode-map>Move point to one of the items in this buffer, then use
280 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
281 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
282
283 \\{occur-mode-map}"
284   (kill-all-local-variables)
285   (use-local-map occur-mode-map)
286   (setq major-mode 'occur-mode)
287   (setq mode-name (gettext "Occur")) ; XEmacs
288   (make-local-variable 'occur-buffer)
289   (make-local-variable 'occur-nlines)
290   (make-local-variable 'occur-pos-list)
291   (require 'mode-motion) ; XEmacs
292   (setq mode-motion-hook 'mode-motion-highlight-line) ; XEmacs
293   (run-hooks 'occur-mode-hook))
294
295 ;; FSF Version of next function:
296 ;  (let (buffer pos)
297 ;    (save-excursion
298 ;      (set-buffer (window-buffer (posn-window (event-end event))))
299 ;      (save-excursion
300 ;       (goto-char (posn-point (event-end event)))
301 ;       (setq pos (occur-mode-find-occurrence))
302 ;       (setq buffer occur-buffer)))
303 ;    (pop-to-buffer buffer)
304 ;    (goto-char (marker-position pos))))
305
306 (defun occur-mode-mouse-goto (event)
307   "Go to the occurrence highlighted by mouse.
308 This function is only reasonable when bound to a mouse key in the occur buffer"
309   (interactive "e")
310   (let ((window-save (selected-window))
311         (frame-save (selected-frame)))
312     ;; preserve the window/frame setup
313     (unwind-protect
314         (progn
315           (mouse-set-point event)
316           (occur-mode-goto-occurrence))
317       (select-frame frame-save)
318       (select-window window-save))))
319
320 ;; Called occur-mode-find-occurrence in FSF
321 (defun occur-mode-goto-occurrence ()
322   "Go to the occurrence the current line describes."
323   (interactive)
324   (if (or (null occur-buffer)
325           (null (buffer-name occur-buffer)))
326       (progn
327         (setq occur-buffer nil
328               occur-pos-list nil)
329         (error "Buffer in which occurrences were found is deleted")))
330   (let* ((line-count
331           (count-lines (point-min)
332                        (save-excursion
333                          (beginning-of-line)
334                          (point))))
335          (occur-number (save-excursion
336                          (beginning-of-line)
337                          (/ (1- line-count)
338                             (cond ((< occur-nlines 0)
339                                    (- 2 occur-nlines))
340                                   ((> occur-nlines 0)
341                                    (+ 2 (* 2 occur-nlines)))
342                                   (t 1)))))
343          (pos (nth occur-number occur-pos-list))
344          ;; removed t arg from Bob Weiner, 10/6/95
345          (window (get-buffer-window occur-buffer))
346          (occur-source-buffer occur-buffer))
347     (if (< line-count 1)
348         (error "No occurrence on this line"))
349     (or pos
350         (error "No occurrence on this line"))
351     ;; XEmacs: don't raise window unless it isn't visible
352     ;; allow for the possibility that the occur buffer is on another frame
353     (or (and window
354              (window-live-p window)
355              (frame-visible-p (window-frame window))
356              (set-buffer occur-source-buffer))
357         (and (pop-to-buffer occur-source-buffer)
358              (setq window (get-buffer-window occur-source-buffer))))
359     (goto-char pos)
360     (set-window-point window pos)))
361
362 \f
363 (defvar list-matching-lines-default-context-lines 0
364   "*Default number of context lines to include around a `list-matching-lines'
365 match.  A negative number means to include that many lines before the match.
366 A positive number means to include that many lines both before and after.")
367
368 ;; XEmacs addition
369 ;;; Damn you Jamie, this is utter trash.
370 (defvar list-matching-lines-whole-buffer t
371   "If t, occur operates on whole buffer, otherwise occur starts from point.
372 default is t.")
373
374 (define-function 'occur 'list-matching-lines)
375 (defun list-matching-lines (regexp &optional nlines)
376   "Show all lines in the current buffer containing a match for REGEXP.
377
378 If a match spreads across multiple lines, all those lines are shown.
379
380 If variable `list-matching-lines-whole-buffer' is non-nil, the entire buffer is
381 searched, otherwise search begins at point.
382
383 Each line is displayed with NLINES lines before and after, or -NLINES
384 before if NLINES is negative.
385 NLINES defaults to `list-matching-lines-default-context-lines'.
386 Interactively it is the prefix arg.
387
388 The lines are shown in a buffer named `*Occur*'.
389 It serves as a menu to find any of the occurrences in this buffer.
390 \\[describe-mode] in that buffer will explain how."
391   (interactive
392    ;; XEmacs change
393    (list (let* ((default (or (symbol-near-point)
394                              (and regexp-history
395                                   (car regexp-history))))
396                 (minibuffer-history-minimum-string-length 0)
397                 (input
398                  (if default
399                      ;; rewritten for I18N3 snarfing
400                      (read-from-minibuffer
401                       (format "List lines matching regexp (default `%s'): "
402                               default) nil nil nil 'regexp-history)
403                    (read-from-minibuffer
404                     "List lines matching regexp: "
405                     nil nil nil
406                     'regexp-history))))
407            (if (and (equal input "") default)
408                (progn
409                  (setq input default)
410                  (setcar regexp-history default)))
411            ;; clear extra entries
412            (setcdr regexp-history (delete (car regexp-history)
413                                           (cdr regexp-history)))
414            input)
415          current-prefix-arg))
416   (if (equal regexp "")
417       (error "Must pass non-empty regexp to `list-matching-lines'"))
418   (setq nlines (if nlines (prefix-numeric-value nlines)
419                  list-matching-lines-default-context-lines))
420   (let ((first t)
421         (dir default-directory)
422         (buffer (current-buffer))
423         (linenum 1)
424         (prevpos (point-min))
425         ;; The rest of this function is very different from FSF.
426         ;; Presumably that's due to Jamie's misfeature
427         (final-context-start (make-marker)))
428     (if (not list-matching-lines-whole-buffer)
429         (save-excursion
430           (beginning-of-line)
431           (setq linenum (1+ (count-lines (point-min) (point))))
432           (setq prevpos (point))))
433     (with-output-to-temp-buffer "*Occur*"
434       (save-excursion
435         (set-buffer standard-output)
436         (setq default-directory dir)
437         ;; We will insert the number of lines, and "lines", later.
438         ;; #### Needs fixing for I18N3
439         (let ((print-escape-newlines t))
440           (insert (format " matching %s in buffer %s.\n"
441                           regexp (buffer-name buffer))))
442         (occur-mode)
443         (setq occur-buffer buffer)
444         (setq occur-nlines nlines)
445         (setq occur-pos-list ()))
446       (if (eq buffer standard-output)
447           (goto-char (point-max)))
448       (save-excursion
449         (if list-matching-lines-whole-buffer
450             (beginning-of-buffer))
451         (message "Searching for %s ..." regexp)
452         ;; Find next match, but give up if prev match was at end of buffer.
453         (while (and (not (= prevpos (point-max)))
454                     (re-search-forward regexp nil t))
455           (goto-char (match-beginning 0))
456           (beginning-of-line)
457           (save-match-data
458             (setq linenum (+ linenum (count-lines prevpos (point)))))
459           (setq prevpos (point))
460           (goto-char (match-end 0))
461           (let* ((start (save-excursion
462                           (goto-char (match-beginning 0))
463                           (forward-line (if (< nlines 0) nlines (- nlines)))
464                           (point)))
465                  (end (save-excursion
466                         (goto-char (match-end 0))
467                         (if (> nlines 0)
468                             (forward-line (1+ nlines))
469                             (forward-line 1))
470                         (point)))
471                  (tag (format "%5d" linenum))
472                  (empty (make-string (length tag) ?\ ))
473                  tem)
474             (save-excursion
475               (setq tem (make-marker))
476               (set-marker tem (point))
477               (set-buffer standard-output)
478               (setq occur-pos-list (cons tem occur-pos-list))
479               (or first (zerop nlines)
480                   (insert "--------\n"))
481               (setq first nil)
482               (insert-buffer-substring buffer start end)
483               (set-marker final-context-start 
484                           (- (point) (- end (match-end 0))))
485               (backward-char (- end start))
486               (setq tem (if (< nlines 0) (- nlines) nlines))
487               (while (> tem 0)
488                 (insert empty ?:)
489                 (forward-line 1)
490                 (setq tem (1- tem)))
491               (let ((this-linenum linenum))
492                 (while (< (point) final-context-start)
493                   (if (null tag)
494                       (setq tag (format "%5d" this-linenum)))
495                   (insert tag ?:)
496 ;; FSFmacs -- we handle this using mode-motion-highlight-line, above.
497 ;                 (put-text-property (save-excursion
498 ;                                      (beginning-of-line)
499 ;                                      (point))
500 ;                                    (save-excursion
501 ;                                      (end-of-line)
502 ;                                      (point))
503 ;                                    'mouse-face 'highlight)
504                   (forward-line 1)
505                   (setq tag nil)
506                   (setq this-linenum (1+ this-linenum)))
507                 (while (<= (point) final-context-start)
508                   (insert empty ?:)
509                   (forward-line 1)
510                   (setq this-linenum (1+ this-linenum))))
511               (while (< tem nlines)
512                 (insert empty ?:)
513                 (forward-line 1)
514                 (setq tem (1+ tem)))
515               (goto-char (point-max)))
516             (forward-line 1)))
517         (set-buffer standard-output)
518         ;; Put positions in increasing order to go with buffer.
519         (setq occur-pos-list (nreverse occur-pos-list))
520         (goto-char (point-min))
521         (if (= (length occur-pos-list) 1)
522             (insert "1 line")
523           (insert (format "%d lines" (length occur-pos-list))))
524         (if (interactive-p)
525             (message "%d matching lines." (length occur-pos-list)))))))
526 \f
527 ;; It would be nice to use \\[...], but there is no reasonable way
528 ;; to make that display both SPC and Y.
529 (defconst query-replace-help
530   (purecopy
531    "Type Space or `y' to replace one match, Delete or `n' to skip to next,
532 RET or `q' to exit, Period to replace one match and exit,
533 Comma to replace but not move point immediately,
534 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
535 C-w to delete match and recursive edit,
536 C-l to clear the frame, redisplay, and offer same replacement again,
537 ! to replace all remaining matches with no more questions,
538 ^ to move point back to previous match."
539 )
540   "Help message while in query-replace")
541
542 (defvar query-replace-map nil
543   "Keymap that defines the responses to questions in `query-replace'.
544 The \"bindings\" in this map are not commands; they are answers.
545 The valid answers include `act', `skip', `act-and-show',
546 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
547 `automatic', `backup', `exit-prefix', and `help'.")
548
549 ;; Why does it seem that ever file has a different method of doing this?
550 (if query-replace-map
551     nil
552     (let ((map (make-sparse-keymap)))
553       (set-keymap-name map 'query-replace-map)
554       (define-key map " " 'act)
555       (define-key map "\d" 'skip)
556       (define-key map [delete] 'skip)
557       (define-key map [backspace] 'skip)
558       (define-key map "y" 'act)
559       (define-key map "n" 'skip)
560       (define-key map "Y" 'act)
561       (define-key map "N" 'skip)
562       (define-key map "," 'act-and-show)
563       (define-key map [escape] 'exit)
564       (define-key map "q" 'exit)
565       (define-key map [return] 'exit)
566       (define-key map "." 'act-and-exit)
567       (define-key map "\C-r" 'edit)
568       (define-key map "\C-w" 'delete-and-edit)
569       (define-key map "\C-l" 'recenter)
570       (define-key map "!" 'automatic)
571       (define-key map "^" 'backup)
572       (define-key map [(control h)] 'help)      ;; XEmacs change
573       (define-key map [f1] 'help)
574       (define-key map [help] 'help)
575       (define-key map "?" 'help)
576       (define-key map "\C-g" 'quit)
577       (define-key map "\C-]" 'quit)
578       ;FSFmacs (define-key map "\e" 'exit-prefix)
579       (define-key map [escape] 'exit-prefix)
580       
581       (setq query-replace-map map)))
582
583 ;; isearch-mode is dumped, so don't autoload.
584 ;(autoload 'isearch-highlight "isearch")
585
586 ;; XEmacs
587 (defun perform-replace-next-event (event)
588   (if isearch-highlight
589       (let ((aborted t))
590         (unwind-protect
591             (progn
592               (if (match-beginning 0)
593                   (isearch-highlight (match-beginning 0) (match-end 0)))
594               (next-command-event event)
595               (setq aborted nil))
596           (isearch-dehighlight aborted)))
597     (next-command-event event)))
598
599 (defun perform-replace (from-string replacements
600                         query-flag regexp-flag delimited-flag
601                         &optional repeat-count map)
602   "Subroutine of `query-replace'.  Its complexity handles interactive queries.
603 Don't use this in your own program unless you want to query and set the mark
604 just as `query-replace' does.  Instead, write a simple loop like this:
605   (while (re-search-forward \"foo[ \t]+bar\" nil t)
606     (replace-match \"foobar\" nil nil))
607 which will run faster and probably do exactly what you want."
608   (or map (setq map query-replace-map))
609   (let* ((event (make-event))
610          (nocasify (not (and case-fold-search case-replace
611                             (string-equal from-string
612                                           (downcase from-string)))))
613          (literal (not regexp-flag))
614          (search-function (if regexp-flag 're-search-forward 'search-forward))
615          (search-string from-string)
616          (real-match-data nil)          ; the match data for the current match
617          (next-replacement nil)
618          (replacement-index 0)
619          (keep-going t)
620          (stack nil)
621          (next-rotate-count 0)
622          (replace-count 0)
623          (lastrepl nil)                 ;Position after last match considered.
624          ;; If non-nil, it is marker saying where in the buffer to
625          ;; stop.
626          (limit nil)
627          (match-again t)
628          ;; XEmacs addition
629          (qr-case-fold-search
630           (if (and case-fold-search search-caps-disable-folding)
631               (isearch-no-upper-case-p search-string)
632             case-fold-search))
633          (message
634           (if query-flag
635               (substitute-command-keys
636                "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
637     ;; If the region is active, operate on region.
638     (when (region-active-p)
639       ;; Original Per Abrahamsen's code simply narrowed the region,
640       ;; thus providing a visual indication of the search boundary.
641       ;; Stallman, on the other hand, handles it like this.
642       (setq limit (copy-marker (region-end)))
643       (goto-char (region-beginning))
644       (zmacs-deactivate-region))
645     (if (stringp replacements)
646         (setq next-replacement replacements)
647       (or repeat-count (setq repeat-count 1)))
648     (if delimited-flag
649         (setq search-function 're-search-forward
650               search-string (concat "\\b"
651                                     (if regexp-flag from-string
652                                       (regexp-quote from-string))
653                                     "\\b")))
654     (push-mark)
655     (undo-boundary)
656     (unwind-protect
657         ;; Loop finding occurrences that perhaps should be replaced.
658         (while (and keep-going
659                     (not (eobp))
660                     (let ((case-fold-search qr-case-fold-search))
661                       (funcall search-function search-string limit t))
662                     ;; If the search string matches immediately after
663                     ;; the previous match, but it did not match there
664                     ;; before the replacement was done, ignore the match.
665                     (if (or (eq lastrepl (point))
666                             (and regexp-flag
667                                  (eq lastrepl (match-beginning 0))
668                                  (not match-again)))
669                         (if (eobp)
670                             nil
671                           ;; Don't replace the null string 
672                           ;; right after end of previous replacement.
673                           (forward-char 1)
674                           (let ((case-fold-search qr-case-fold-search))
675                             (funcall search-function search-string limit t)))
676                       t))
677
678           ;; Save the data associated with the real match.
679           (setq real-match-data (match-data))
680
681           ;; Before we make the replacement, decide whether the search string
682           ;; can match again just after this match.
683           (if regexp-flag
684               (progn 
685                 (setq match-again (looking-at search-string))
686                 ;; XEmacs addition
687                 (store-match-data real-match-data)))
688           ;; If time for a change, advance to next replacement string.
689           (if (and (listp replacements)
690                    (= next-rotate-count replace-count))
691               (progn
692                 (setq next-rotate-count
693                       (+ next-rotate-count repeat-count))
694                 (setq next-replacement (nth replacement-index replacements))
695                 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
696           (if (not query-flag)
697               (progn
698                 (store-match-data real-match-data)
699                 (replace-match next-replacement nocasify literal)
700                 (setq replace-count (1+ replace-count)))
701             (undo-boundary)
702             (let ((help-form
703                    '(concat (format "Query replacing %s%s with %s.\n\n"
704                                     (if regexp-flag (gettext "regexp ") "")
705                                     from-string next-replacement)
706                             (substitute-command-keys query-replace-help)))
707                   done replaced def)
708               ;; Loop reading commands until one of them sets done,
709               ;; which means it has finished handling this occurrence.
710               (while (not done)
711                 ;; Don't fill up the message log
712                 ;; with a bunch of identical messages.
713                 ;; XEmacs change
714                 (display-message 'prompt
715                                  (format message from-string next-replacement))
716                 (perform-replace-next-event event)
717                 (setq def (lookup-key map (vector event)))
718                 ;; Restore the match data while we process the command.
719                 (store-match-data real-match-data)
720                 (cond ((eq def 'help)
721                        (with-output-to-temp-buffer (gettext "*Help*")
722                          (princ (concat
723                                  (format "Query replacing %s%s with %s.\n\n"
724                                          (if regexp-flag "regexp " "")
725                                          from-string next-replacement)
726                                  (substitute-command-keys
727                                   query-replace-help)))
728                          (save-excursion
729                            (set-buffer standard-output)
730                            (help-mode))))
731                       ((eq def 'exit)
732                        (setq keep-going nil)
733                        (setq done t))
734                       ((eq def 'backup)
735                        (if stack
736                            (let ((elt (car stack)))
737                              (goto-char (car elt))
738                              (setq replaced (eq t (cdr elt)))
739                              (or replaced
740                                  (store-match-data (cdr elt)))
741                              (setq stack (cdr stack)))
742                          (message "No previous match")
743                          (ding 'no-terminate)
744                          (sit-for 1)))
745                       ((eq def 'act)
746                        (or replaced
747                            (replace-match next-replacement nocasify literal))
748                        (setq done t replaced t))
749                       ((eq def 'act-and-exit)
750                        (or replaced
751                            (replace-match next-replacement nocasify literal))
752                        (setq keep-going nil)
753                        (setq done t replaced t))
754                       ((eq def 'act-and-show)
755                        (if (not replaced)
756                            (progn
757                              (replace-match next-replacement nocasify literal)
758                              (store-match-data nil)
759                              (setq replaced t))))
760                       ((eq def 'automatic)
761                        (or replaced
762                            (replace-match next-replacement nocasify literal))
763                        (setq done t query-flag nil replaced t))
764                       ((eq def 'skip)
765                        (setq done t))
766                       ((eq def 'recenter)
767                        (recenter nil))
768                       ((eq def 'edit)
769                        (store-match-data
770                         (prog1 (match-data)
771                           (save-excursion (recursive-edit))))
772                        ;; Before we make the replacement,
773                        ;; decide whether the search string
774                        ;; can match again just after this match.
775                        (if regexp-flag
776                            (setq match-again (looking-at search-string))))
777                       ((eq def 'delete-and-edit)
778                        (delete-region (match-beginning 0) (match-end 0))
779                        (store-match-data (prog1 (match-data)
780                                            (save-excursion (recursive-edit))))
781                        (setq replaced t))
782                       ;; Note: we do not need to treat `exit-prefix'
783                       ;; specially here, since we reread
784                       ;; any unrecognized character.
785                       (t
786                        (setq this-command 'mode-exited)
787                        (setq keep-going nil)
788                        (setq unread-command-events
789                              (cons event unread-command-events))
790                        (setq done t))))
791               ;; Record previous position for ^ when we move on.
792               ;; Change markers to numbers in the match data
793               ;; since lots of markers slow down editing.
794               (setq stack
795                     (cons (cons (point)
796                                 (or replaced
797                                     (match-data t)))
798                           stack))
799               (if replaced (setq replace-count (1+ replace-count)))))
800           (setq lastrepl (point)))
801       ;; Useless in XEmacs.  We handle (de)highlighting through
802       ;; perform-replace-next-event.
803       ;(replace-dehighlight)
804       )
805     (or unread-command-events
806         (message "Replaced %d occurrence%s"
807                  replace-count
808                  (if (= replace-count 1) "" "s")))
809     (and keep-going stack)))
810
811 ;; FSFmacs code: someone should port it.
812
813 ;(defvar query-replace-highlight nil
814 ;  "*Non-nil means to highlight words during query replacement.")
815
816 ;(defvar replace-overlay nil)
817
818 ;(defun replace-dehighlight ()
819 ;  (and replace-overlay
820 ;       (progn
821 ;        (delete-overlay replace-overlay)
822 ;        (setq replace-overlay nil))))
823
824 ;(defun replace-highlight (start end)
825 ;  (and query-replace-highlight
826 ;       (progn
827 ;        (or replace-overlay
828 ;            (progn
829 ;              (setq replace-overlay (make-overlay start end))
830 ;              (overlay-put replace-overlay 'face
831 ;                           (if (internal-find-face 'query-replace)
832 ;                               'query-replace 'region))))
833 ;        (move-overlay replace-overlay start end (current-buffer)))))
834
835 (defun match-string (num &optional string)
836   "Return string of text matched by last search.
837 NUM specifies which parenthesized expression in the last regexp.
838  Value is nil if NUMth pair didn't match, or there were less than NUM pairs.
839 Zero means the entire text matched by the whole regexp or whole string.
840 STRING should be given if the last search was by `string-match' on STRING."
841   (if (match-beginning num)
842       (if string
843           (substring string (match-beginning num) (match-end num))
844         (buffer-substring (match-beginning num) (match-end num)))))
845
846 (defmacro save-match-data (&rest body)
847   "Execute BODY forms, restoring the global value of the match data."
848   (let ((original (make-symbol "match-data")))
849     (list 'let (list (list original '(match-data)))
850           (list 'unwind-protect
851                 (cons 'progn body)
852                 (list 'store-match-data original)))))
853
854 ;;; replace.el ends here