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