1 ;;; replace.el --- replace commands for Emacs.
3 ;; Copyright (C) 1985, 86, 87, 92, 94, 96, 1997 Free Software Foundation, Inc.
5 ;; This file is part of GNU Emacs.
7 ;; GNU Emacs is free software; you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;; GNU General Public License for more details.
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with GNU Emacs; see the file COPYING. If not, write to the
19 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 ;; Boston, MA 02111-1307, USA.
24 ;; This package supplies the string and regular-expression replace functions
25 ;; documented in the Emacs user's manual.
29 (defcustom case-replace t
30 "*Non-nil means query-replace should preserve case in replacements."
34 (defvar query-replace-history nil
)
36 (defvar query-replace-interactive nil
37 "Non-nil means `query-replace' uses the last search string.
38 That becomes the \"string to replace\".")
40 (defcustom query-replace-from-history-variable
'query-replace-history
41 "History list to use for the FROM argument of query-replace commands.
42 The value of this variable should be a symbol; that symbol
43 is used as a variable to hold a history list for the strings
44 or patterns to be replaced."
49 (defcustom query-replace-to-history-variable
'query-replace-history
50 "History list to use for the TO argument of query-replace commands.
51 The value of this variable should be a symbol; that symbol
52 is used as a variable to hold a history list for replacement
58 (defun query-replace-read-args (string regexp-flag
)
60 (if query-replace-interactive
61 (setq from
(car (if regexp-flag regexp-search-ring search-ring
)))
62 (setq from
(read-from-minibuffer (format "%s: " string
)
64 query-replace-from-history-variable
66 (setq to
(read-from-minibuffer (format "%s %s with: " string from
)
68 query-replace-to-history-variable from t
))
69 (list from to current-prefix-arg
)))
71 (defun query-replace (from-string to-string
&optional arg
)
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.
76 In Transient Mark mode, if the mark is active, operate on the contents
77 of the region. Otherwise, operate from point to the end of the buffer.
79 If `query-replace-interactive' is non-nil, the last incremental search
80 string is used as FROM-STRING--you don't have to specify it with the
83 Preserves case in each replacement if `case-replace' and `case-fold-search'
84 are non-nil and FROM-STRING has no uppercase letters.
85 \(Preserving case means that if the string matched is all caps, or capitalized,
86 then its replacement is upcased or capitalized.)
88 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
89 only matches surrounded by word boundaries.
91 To customize possible responses, change the \"bindings\" in `query-replace-map'."
92 (interactive (query-replace-read-args "Query replace" nil
))
93 (perform-replace from-string to-string t nil arg
))
95 (define-key esc-map
"%" 'query-replace
)
97 (defun query-replace-regexp (regexp to-string
&optional arg
)
98 "Replace some things after point matching REGEXP with TO-STRING.
99 As each match is found, the user must type a character saying
100 what to do with it. For directions, type \\[help-command] at that time.
102 In Transient Mark mode, if the mark is active, operate on the contents
103 of the region. Otherwise, operate from point to the end of the buffer.
105 If `query-replace-interactive' is non-nil, the last incremental search
106 regexp is used as REGEXP--you don't have to specify it with the
109 Preserves case in each replacement if `case-replace' and `case-fold-search'
110 are non-nil and REGEXP has no uppercase letters.
111 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
112 only matches surrounded by word boundaries.
113 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
114 and `\\=\\N' (where N is a digit) stands for
115 whatever what matched the Nth `\\(...\\)' in REGEXP."
116 (interactive (query-replace-read-args "Query replace regexp" t
))
117 (perform-replace regexp to-string t t arg
))
119 (defun map-query-replace-regexp (regexp to-strings
&optional arg
)
120 "Replace some matches for REGEXP with various strings, in rotation.
121 The second argument TO-STRINGS contains the replacement strings, separated
122 by spaces. This command works like `query-replace-regexp' except
123 that each successive replacement uses the next successive replacement string,
124 wrapping around from the last such string to the first.
126 In Transient Mark mode, if the mark is active, operate on the contents
127 of the region. Otherwise, operate from point to the end of the buffer.
129 Non-interactively, TO-STRINGS may be a list of replacement strings.
131 If `query-replace-interactive' is non-nil, the last incremental search
132 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
134 A prefix argument N says to use each replacement string N times
135 before rotating to the next."
138 (setq from
(if query-replace-interactive
139 (car regexp-search-ring
)
140 (read-from-minibuffer "Map query replace (regexp): "
142 'query-replace-history nil t
)))
143 (setq to
(read-from-minibuffer
144 (format "Query replace %s with (space-separated strings): "
147 'query-replace-history from t
))
148 (list from to current-prefix-arg
)))
150 (if (listp to-strings
)
151 (setq replacements to-strings
)
152 (while (/= (length to-strings
) 0)
153 (if (string-match " " to-strings
)
156 (list (substring to-strings
0
157 (string-match " " to-strings
))))
158 to-strings
(substring to-strings
159 (1+ (string-match " " to-strings
))))
160 (setq replacements
(append replacements
(list to-strings
))
162 (perform-replace regexp replacements t t nil arg
)))
164 (defun replace-string (from-string to-string
&optional delimited
)
165 "Replace occurrences of FROM-STRING with TO-STRING.
166 Preserve case in each match if `case-replace' and `case-fold-search'
167 are non-nil and FROM-STRING has no uppercase letters.
168 \(Preserving case means that if the string matched is all caps, or capitalized,
169 then its replacement is upcased or capitalized.)
171 In Transient Mark mode, if the mark is active, operate on the contents
172 of the region. Otherwise, operate from point to the end of the buffer.
174 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
175 only matches surrounded by word boundaries.
177 If `query-replace-interactive' is non-nil, the last incremental search
178 string is used as FROM-STRING--you don't have to specify it with the
181 This function is usually the wrong thing to use in a Lisp program.
182 What you probably want is a loop like this:
183 (while (search-forward FROM-STRING nil t)
184 (replace-match TO-STRING nil t))
185 which will run faster and will not set the mark or print anything.
186 \(You may need a more complex loop if FROM-STRING can match the null string
187 and TO-STRING is also null.)"
188 (interactive (query-replace-read-args "Replace string" nil
))
189 (perform-replace from-string to-string nil nil delimited
))
191 (defun replace-regexp (regexp to-string
&optional delimited
)
192 "Replace things after point matching REGEXP with TO-STRING.
193 Preserve case in each match if `case-replace' and `case-fold-search'
194 are non-nil and REGEXP has no uppercase letters.
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.
201 In Transient Mark mode, if the mark is active, operate on the contents
202 of the region. Otherwise, operate from point to the end of the buffer.
204 If `query-replace-interactive' is non-nil, the last incremental search
205 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
207 This function is usually the wrong thing to use in a Lisp program.
208 What you probably want is a loop like this:
209 (while (re-search-forward REGEXP nil t)
210 (replace-match TO-STRING nil nil))
211 which will run faster and will not set the mark or print anything."
212 (interactive (query-replace-read-args "Replace regexp" t
))
213 (perform-replace regexp to-string nil t delimited
))
215 (defvar regexp-history nil
216 "History list for some commands that read regular expressions.")
218 (defalias 'delete-non-matching-lines
'keep-lines
)
219 (defun keep-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 nil t
)))
227 (or (bolp) (forward-line 1))
228 (let ((start (point)))
230 ;; Start is first char not preserved by previous match.
231 (if (not (re-search-forward regexp nil
'move
))
232 (delete-region start
(point-max))
233 (let ((end (save-excursion (goto-char (match-beginning 0))
236 ;; Now end is first char preserved by the new match.
238 (delete-region start end
))))
239 (setq start
(save-excursion (forward-line 1)
241 ;; If the match was empty, avoid matching again at same place.
242 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
243 (forward-char 1))))))
245 (defalias 'delete-matching-lines
'flush-lines
)
246 (defun flush-lines (regexp)
247 "Delete lines containing matches for REGEXP.
248 If a match is split across lines, all the lines it lies in are deleted.
249 Applies to lines after point."
250 (interactive (list (read-from-minibuffer
251 "Flush lines (containing match for regexp): "
252 nil nil nil
'regexp-history nil t
)))
254 (while (and (not (eobp))
255 (re-search-forward regexp nil t
))
256 (delete-region (save-excursion (goto-char (match-beginning 0))
259 (progn (forward-line 1) (point))))))
261 (defalias 'count-matches
'how-many
)
262 (defun how-many (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 nil t
)))
267 (let ((count 0) opoint
)
269 (while (and (not (eobp))
270 (progn (setq opoint
(point))
271 (re-search-forward regexp nil t
)))
272 (if (= opoint
(point))
274 (setq count
(1+ count
))))
275 (message "%d occurrences" count
))))
277 (defvar occur-mode-map
())
280 (setq occur-mode-map
(make-sparse-keymap))
281 (define-key occur-mode-map
[mouse-2
] 'occur-mode-mouse-goto
)
282 (define-key occur-mode-map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
283 (define-key occur-mode-map
"\C-m" 'occur-mode-goto-occurrence
)
284 (define-key occur-mode-map
"\M-n" 'occur-next
)
285 (define-key occur-mode-map
"\M-p" 'occur-prev
)
286 (define-key occur-mode-map
"g" 'revert-buffer
))
289 (defvar occur-buffer nil
290 "Name of buffer for last occur.")
293 (defvar occur-nlines nil
294 "Number of lines of context to show around matching line.")
296 (defvar occur-command-arguments nil
297 "Arguments that were given to `occur' when it made this buffer.")
299 (put 'occur-mode
'mode-class
'special
)
302 "Major mode for output from \\[occur].
303 \\<occur-mode-map>Move point to one of the items in this buffer, then use
304 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
305 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
308 (kill-all-local-variables)
309 (use-local-map occur-mode-map
)
310 (setq major-mode
'occur-mode
)
311 (setq mode-name
"Occur")
312 (make-local-variable 'revert-buffer-function
)
313 (setq revert-buffer-function
'occur-revert-function
)
314 (make-local-variable 'occur-buffer
)
315 (make-local-variable 'occur-nlines
)
316 (make-local-variable 'occur-command-arguments
)
317 (run-hooks 'occur-mode-hook
))
319 ;; Handle revert-buffer for *Occur* buffers.
320 (defun occur-revert-function (ignore1 ignore2
)
321 (let ((args occur-command-arguments
))
323 (set-buffer occur-buffer
)
324 (apply 'occur args
))))
326 (defun occur-mode-mouse-goto (event)
327 "In Occur mode, go to the occurrence whose line you click on."
331 (set-buffer (window-buffer (posn-window (event-end event
))))
333 (goto-char (posn-point (event-end event
)))
334 (setq pos
(occur-mode-find-occurrence))
335 (setq buffer occur-buffer
)))
336 (pop-to-buffer buffer
)
337 (goto-char (marker-position pos
))))
339 (defun occur-mode-find-occurrence ()
340 (if (or (null occur-buffer
)
341 (null (buffer-name occur-buffer
)))
343 (setq occur-buffer nil
)
344 (error "Buffer in which occurrences were found is deleted")))
345 (let ((pos (get-text-property (point) 'occur
)))
347 (error "No occurrence on this line")
350 (defun occur-mode-goto-occurrence ()
351 "Go to the occurrence the current line describes."
353 (let ((pos (occur-mode-find-occurrence)))
354 (pop-to-buffer occur-buffer
)
355 (goto-char (marker-position pos
))))
357 (defun occur-next (&optional n
)
358 "Move to the Nth (default 1) next match in the *Occur* buffer."
360 (if (not n
) (setq n
1))
363 (if (get-text-property (point) 'occur-point
)
365 (setq r
(next-single-property-change (point) 'occur-point
))
368 (error "no more matches"))
373 (defun occur-prev (&optional n
)
374 "Move to the Nth (default 1) previous match in the *Occur* buffer."
376 (if (not n
) (setq n
1))
380 (setq r
(get-text-property (point) 'occur-point
))
381 (if r
(forward-char -
1))
383 (setq r
(previous-single-property-change (point) 'occur-point
))
386 (error "no earlier matches"))
390 (defcustom list-matching-lines-default-context-lines
0
391 "*Default number of context lines to include around a `list-matching-lines'
392 match. A negative number means to include that many lines before the match.
393 A positive number means to include that many lines both before and after."
397 (defalias 'list-matching-lines
'occur
)
399 (defvar list-matching-lines-face
'bold
400 "*Face used by M-x list-matching-lines to show the text that matches.
401 If the value is nil, don't highlight the matching portions specially.")
403 (defun occur (regexp &optional nlines
)
404 "Show all lines in the current buffer containing a match for REGEXP.
406 If a match spreads across multiple lines, all those lines are shown.
408 Each line is displayed with NLINES lines before and after, or -NLINES
409 before if NLINES is negative.
410 NLINES defaults to `list-matching-lines-default-context-lines'.
411 Interactively it is the prefix arg.
413 The lines are shown in a buffer named `*Occur*'.
414 It serves as a menu to find any of the occurrences in this buffer.
415 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
417 If REGEXP contains upper case characters (excluding those preceded by `\\'),
418 the matching is case-sensitive."
420 (list (let* ((default (car regexp-history
))
422 (read-from-minibuffer
424 (format "List lines matching regexp (default `%s'): "
426 "List lines matching regexp: ")
427 nil nil nil
'regexp-history default t
)))
428 (and (equal input
"") default
429 (setq input default
))
432 (let ((nlines (if nlines
433 (prefix-numeric-value nlines
)
434 list-matching-lines-default-context-lines
))
436 ;;flag to prevent printing separator for first match
437 (occur-num-matches 0)
438 (buffer (current-buffer))
439 (dir default-directory
)
442 ;;position of most recent match
444 (case-fold-search (and case-fold-search
445 (isearch-no-upper-case-p regexp t
)))
447 ;; Marker to the start of context immediately following
448 ;; the matched text in *Occur*.
451 ;;; (beginning-of-line)
452 ;;; (setq linenum (1+ (count-lines (point-min) (point))))
453 ;;; (setq prevpos (point)))
455 (goto-char (point-min))
456 ;; Check first whether there are any matches at all.
457 (if (not (re-search-forward regexp nil t
))
458 (message "No matches for `%s'" regexp
)
459 ;; Back up, so the search loop below will find the first match.
460 (goto-char (match-beginning 0))
461 (with-output-to-temp-buffer "*Occur*"
463 (set-buffer standard-output
)
464 (setq default-directory dir
)
465 ;; We will insert the number of lines, and "lines", later.
466 (insert " matching ")
467 (let ((print-escape-newlines t
))
469 (insert " in buffer " (buffer-name buffer
) ?. ?
\n)
471 (setq occur-buffer buffer
)
472 (setq occur-nlines nlines
)
473 (setq occur-command-arguments
474 (list regexp nlines
)))
475 (if (eq buffer standard-output
)
476 (goto-char (point-max)))
478 ;; Find next match, but give up if prev match was at end of buffer.
479 (while (and (not (= prevpos
(point-max)))
480 (re-search-forward regexp nil t
))
481 (goto-char (match-beginning 0))
484 (setq linenum
(+ linenum
(count-lines prevpos
(point)))))
485 (setq prevpos
(point))
486 (goto-char (match-end 0))
488 ;;start point of text in source buffer to be put
491 (goto-char (match-beginning 0))
492 (forward-line (if (< nlines
0)
497 ;; end point of text in source buffer to be put
500 (goto-char (match-end 0))
502 (forward-line (1+ nlines
))
506 ;; Amount of context before matching text
507 (- (match-beginning 0) start
))
509 ;; Length of matching text
510 (- (match-end 0) (match-beginning 0)))
511 (tag (format "%5d" linenum
))
512 (empty (make-string (length tag
) ?\
))
515 ;; Number of lines of context to show for current match.
517 ;; Marker pointing to end of match in source buffer.
519 ;; Marker pointing to start of text for one
523 ;; Marker pointing to end of text for one match
528 (setq occur-marker
(make-marker))
529 (set-marker occur-marker
(point))
530 (set-buffer standard-output
)
531 (setq occur-num-matches
(1+ occur-num-matches
))
532 (or first
(zerop nlines
)
533 (insert "--------\n"))
536 ;; Insert matching text including context lines from
537 ;; source buffer into *Occur*
538 (set-marker text-beg
(point))
539 (setq insertion-start
(point))
540 (insert-buffer-substring buffer start end
)
541 (or (and (/= (+ start match-beg
) end
)
542 (with-current-buffer buffer
543 (eq (char-before end
) ?
\n)))
545 (set-marker final-context-start
546 (+ (- (point) (- end
(match-end 0)))
550 (goto-char (match-end 0))
554 (set-marker text-end
(point))
556 ;; Highlight text that was matched.
557 (if list-matching-lines-face
559 (+ (marker-position text-beg
) match-beg
)
560 (+ (marker-position text-beg
) match-beg match-len
)
561 'face list-matching-lines-face
))
563 ;; `occur-point' property is used by occur-next and
564 ;; occur-prev to move between matching lines.
566 (+ (marker-position text-beg
) match-beg match-len
)
567 (+ (marker-position text-beg
) match-beg match-len
1)
570 ;; Now go back to the start of the matching text
571 ;; adding the space and colon to the start of each line.
572 (goto-char insertion-start
)
573 ;; Insert space and colon for lines of context before match.
574 (setq tem
(if (< linenum nlines
)
582 ;; Insert line number and colon for the lines of
584 (let ((this-linenum linenum
))
585 (while (< (point) final-context-start
)
587 (setq tag
(format "%5d" this-linenum
)))
591 (setq this-linenum
(1+ this-linenum
)))
592 (while (and (not (eobp)) (<= (point) final-context-start
))
595 (setq this-linenum
(1+ this-linenum
))))
597 ;; Insert space and colon for lines of context after match.
598 (while (and (< (point) (point-max)) (< tem nlines
))
603 ;; Add text properties. The `occur' prop is used to
604 ;; store the marker of the matching text in the
606 (put-text-property (marker-position text-beg
)
607 (- (marker-position text-end
) 1)
608 'mouse-face
'highlight
)
609 (put-text-property (marker-position text-beg
)
610 (marker-position text-end
)
612 (goto-char (point-max)))
614 (set-buffer standard-output
)
615 ;; Go back to top of *Occur* and finish off by printing the
616 ;; number of matching lines.
617 (goto-char (point-min))
618 (let ((message-string
619 (if (= occur-num-matches
1)
621 (format "%d lines" occur-num-matches
))))
622 (insert message-string
)
624 (message "%s matched" message-string
)))))))))
626 ;; It would be nice to use \\[...], but there is no reasonable way
627 ;; to make that display both SPC and Y.
628 (defconst query-replace-help
629 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
630 RET or `q' to exit, Period to replace one match and exit,
631 Comma to replace but not move point immediately,
632 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
633 C-w to delete match and recursive edit,
634 C-l to clear the screen, redisplay, and offer same replacement again,
635 ! to replace all remaining matches with no more questions,
636 ^ to move point back to previous match."
637 "Help message while in query-replace")
639 (defvar query-replace-map
(make-sparse-keymap)
640 "Keymap that defines the responses to questions in `query-replace'.
641 The \"bindings\" in this map are not commands; they are answers.
642 The valid answers include `act', `skip', `act-and-show',
643 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
644 `automatic', `backup', `exit-prefix', and `help'.")
646 (define-key query-replace-map
" " 'act
)
647 (define-key query-replace-map
"\d" 'skip
)
648 (define-key query-replace-map
[delete] 'skip)
649 (define-key query-replace-map [backspace] 'skip)
650 (define-key query-replace-map "y" 'act)
651 (define-key query-replace-map "n" 'skip)
652 (define-key query-replace-map "Y" 'act)
653 (define-key query-replace-map "N" 'skip)
654 (define-key query-replace-map "," 'act-and-show)
655 (define-key query-replace-map "q" 'exit)
656 (define-key query-replace-map "\r" 'exit)
657 (define-key query-replace-map [return] 'exit)
658 (define-key query-replace-map "." 'act-and-exit)
659 (define-key query-replace-map "\C-r" 'edit)
660 (define-key query-replace-map "\C-w" 'delete-and-edit)
661 (define-key query-replace-map "\C-l" 'recenter)
662 (define-key query-replace-map "!" 'automatic)
663 (define-key query-replace-map "^" 'backup)
664 (define-key query-replace-map "\C-h" 'help)
665 (define-key query-replace-map [f1] 'help)
666 (define-key query-replace-map [help] 'help)
667 (define-key query-replace-map "?" 'help)
668 (define-key query-replace-map "\C-g" 'quit)
669 (define-key query-replace-map "\C-]" 'quit)
670 (define-key query-replace-map "\e" 'exit-prefix)
671 (define-key query-replace-map [escape] 'exit-prefix)
673 (defun perform-replace (from-string replacements
674 query-flag regexp-flag delimited-flag
675 &optional repeat-count map)
676 "Subroutine of `query-replace'. Its complexity handles interactive queries.
677 Don't use this in your own program unless you want to query and set the mark
678 just as `query-replace' does. Instead, write a simple loop like this:
679 (while (re-search-forward \"foo[ \t]+bar\" nil t)
680 (replace-match \"foobar\" nil nil))
681 which will run faster and probably do exactly what you want."
682 (or map (setq map query-replace-map))
683 (and query-flag minibuffer-auto-raise
684 (raise-frame (window-frame (minibuffer-window))))
685 (let ((nocasify (not (and case-fold-search case-replace
686 (string-equal from-string
687 (downcase from-string)))))
688 (literal (not regexp-flag))
689 (search-function (if regexp-flag 're-search-forward 'search-forward))
690 (search-string from-string)
691 (real-match-data nil) ; the match data for the current match
692 (next-replacement nil)
693 (replacement-index 0)
696 (next-rotate-count 0)
700 ;; If non-nil, it is marker saying where in the buffer to stop.
703 ;; Data for the next match. If a cons, it has the same format as
704 ;; (match-data); otherwise it is t if a match is possible at point.
709 (substitute-command-keys
710 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
712 ;; If region is active, in Transient Mark mode, operate on region.
713 (if (and transient-mark-mode mark-active)
715 (setq limit (copy-marker (region-end)))
716 (goto-char (region-beginning))
718 (if (stringp replacements)
719 (setq next-replacement replacements)
720 (or repeat-count (setq repeat-count 1)))
722 (setq search-function 're-search-forward
723 search-string (concat "\\b"
724 (if regexp-flag from-string
725 (regexp-quote from-string))
730 ;; Loop finding occurrences that perhaps should be replaced.
731 (while (and keep-going
733 ;; Use the next match if it is already known;
734 ;; otherwise, search for a match after moving forward
735 ;; one char if progress is required.
736 (setq real-match-data
737 (if (consp match-again)
738 (progn (goto-char (nth 1 match-again))
744 (funcall search-function search-string limit t)
745 ;; For speed, use only integers and
746 ;; reuse the list used last time.
747 (match-data t real-match-data)))))
749 ;; Record whether the match is nonempty, to avoid an infinite loop
750 ;; repeatedly matching the same empty string.
752 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
754 ;; If the match is empty, record that the next one can't be adjacent.
755 ;; Otherwise, if matching a regular expression, do the next
756 ;; match now, since the replacement for this match may
757 ;; affect whether the next match is adjacent to this one.
760 (or (not regexp-flag)
761 (and (looking-at search-string)
764 ;; If time for a change, advance to next replacement string.
765 (if (and (listp replacements)
766 (= next-rotate-count replace-count))
768 (setq next-rotate-count
769 (+ next-rotate-count repeat-count))
770 (setq next-replacement (nth replacement-index replacements))
771 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
774 (set-match-data real-match-data)
775 (replace-match next-replacement nocasify literal)
776 (setq replace-count (1+ replace-count)))
778 (let (done replaced key def)
779 ;; Loop reading commands until one of them sets done,
780 ;; which means it has finished handling this occurrence.
782 (set-match-data real-match-data)
783 (replace-highlight (match-beginning 0) (match-end 0))
784 ;; Bind message-log-max so we don't fill up the message log
785 ;; with a bunch of identical messages.
786 (let ((message-log-max nil))
787 (message message from-string next-replacement))
788 (setq key (read-event))
789 ;; Necessary in case something happens during read-event
790 ;; that clobbers the match data.
791 (set-match-data real-match-data)
792 (setq key (vector key))
793 (setq def (lookup-key map key))
794 ;; Restore the match data while we process the command.
795 (cond ((eq def 'help)
796 (with-output-to-temp-buffer "*Help*"
798 (concat "Query replacing "
799 (if regexp-flag "regexp " "")
801 next-replacement ".\n\n"
802 (substitute-command-keys
803 query-replace-help)))
805 (set-buffer standard-output)
808 (setq keep-going nil)
812 (let ((elt (car stack)))
813 (goto-char (car elt))
814 (setq replaced (eq t (cdr elt)))
816 (set-match-data (cdr elt)))
817 (setq stack (cdr stack)))
818 (message "No previous match")
824 (replace-match next-replacement nocasify literal)
825 (setq replace-count (1+ replace-count))))
826 (setq done t replaced t))
827 ((eq def 'act-and-exit)
830 (replace-match next-replacement nocasify literal)
831 (setq replace-count (1+ replace-count))))
832 (setq keep-going nil)
833 (setq done t replaced t))
834 ((eq def 'act-and-show)
837 (replace-match next-replacement nocasify literal)
838 (setq replace-count (1+ replace-count))
843 (replace-match next-replacement nocasify literal)
844 (setq replace-count (1+ replace-count))))
845 (setq done t query-flag nil replaced t))
851 (goto-char (match-beginning 0))
852 (funcall search-function search-string limit t)
853 (setq real-match-data (match-data))
854 (save-excursion (recursive-edit))
855 (set-match-data real-match-data)
856 ;; Before we make the replacement,
857 ;; decide whether the search string
858 ;; can match again just after this match.
859 (if (and regexp-flag nonempty-match)
860 (setq match-again (and (looking-at search-string)
862 ((eq def 'delete-and-edit)
863 (delete-region (match-beginning 0) (match-end 0))
866 (save-excursion (recursive-edit))))
868 ;; Note: we do not need to treat `exit-prefix'
869 ;; specially here, since we reread
870 ;; any unrecognized character.
872 (setq this-command 'mode-exited)
873 (setq keep-going nil)
874 (setq unread-command-events
875 (append (listify-key-sequence key)
876 unread-command-events))
878 ;; Record previous position for ^ when we move on.
879 ;; Change markers to numbers in the match data
880 ;; since lots of markers slow down editing.
883 (or replaced (match-data t)))
885 (replace-dehighlight))
886 (or unread-command-events
887 (message "Replaced %d occurrence%s"
889 (if (= replace-count 1) "" "s")))
890 (and keep-going stack)))
892 (defcustom query-replace-highlight t
893 "*Non-nil means to highlight words during query replacement."
897 (defvar replace-overlay nil)
899 (defun replace-dehighlight ()
902 (delete-overlay replace-overlay)
903 (setq replace-overlay nil))))
905 (defun replace-highlight (start end)
906 (and query-replace-highlight
910 (setq replace-overlay (make-overlay start end))
911 (overlay-put replace-overlay 'face
912 (if (internal-find-face 'query-replace)
913 'query-replace 'region))))
914 (move-overlay replace-overlay start end (current-buffer)))))
916 ;;; replace.el ends here