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