]> code.delx.au - gnu-emacs/blob - lisp/replace.el
*** empty log message ***
[gnu-emacs] / lisp / replace.el
1 ;;; replace.el --- replace commands for Emacs
2
3 ;; Copyright (C) 1985, 86, 87, 92, 94, 96, 1997, 2000, 2001, 2002
4 ;; Free Software Foundation, Inc.
5
6 ;; Maintainer: FSF
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs 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 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs 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 GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; This package supplies the string and regular-expression replace functions
28 ;; documented in the Emacs user's manual.
29
30 ;;; Code:
31
32 (defcustom case-replace t
33 "*Non-nil means `query-replace' should preserve case in replacements."
34 :type 'boolean
35 :group 'matching)
36
37 (defvar query-replace-history nil)
38
39 (defvar query-replace-interactive nil
40 "Non-nil means `query-replace' uses the last search string.
41 That becomes the \"string to replace\".")
42
43 (defcustom query-replace-from-history-variable 'query-replace-history
44 "History list to use for the FROM argument of `query-replace' commands.
45 The value of this variable should be a symbol; that symbol
46 is used as a variable to hold a history list for the strings
47 or patterns to be replaced."
48 :group 'matching
49 :type 'symbol
50 :version "20.3")
51
52 (defcustom query-replace-to-history-variable 'query-replace-history
53 "History list to use for the TO argument of `query-replace' commands.
54 The value of this variable should be a symbol; that symbol
55 is used as a variable to hold a history list for replacement
56 strings or patterns."
57 :group 'matching
58 :type 'symbol
59 :version "20.3")
60
61 (defcustom query-replace-skip-read-only nil
62 "*Non-nil means `query-replace' and friends ignore read-only matches."
63 :type 'boolean
64 :group 'matching
65 :version "21.4")
66
67 (defun query-replace-read-args (string regexp-flag &optional noerror)
68 (unless noerror
69 (barf-if-buffer-read-only))
70 (let (from to)
71 (if query-replace-interactive
72 (setq from (car (if regexp-flag regexp-search-ring search-ring)))
73 (setq from (read-from-minibuffer (format "%s: " string)
74 nil nil nil
75 query-replace-from-history-variable
76 nil t))
77 ;; Warn if user types \n or \t, but don't reject the input.
78 (if (string-match "\\\\[nt]" from)
79 (let ((match (match-string 0 from)))
80 (cond
81 ((string= match "\\n")
82 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
83 ((string= match "\\t")
84 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
85 (sit-for 2))))
86
87 (setq to (read-from-minibuffer (format "%s %s with: " string from)
88 nil nil nil
89 query-replace-to-history-variable from t))
90 (list from to current-prefix-arg)))
91
92 (defun query-replace (from-string to-string &optional delimited start end)
93 "Replace some occurrences of FROM-STRING with TO-STRING.
94 As each match is found, the user must type a character saying
95 what to do with it. For directions, type \\[help-command] at that time.
96
97 In Transient Mark mode, if the mark is active, operate on the contents
98 of the region. Otherwise, operate from point to the end of the buffer.
99
100 If `query-replace-interactive' is non-nil, the last incremental search
101 string is used as FROM-STRING--you don't have to specify it with the
102 minibuffer.
103
104 Matching is independent of case if `case-fold-search' is non-nil and
105 FROM-STRING has no uppercase letters. Replacement transfers the case
106 pattern of the old text to the new text, if `case-replace' and
107 `case-fold-search' are non-nil and FROM-STRING has no uppercase
108 letters. \(Transferring the case pattern means that if the old text
109 matched is all caps, or capitalized, then its replacement is upcased
110 or capitalized.)
111
112 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
113 only matches surrounded by word boundaries.
114 Fourth and fifth arg START and END specify the region to operate on.
115
116 To customize possible responses, change the \"bindings\" in `query-replace-map'."
117 (interactive (let ((common
118 (query-replace-read-args "Query replace" nil)))
119 (list (nth 0 common) (nth 1 common) (nth 2 common)
120 ;; These are done separately here
121 ;; so that command-history will record these expressions
122 ;; rather than the values they had this time.
123 (if (and transient-mark-mode mark-active)
124 (region-beginning))
125 (if (and transient-mark-mode mark-active)
126 (region-end)))))
127 (perform-replace from-string to-string t nil delimited nil nil start end))
128
129 (define-key esc-map "%" 'query-replace)
130
131 (defun query-replace-regexp (regexp to-string &optional delimited start end)
132 "Replace some things after point matching REGEXP with TO-STRING.
133 As each match is found, the user must type a character saying
134 what to do with it. For directions, type \\[help-command] at that time.
135
136 In Transient Mark mode, if the mark is active, operate on the contents
137 of the region. Otherwise, operate from point to the end of the buffer.
138
139 If `query-replace-interactive' is non-nil, the last incremental search
140 regexp is used as REGEXP--you don't have to specify it with the
141 minibuffer.
142
143 Matching is independent of case if `case-fold-search' is non-nil and
144 REGEXP has no uppercase letters. Replacement transfers the case
145 pattern of the old text to the new text, if `case-replace' and
146 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
147 \(Transferring the case pattern means that if the old text matched is
148 all caps, or capitalized, then its replacement is upcased or
149 capitalized.)
150
151 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
152 only matches surrounded by word boundaries.
153 Fourth and fifth arg START and END specify the region to operate on.
154
155 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
156 and `\\=\\N' (where N is a digit) stands for
157 whatever what matched the Nth `\\(...\\)' in REGEXP."
158 (interactive
159 (let ((common
160 (query-replace-read-args "Query replace regexp" t)))
161 (list (nth 0 common) (nth 1 common) (nth 2 common)
162 ;; These are done separately here
163 ;; so that command-history will record these expressions
164 ;; rather than the values they had this time.
165 (if (and transient-mark-mode mark-active)
166 (region-beginning))
167 (if (and transient-mark-mode mark-active)
168 (region-end)))))
169
170 (perform-replace regexp to-string t t delimited nil nil start end))
171 (define-key esc-map [?\C-%] 'query-replace-regexp)
172
173 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
174 "Replace some things after point matching REGEXP with the result of TO-EXPR.
175 As each match is found, the user must type a character saying
176 what to do with it. For directions, type \\[help-command] at that time.
177
178 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
179 reference `replace-count' to get the number of replacements already made.
180 If the result of TO-EXPR is not a string, it is converted to one using
181 `prin1-to-string' with the NOESCAPE argument (which see).
182
183 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
184 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
185 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
186 Use `\\#&' or `\\#N' if you want a number instead of a string.
187
188 In Transient Mark mode, if the mark is active, operate on the contents
189 of the region. Otherwise, operate from point to the end of the buffer.
190
191 If `query-replace-interactive' is non-nil, the last incremental search
192 regexp is used as REGEXP--you don't have to specify it with the
193 minibuffer.
194
195 Preserves case in each replacement if `case-replace' and `case-fold-search'
196 are non-nil and REGEXP has no uppercase letters.
197
198 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
199 only matches that are surrounded by word boundaries.
200 Fourth and fifth arg START and END specify the region to operate on."
201 (interactive
202 (let (from to)
203 (if query-replace-interactive
204 (setq from (car regexp-search-ring))
205 (setq from (read-from-minibuffer "Query replace regexp: "
206 nil nil nil
207 query-replace-from-history-variable
208 nil t)))
209 (setq to (list (read-from-minibuffer
210 (format "Query replace regexp %s with eval: " from)
211 nil nil t query-replace-to-history-variable from t)))
212 ;; We make TO a list because replace-match-string-symbols requires one,
213 ;; and the user might enter a single token.
214 (replace-match-string-symbols to)
215 (list from (car to) current-prefix-arg
216 (if (and transient-mark-mode mark-active)
217 (region-beginning))
218 (if (and transient-mark-mode mark-active)
219 (region-end)))))
220 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
221 t t delimited nil nil start end))
222
223 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
224 "Replace some matches for REGEXP with various strings, in rotation.
225 The second argument TO-STRINGS contains the replacement strings,
226 separated by spaces. Third arg DELIMITED (prefix arg if interactive),
227 if non-nil, means replace only matches surrounded by word boundaries.
228 This command works like `query-replace-regexp' except that each
229 successive replacement uses the next successive replacement string,
230 wrapping around from the last such string to the first.
231
232 In Transient Mark mode, if the mark is active, operate on the contents
233 of the region. Otherwise, operate from point to the end of the buffer.
234
235 Non-interactively, TO-STRINGS may be a list of replacement strings.
236
237 If `query-replace-interactive' is non-nil, the last incremental search
238 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
239
240 A prefix argument N says to use each replacement string N times
241 before rotating to the next.
242 Fourth and fifth arg START and END specify the region to operate on."
243 (interactive
244 (let (from to)
245 (setq from (if query-replace-interactive
246 (car regexp-search-ring)
247 (read-from-minibuffer "Map query replace (regexp): "
248 nil nil nil
249 'query-replace-history nil t)))
250 (setq to (read-from-minibuffer
251 (format "Query replace %s with (space-separated strings): "
252 from)
253 nil nil nil
254 'query-replace-history from t))
255 (list from to current-prefix-arg
256 (if (and transient-mark-mode mark-active)
257 (region-beginning))
258 (if (and transient-mark-mode mark-active)
259 (region-end)))))
260 (let (replacements)
261 (if (listp to-strings)
262 (setq replacements to-strings)
263 (while (/= (length to-strings) 0)
264 (if (string-match " " to-strings)
265 (setq replacements
266 (append replacements
267 (list (substring to-strings 0
268 (string-match " " to-strings))))
269 to-strings (substring to-strings
270 (1+ (string-match " " to-strings))))
271 (setq replacements (append replacements (list to-strings))
272 to-strings ""))))
273 (perform-replace regexp replacements t t nil n nil start end)))
274
275 (defun replace-string (from-string to-string &optional delimited start end)
276 "Replace occurrences of FROM-STRING with TO-STRING.
277 Preserve case in each match if `case-replace' and `case-fold-search'
278 are non-nil and FROM-STRING has no uppercase letters.
279 \(Preserving case means that if the string matched is all caps, or capitalized,
280 then its replacement is upcased or capitalized.)
281
282 In Transient Mark mode, if the mark is active, operate on the contents
283 of the region. Otherwise, operate from point to the end of the buffer.
284
285 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
286 only matches surrounded by word boundaries.
287 Fourth and fifth arg START and END specify the region to operate on.
288
289 If `query-replace-interactive' is non-nil, the last incremental search
290 string is used as FROM-STRING--you don't have to specify it with the
291 minibuffer.
292
293 This function is usually the wrong thing to use in a Lisp program.
294 What you probably want is a loop like this:
295 (while (search-forward FROM-STRING nil t)
296 (replace-match TO-STRING nil t))
297 which will run faster and will not set the mark or print anything.
298 \(You may need a more complex loop if FROM-STRING can match the null string
299 and TO-STRING is also null.)"
300 (interactive
301 (let ((common
302 (query-replace-read-args "Replace string" nil)))
303 (list (nth 0 common) (nth 1 common) (nth 2 common)
304 (if (and transient-mark-mode mark-active)
305 (region-beginning))
306 (if (and transient-mark-mode mark-active)
307 (region-end)))))
308 (perform-replace from-string to-string nil nil delimited nil nil start end))
309
310 (defun replace-regexp (regexp to-string &optional delimited start end)
311 "Replace things after point matching REGEXP with TO-STRING.
312 Preserve case in each match if `case-replace' and `case-fold-search'
313 are non-nil and REGEXP has no uppercase letters.
314
315 In Transient Mark mode, if the mark is active, operate on the contents
316 of the region. Otherwise, operate from point to the end of the buffer.
317
318 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
319 only matches surrounded by word boundaries.
320 Fourth and fifth arg START and END specify the region to operate on.
321
322 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
323 and `\\=\\N' (where N is a digit) stands for
324 whatever what matched the Nth `\\(...\\)' in REGEXP.
325
326 If `query-replace-interactive' is non-nil, the last incremental search
327 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
328
329 This function is usually the wrong thing to use in a Lisp program.
330 What you probably want is a loop like this:
331 (while (re-search-forward REGEXP nil t)
332 (replace-match TO-STRING nil nil))
333 which will run faster and will not set the mark or print anything."
334 (interactive
335 (let ((common
336 (query-replace-read-args "Replace regexp" t)))
337 (list (nth 0 common) (nth 1 common) (nth 2 common)
338 (if (and transient-mark-mode mark-active)
339 (region-beginning))
340 (if (and transient-mark-mode mark-active)
341 (region-end)))))
342 (perform-replace regexp to-string nil t delimited nil nil start end))
343
344 \f
345 (defvar regexp-history nil
346 "History list for some commands that read regular expressions.")
347
348
349 (defalias 'delete-non-matching-lines 'keep-lines)
350 (defalias 'delete-matching-lines 'flush-lines)
351 (defalias 'count-matches 'how-many)
352
353
354 (defun keep-lines-read-args (prompt)
355 "Read arguments for `keep-lines' and friends.
356 Prompt for a regexp with PROMPT.
357 Value is a list, (REGEXP)."
358 (list (read-from-minibuffer prompt nil nil nil
359 'regexp-history nil t)))
360
361 (defun keep-lines (regexp &optional rstart rend)
362 "Delete all lines except those containing matches for REGEXP.
363 A match split across lines preserves all the lines it lies in.
364 Applies to all lines after point.
365
366 If REGEXP contains upper case characters (excluding those preceded by `\\'),
367 the matching is case-sensitive.
368
369 Second and third arg RSTART and REND specify the region to operate on.
370
371 Interactively, in Transient Mark mode when the mark is active, operate
372 on the contents of the region. Otherwise, operate from point to the
373 end of the buffer."
374
375 (interactive
376 (progn
377 (barf-if-buffer-read-only)
378 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
379 (if rstart
380 (progn
381 (goto-char (min rstart rend))
382 (setq rend (copy-marker (max rstart rend))))
383 (if (and transient-mark-mode mark-active)
384 (setq rstart (region-beginning)
385 rend (copy-marker (region-end)))
386 (setq rstart (point)
387 rend (point-max-marker)))
388 (goto-char rstart))
389 (save-excursion
390 (or (bolp) (forward-line 1))
391 (let ((start (point))
392 (case-fold-search (and case-fold-search
393 (isearch-no-upper-case-p regexp t))))
394 (while (< (point) rend)
395 ;; Start is first char not preserved by previous match.
396 (if (not (re-search-forward regexp rend 'move))
397 (delete-region start rend)
398 (let ((end (save-excursion (goto-char (match-beginning 0))
399 (beginning-of-line)
400 (point))))
401 ;; Now end is first char preserved by the new match.
402 (if (< start end)
403 (delete-region start end))))
404
405 (setq start (save-excursion (forward-line 1) (point)))
406 ;; If the match was empty, avoid matching again at same place.
407 (and (< (point) rend)
408 (= (match-beginning 0) (match-end 0))
409 (forward-char 1))))))
410
411
412 (defun flush-lines (regexp &optional rstart rend)
413 "Delete lines containing matches for REGEXP.
414 If a match is split across lines, all the lines it lies in are deleted.
415 Applies to lines after point.
416
417 If REGEXP contains upper case characters (excluding those preceded by `\\'),
418 the matching is case-sensitive.
419
420 Second and third arg RSTART and REND specify the region to operate on.
421
422 Interactively, in Transient Mark mode when the mark is active, operate
423 on the contents of the region. Otherwise, operate from point to the
424 end of the buffer."
425
426 (interactive
427 (progn
428 (barf-if-buffer-read-only)
429 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
430 (if rstart
431 (progn
432 (goto-char (min rstart rend))
433 (setq rend (copy-marker (max rstart rend))))
434 (if (and transient-mark-mode mark-active)
435 (setq rstart (region-beginning)
436 rend (copy-marker (region-end)))
437 (setq rstart (point)
438 rend (point-max-marker)))
439 (goto-char rstart))
440 (let ((case-fold-search (and case-fold-search
441 (isearch-no-upper-case-p regexp t))))
442 (save-excursion
443 (while (and (< (point) rend)
444 (re-search-forward regexp rend t))
445 (delete-region (save-excursion (goto-char (match-beginning 0))
446 (beginning-of-line)
447 (point))
448 (progn (forward-line 1) (point)))))))
449
450
451 (defun how-many (regexp &optional rstart rend)
452 "Print number of matches for REGEXP following point.
453
454 If REGEXP contains upper case characters (excluding those preceded by `\\'),
455 the matching is case-sensitive.
456
457 Second and third arg RSTART and REND specify the region to operate on.
458
459 Interactively, in Transient Mark mode when the mark is active, operate
460 on the contents of the region. Otherwise, operate from point to the
461 end of the buffer."
462
463 (interactive
464 (keep-lines-read-args "How many matches for (regexp): "))
465 (save-excursion
466 (if rstart
467 (goto-char (min rstart rend))
468 (if (and transient-mark-mode mark-active)
469 (setq rstart (region-beginning)
470 rend (copy-marker (region-end)))
471 (setq rstart (point)
472 rend (point-max-marker)))
473 (goto-char rstart))
474 (let ((count 0)
475 opoint
476 (case-fold-search (and case-fold-search
477 (isearch-no-upper-case-p regexp t))))
478 (while (and (< (point) rend)
479 (progn (setq opoint (point))
480 (re-search-forward regexp rend t)))
481 (if (= opoint (point))
482 (forward-char 1)
483 (setq count (1+ count))))
484 (message "%d occurrences" count))))
485
486 \f
487 (defvar occur-mode-map
488 (let ((map (make-sparse-keymap)))
489 (define-key map [mouse-2] 'occur-mode-mouse-goto)
490 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
491 (define-key map "\C-m" 'occur-mode-goto-occurrence)
492 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
493 (define-key map "\C-o" 'occur-mode-display-occurrence)
494 (define-key map "\M-n" 'occur-next)
495 (define-key map "\M-p" 'occur-prev)
496 (define-key map "r" 'occur-rename-buffer)
497 (define-key map "c" 'clone-buffer)
498 (define-key map "g" 'revert-buffer)
499 (define-key map "q" 'quit-window)
500 (define-key map "z" 'kill-this-buffer)
501 map)
502 "Keymap for `occur-mode'.")
503
504 (defvar occur-revert-arguments nil
505 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
506 See `occur-revert-function'.")
507
508 (defcustom occur-mode-hook '(turn-on-font-lock)
509 "Hook run when entering Occur mode."
510 :type 'hook
511 :group 'matching)
512
513 (defcustom occur-hook nil
514 "Hook run when `occur' is called."
515 :type 'hook
516 :group 'matching)
517
518 (put 'occur-mode 'mode-class 'special)
519 (defun occur-mode ()
520 "Major mode for output from \\[occur].
521 \\<occur-mode-map>Move point to one of the items in this buffer, then use
522 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
523 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
524
525 \\{occur-mode-map}"
526 (interactive)
527 (kill-all-local-variables)
528 (use-local-map occur-mode-map)
529 (setq major-mode 'occur-mode)
530 (setq mode-name "Occur")
531 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
532 (make-local-variable 'occur-revert-arguments)
533 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
534 (run-hooks 'occur-mode-hook))
535
536 (defun occur-revert-function (ignore1 ignore2)
537 "Handle `revert-buffer' for Occur mode buffers."
538 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
539
540 (defun occur-mode-mouse-goto (event)
541 "In Occur mode, go to the occurrence whose line you click on."
542 (interactive "e")
543 (let (pos)
544 (save-excursion
545 (set-buffer (window-buffer (posn-window (event-end event))))
546 (save-excursion
547 (goto-char (posn-point (event-end event)))
548 (setq pos (occur-mode-find-occurrence))))
549 (pop-to-buffer (marker-buffer pos))
550 (goto-char pos)))
551
552 (defun occur-mode-find-occurrence ()
553 (let ((pos (get-text-property (point) 'occur-target)))
554 (unless pos
555 (error "No occurrence on this line"))
556 (unless (buffer-live-p (marker-buffer pos))
557 (error "Buffer for this occurrence was killed"))
558 pos))
559
560 (defun occur-mode-goto-occurrence ()
561 "Go to the occurrence the current line describes."
562 (interactive)
563 (let ((pos (occur-mode-find-occurrence)))
564 (pop-to-buffer (marker-buffer pos))
565 (goto-char pos)))
566
567 (defun occur-mode-goto-occurrence-other-window ()
568 "Go to the occurrence the current line describes, in another window."
569 (interactive)
570 (let ((pos (occur-mode-find-occurrence)))
571 (switch-to-buffer-other-window (marker-buffer pos))
572 (goto-char pos)))
573
574 (defun occur-mode-display-occurrence ()
575 "Display in another window the occurrence the current line describes."
576 (interactive)
577 (let ((pos (occur-mode-find-occurrence))
578 window
579 ;; Bind these to ensure `display-buffer' puts it in another window.
580 same-window-buffer-names
581 same-window-regexps)
582 (setq window (display-buffer (marker-buffer pos)))
583 ;; This is the way to set point in the proper window.
584 (save-selected-window
585 (select-window window)
586 (goto-char pos))))
587
588 (defun occur-find-match (n search message)
589 (if (not n) (setq n 1))
590 (let ((r))
591 (while (> n 0)
592 (setq r (funcall search (point) 'occur-match))
593 (and r
594 (get-text-property r 'occur-match)
595 (setq r (funcall search r 'occur-match)))
596 (if r
597 (goto-char r)
598 (error message))
599 (setq n (1- n)))))
600
601 (defun occur-next (&optional n)
602 "Move to the Nth (default 1) next match in an Occur mode buffer."
603 (interactive "p")
604 (occur-find-match n #'next-single-property-change "No more matches"))
605
606 (defun occur-prev (&optional n)
607 "Move to the Nth (default 1) previous match in an Occur mode buffer."
608 (interactive "p")
609 (occur-find-match n #'previous-single-property-change "No earlier matches"))
610 \f
611 (defcustom list-matching-lines-default-context-lines 0
612 "*Default number of context lines included around `list-matching-lines' matches.
613 A negative number means to include that many lines before the match.
614 A positive number means to include that many lines both before and after."
615 :type 'integer
616 :group 'matching)
617
618 (defalias 'list-matching-lines 'occur)
619
620 (defcustom list-matching-lines-face 'bold
621 "*Face used by \\[list-matching-lines] to show the text that matches.
622 If the value is nil, don't highlight the matching portions specially."
623 :type 'face
624 :group 'matching)
625
626 (defcustom list-matching-lines-buffer-name-face 'underline
627 "*Face used by \\[list-matching-lines] to show the names of buffers.
628 If the value is nil, don't highlight the buffer names specially."
629 :type 'face
630 :group 'matching)
631
632 (defun occur-accumulate-lines (count &optional no-props)
633 (save-excursion
634 (let ((forwardp (> count 0))
635 (result nil))
636 (while (not (or (zerop count)
637 (if forwardp
638 (eobp)
639 (bobp))))
640 (setq count (+ count (if forwardp -1 1)))
641 (push
642 (funcall (if no-props
643 #'buffer-substring-no-properties
644 #'buffer-substring)
645 (line-beginning-position)
646 (line-end-position))
647 result)
648 (forward-line (if forwardp 1 -1)))
649 (nreverse result))))
650
651 (defun occur-read-primary-args ()
652 (list (let* ((default (car regexp-history))
653 (input
654 (read-from-minibuffer
655 (if default
656 (format "List lines matching regexp (default `%s'): "
657 default)
658 "List lines matching regexp: ")
659 nil
660 nil
661 nil
662 'regexp-history)))
663 (if (equal input "")
664 default
665 input))
666 (when current-prefix-arg
667 (prefix-numeric-value current-prefix-arg))))
668
669 (defun occur-rename-buffer (&optional unique-p)
670 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
671 Here `original-buffer-name' is the buffer name were occur was originally run.
672 When given the prefix argument, the renaming will not clobber the existing
673 buffer(s) of that name, but use `generate-new-buffer-name' instead.
674 You can add this to `occur-hook' if you always want a separate *Occur*
675 buffer for each buffer where you invoke `occur'."
676 (interactive "P")
677 (with-current-buffer
678 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
679 (rename-buffer (concat "*Occur: "
680 (mapconcat #'buffer-name
681 (car (cddr occur-revert-arguments)) "/")
682 "*")
683 unique-p)))
684
685 (defun occur (regexp &optional nlines)
686 "Show all lines in the current buffer containing a match for REGEXP.
687
688 If a match spreads across multiple lines, all those lines are shown.
689
690 Each line is displayed with NLINES lines before and after, or -NLINES
691 before if NLINES is negative.
692 NLINES defaults to `list-matching-lines-default-context-lines'.
693 Interactively it is the prefix arg.
694
695 The lines are shown in a buffer named `*Occur*'.
696 It serves as a menu to find any of the occurrences in this buffer.
697 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
698
699 If REGEXP contains upper case characters (excluding those preceded by `\\'),
700 the matching is case-sensitive."
701 (interactive (occur-read-primary-args))
702 (occur-1 regexp nlines (list (current-buffer))))
703
704 (defun multi-occur (bufs regexp &optional nlines)
705 "Show all lines in buffers BUFS containing a match for REGEXP.
706 This function acts on multiple buffers; otherwise, it is exactly like
707 `occur'."
708 (interactive
709 (cons
710 (let* ((bufs (list (read-buffer "First buffer to search: "
711 (current-buffer) t)))
712 (buf nil)
713 (ido-ignore-item-temp-list bufs))
714 (while (not (string-equal
715 (setq buf (read-buffer
716 (if (eq read-buffer-function 'ido-read-buffer)
717 "Next buffer to search (C-j to end): "
718 "Next buffer to search (RET to end): ")
719 nil t))
720 ""))
721 (add-to-list 'bufs buf)
722 (setq ido-ignore-item-temp-list bufs))
723 (nreverse (mapcar #'get-buffer bufs)))
724 (occur-read-primary-args)))
725 (occur-1 regexp nlines bufs))
726
727 (defun multi-occur-by-filename-regexp (bufregexp regexp &optional nlines)
728 "Show all lines matching REGEXP in buffers named by BUFREGEXP.
729 See also `multi-occur'."
730 (interactive
731 (cons
732 (let* ((default (car regexp-history))
733 (input
734 (read-from-minibuffer
735 "List lines in buffers whose filename matches regexp: "
736 nil
737 nil
738 nil
739 'regexp-history)))
740 (if (equal input "")
741 default
742 input))
743 (occur-read-primary-args)))
744 (when bufregexp
745 (occur-1 regexp nlines
746 (delq nil
747 (mapcar (lambda (buf)
748 (when (and (buffer-file-name buf)
749 (string-match bufregexp
750 (buffer-file-name buf)))
751 buf))
752 (buffer-list))))))
753
754 (defun occur-1 (regexp nlines bufs &optional buf-name)
755 (unless buf-name
756 (setq buf-name "*Occur*"))
757 (let ((occur-buf (get-buffer-create buf-name))
758 (made-temp-buf nil)
759 (active-bufs (delq nil (mapcar #'(lambda (buf)
760 (when (buffer-live-p buf) buf))
761 bufs))))
762 ;; Handle the case where one of the buffers we're searching is the
763 ;; *Occur* buffer itself.
764 (when (memq occur-buf bufs)
765 (setq occur-buf (with-current-buffer occur-buf
766 (clone-buffer "*Occur-temp*"))
767 made-temp-buf t))
768 (with-current-buffer occur-buf
769 (setq buffer-read-only nil)
770 (occur-mode)
771 (erase-buffer)
772 (let ((count (occur-engine
773 regexp active-bufs occur-buf
774 (or nlines list-matching-lines-default-context-lines)
775 (and case-fold-search
776 (isearch-no-upper-case-p regexp t))
777 list-matching-lines-buffer-name-face
778 nil list-matching-lines-face nil)))
779 (let* ((bufcount (length active-bufs))
780 (diff (- (length bufs) bufcount)))
781 (message "Searched %d buffer%s%s; %s match%s for `%s'"
782 bufcount (if (= bufcount 1) "" "s")
783 (if (zerop diff) "" (format " (%d killed)" diff))
784 (if (zerop count) "no" (format "%d" count))
785 (if (= count 1) "" "es")
786 regexp))
787 ;; If we had to make a temporary buffer, make it the *Occur*
788 ;; buffer now.
789 (when made-temp-buf
790 (with-current-buffer (get-buffer buf-name)
791 (kill-buffer (current-buffer)))
792 (rename-buffer buf-name))
793 (setq occur-revert-arguments (list regexp nlines bufs)
794 buffer-read-only t)
795 (if (> count 0)
796 (display-buffer occur-buf)
797 (kill-buffer occur-buf)))
798 (run-hooks 'occur-hook))))
799
800 (defun occur-engine-add-prefix (lines)
801 (mapcar
802 #'(lambda (line)
803 (concat " :" line "\n"))
804 lines))
805
806 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
807 title-face prefix-face match-face keep-props)
808 (with-current-buffer out-buf
809 (setq buffer-read-only nil)
810 (let ((globalcount 0)
811 (coding nil))
812 ;; Map over all the buffers
813 (dolist (buf buffers)
814 (when (buffer-live-p buf)
815 (let ((matches 0) ;; count of matched lines
816 (lines 1) ;; line count
817 (matchbeg 0)
818 (matchend 0)
819 (origpt nil)
820 (begpt nil)
821 (endpt nil)
822 (marker nil)
823 (curstring "")
824 (headerpt (with-current-buffer out-buf (point))))
825 (save-excursion
826 (set-buffer buf)
827 (or coding
828 ;; Set CODING only if the current buffer locally
829 ;; binds buffer-file-coding-system.
830 (not (local-variable-p 'buffer-file-coding-system))
831 (setq coding buffer-file-coding-system))
832 (save-excursion
833 (goto-char (point-min)) ;; begin searching in the buffer
834 (while (not (eobp))
835 (setq origpt (point))
836 (when (setq endpt (re-search-forward regexp nil t))
837 (setq matches (1+ matches)) ;; increment match count
838 (setq matchbeg (match-beginning 0)
839 matchend (match-end 0))
840 (setq begpt (save-excursion
841 (goto-char matchbeg)
842 (line-beginning-position)))
843 (setq lines (+ lines (1- (count-lines origpt endpt))))
844 (setq marker (make-marker))
845 (set-marker marker matchbeg)
846 (setq curstring (buffer-substring begpt
847 (line-end-position)))
848 ;; Depropertize the string, and maybe
849 ;; highlight the matches
850 (let ((len (length curstring))
851 (start 0))
852 (unless keep-props
853 (set-text-properties 0 len nil curstring))
854 (while (and (< start len)
855 (string-match regexp curstring start))
856 (add-text-properties (match-beginning 0)
857 (match-end 0)
858 (append
859 `(occur-match t)
860 (when match-face
861 `(font-lock-face ,match-face)))
862 curstring)
863 (setq start (match-end 0))))
864 ;; Generate the string to insert for this match
865 (let* ((out-line
866 (concat
867 ;; Using 7 digits aligns tabs properly.
868 (apply #'propertize (format "%7d:" lines)
869 (append
870 (when prefix-face
871 `(font-lock-face prefix-face))
872 '(occur-prefix t)))
873 curstring
874 "\n"))
875 (data
876 (if (= nlines 0)
877 ;; The simple display style
878 out-line
879 ;; The complex multi-line display
880 ;; style. Generate a list of lines,
881 ;; concatenate them all together.
882 (apply #'concat
883 (nconc
884 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ nlines)) keep-props))))
885 (list out-line)
886 (occur-engine-add-prefix (cdr (occur-accumulate-lines (1+ nlines) keep-props))))))))
887 ;; Actually insert the match display data
888 (with-current-buffer out-buf
889 (let ((beg (point))
890 (end (progn (insert data) (point))))
891 (unless (= nlines 0)
892 (insert "-------\n"))
893 (add-text-properties
894 beg end
895 `(occur-target ,marker help-echo "mouse-2: go to this occurrence"))
896 ;; We don't put `mouse-face' on the newline,
897 ;; because that loses.
898 (add-text-properties beg (1- end) '(mouse-face highlight)))))
899 (goto-char endpt))
900 (if endpt
901 (progn
902 (setq lines (1+ lines))
903 ;; On to the next match...
904 (forward-line 1))
905 (goto-char (point-max))))))
906 (when (not (zerop matches)) ;; is the count zero?
907 (setq globalcount (+ globalcount matches))
908 (with-current-buffer out-buf
909 (goto-char headerpt)
910 (let ((beg (point))
911 end)
912 (insert (format "%d lines matching \"%s\" in buffer: %s\n"
913 matches regexp (buffer-name buf)))
914 (setq end (point))
915 (add-text-properties beg end
916 (append
917 (when title-face
918 `(font-lock-face ,title-face))
919 `(occur-title ,buf))))
920 (goto-char (point-min)))))))
921 (if coding
922 ;; CODING is buffer-file-coding-system of the first buffer
923 ;; that locally binds it. Let's use it also for the output
924 ;; buffer.
925 (set-buffer-file-coding-system coding))
926 ;; Return the number of matches
927 globalcount)))
928
929 \f
930 ;; It would be nice to use \\[...], but there is no reasonable way
931 ;; to make that display both SPC and Y.
932 (defconst query-replace-help
933 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
934 RET or `q' to exit, Period to replace one match and exit,
935 Comma to replace but not move point immediately,
936 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
937 C-w to delete match and recursive edit,
938 C-l to clear the screen, redisplay, and offer same replacement again,
939 ! to replace all remaining matches with no more questions,
940 ^ to move point back to previous match,
941 E to edit the replacement string"
942 "Help message while in `query-replace'.")
943
944 (defvar query-replace-map (make-sparse-keymap)
945 "Keymap that defines the responses to questions in `query-replace'.
946 The \"bindings\" in this map are not commands; they are answers.
947 The valid answers include `act', `skip', `act-and-show',
948 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
949 `automatic', `backup', `exit-prefix', and `help'.")
950
951 (define-key query-replace-map " " 'act)
952 (define-key query-replace-map "\d" 'skip)
953 (define-key query-replace-map [delete] 'skip)
954 (define-key query-replace-map [backspace] 'skip)
955 (define-key query-replace-map "y" 'act)
956 (define-key query-replace-map "n" 'skip)
957 (define-key query-replace-map "Y" 'act)
958 (define-key query-replace-map "N" 'skip)
959 (define-key query-replace-map "e" 'edit-replacement)
960 (define-key query-replace-map "E" 'edit-replacement)
961 (define-key query-replace-map "," 'act-and-show)
962 (define-key query-replace-map "q" 'exit)
963 (define-key query-replace-map "\r" 'exit)
964 (define-key query-replace-map [return] 'exit)
965 (define-key query-replace-map "." 'act-and-exit)
966 (define-key query-replace-map "\C-r" 'edit)
967 (define-key query-replace-map "\C-w" 'delete-and-edit)
968 (define-key query-replace-map "\C-l" 'recenter)
969 (define-key query-replace-map "!" 'automatic)
970 (define-key query-replace-map "^" 'backup)
971 (define-key query-replace-map "\C-h" 'help)
972 (define-key query-replace-map [f1] 'help)
973 (define-key query-replace-map [help] 'help)
974 (define-key query-replace-map "?" 'help)
975 (define-key query-replace-map "\C-g" 'quit)
976 (define-key query-replace-map "\C-]" 'quit)
977 (define-key query-replace-map "\e" 'exit-prefix)
978 (define-key query-replace-map [escape] 'exit-prefix)
979
980 (defun replace-match-string-symbols (n)
981 "Process a list (and any sub-lists), expanding certain symbols.
982 Symbol Expands To
983 N (match-string N) (where N is a string of digits)
984 #N (string-to-number (match-string N))
985 & (match-string 0)
986 #& (string-to-number (match-string 0))
987
988 Note that these symbols must be preceeded by a backslash in order to
989 type them."
990 (while n
991 (cond
992 ((consp (car n))
993 (replace-match-string-symbols (car n))) ;Process sub-list
994 ((symbolp (car n))
995 (let ((name (symbol-name (car n))))
996 (cond
997 ((string-match "^[0-9]+$" name)
998 (setcar n (list 'match-string (string-to-number name))))
999 ((string-match "^#[0-9]+$" name)
1000 (setcar n (list 'string-to-number
1001 (list 'match-string
1002 (string-to-number (substring name 1))))))
1003 ((string= "&" name)
1004 (setcar n '(match-string 0)))
1005 ((string= "#&" name)
1006 (setcar n '(string-to-number (match-string 0))))))))
1007 (setq n (cdr n))))
1008
1009 (defun replace-eval-replacement (expression replace-count)
1010 (let ((replacement (eval expression)))
1011 (if (stringp replacement)
1012 replacement
1013 (prin1-to-string replacement t))))
1014
1015 (defun replace-loop-through-replacements (data replace-count)
1016 ;; DATA is a vector contaning the following values:
1017 ;; 0 next-rotate-count
1018 ;; 1 repeat-count
1019 ;; 2 next-replacement
1020 ;; 3 replacements
1021 (if (= (aref data 0) replace-count)
1022 (progn
1023 (aset data 0 (+ replace-count (aref data 1)))
1024 (let ((next (cdr (aref data 2))))
1025 (aset data 2 (if (consp next) next (aref data 3))))))
1026 (car (aref data 2)))
1027
1028 (defun perform-replace (from-string replacements
1029 query-flag regexp-flag delimited-flag
1030 &optional repeat-count map start end)
1031 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1032 Don't use this in your own program unless you want to query and set the mark
1033 just as `query-replace' does. Instead, write a simple loop like this:
1034
1035 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1036 (replace-match \"foobar\" nil nil))
1037
1038 which will run faster and probably do exactly what you want. Please
1039 see the documentation of `replace-match' to find out how to simulate
1040 `case-replace'.
1041
1042 This function returns nil if and only if there were no matches to
1043 make, or the user didn't cancel the call."
1044 (or map (setq map query-replace-map))
1045 (and query-flag minibuffer-auto-raise
1046 (raise-frame (window-frame (minibuffer-window))))
1047 (let ((nocasify (not (and case-fold-search case-replace
1048 (string-equal from-string
1049 (downcase from-string)))))
1050 (case-fold-search (and case-fold-search
1051 (string-equal from-string
1052 (downcase from-string))))
1053 (literal (not regexp-flag))
1054 (search-function (if regexp-flag 're-search-forward 'search-forward))
1055 (search-string from-string)
1056 (real-match-data nil) ; the match data for the current match
1057 (next-replacement nil)
1058 (keep-going t)
1059 (stack nil)
1060 (replace-count 0)
1061 (nonempty-match nil)
1062
1063 ;; If non-nil, it is marker saying where in the buffer to stop.
1064 (limit nil)
1065
1066 ;; Data for the next match. If a cons, it has the same format as
1067 ;; (match-data); otherwise it is t if a match is possible at point.
1068 (match-again t)
1069
1070 (message
1071 (if query-flag
1072 (substitute-command-keys
1073 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
1074
1075 ;; If region is active, in Transient Mark mode, operate on region.
1076 (when start
1077 (setq limit (copy-marker (max start end)))
1078 (goto-char (min start end))
1079 (deactivate-mark))
1080
1081 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1082 ;; containing a function and its first argument. The function is
1083 ;; called to generate each replacement like this:
1084 ;; (funcall (car replacements) (cdr replacements) replace-count)
1085 ;; It must return a string.
1086 (cond
1087 ((stringp replacements)
1088 (setq next-replacement replacements
1089 replacements nil))
1090 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1091 (or repeat-count (setq repeat-count 1))
1092 (setq replacements (cons 'replace-loop-through-replacements
1093 (vector repeat-count repeat-count
1094 replacements replacements)))))
1095
1096 (if delimited-flag
1097 (setq search-function 're-search-forward
1098 search-string (concat "\\b"
1099 (if regexp-flag from-string
1100 (regexp-quote from-string))
1101 "\\b")))
1102 (push-mark)
1103 (undo-boundary)
1104 (unwind-protect
1105 ;; Loop finding occurrences that perhaps should be replaced.
1106 (while (and keep-going
1107 (not (eobp))
1108 ;; Use the next match if it is already known;
1109 ;; otherwise, search for a match after moving forward
1110 ;; one char if progress is required.
1111 (setq real-match-data
1112 (if (consp match-again)
1113 (progn (goto-char (nth 1 match-again))
1114 match-again)
1115 (and (or match-again
1116 ;; MATCH-AGAIN non-nil means we
1117 ;; accept an adjacent match. If
1118 ;; we don't, move one char to the
1119 ;; right. This takes us a
1120 ;; character too far at the end,
1121 ;; but this is undone after the
1122 ;; while-loop.
1123 (progn (forward-char 1) (not (eobp))))
1124 (funcall search-function search-string limit t)
1125 ;; For speed, use only integers and
1126 ;; reuse the list used last time.
1127 (match-data t real-match-data)))))
1128 ;; Optionally ignore matches that have a read-only property.
1129 (unless (and query-replace-skip-read-only
1130 (text-property-not-all
1131 (match-beginning 0) (match-end 0)
1132 'read-only nil))
1133
1134 ;; Record whether the match is nonempty, to avoid an infinite loop
1135 ;; repeatedly matching the same empty string.
1136 (setq nonempty-match
1137 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1138
1139 ;; If the match is empty, record that the next one can't be
1140 ;; adjacent.
1141
1142 ;; Otherwise, if matching a regular expression, do the next
1143 ;; match now, since the replacement for this match may
1144 ;; affect whether the next match is adjacent to this one.
1145 ;; If that match is empty, don't use it.
1146 (setq match-again
1147 (and nonempty-match
1148 (or (not regexp-flag)
1149 (and (looking-at search-string)
1150 (let ((match (match-data)))
1151 (and (/= (nth 0 match) (nth 1 match))
1152 match))))))
1153
1154 ;; Calculate the replacement string, if necessary.
1155 (when replacements
1156 (set-match-data real-match-data)
1157 (setq next-replacement
1158 (funcall (car replacements) (cdr replacements)
1159 replace-count)))
1160 (if (not query-flag)
1161 (let ((inhibit-read-only query-replace-skip-read-only))
1162 (set-match-data real-match-data)
1163 (replace-match next-replacement nocasify literal)
1164 (setq replace-count (1+ replace-count)))
1165 (undo-boundary)
1166 (let (done replaced key def)
1167 ;; Loop reading commands until one of them sets done,
1168 ;; which means it has finished handling this occurrence.
1169 (while (not done)
1170 (set-match-data real-match-data)
1171 (replace-highlight (match-beginning 0) (match-end 0))
1172 ;; Bind message-log-max so we don't fill up the message log
1173 ;; with a bunch of identical messages.
1174 (let ((message-log-max nil))
1175 (message message from-string next-replacement))
1176 (setq key (read-event))
1177 ;; Necessary in case something happens during read-event
1178 ;; that clobbers the match data.
1179 (set-match-data real-match-data)
1180 (setq key (vector key))
1181 (setq def (lookup-key map key))
1182 ;; Restore the match data while we process the command.
1183 (cond ((eq def 'help)
1184 (with-output-to-temp-buffer "*Help*"
1185 (princ
1186 (concat "Query replacing "
1187 (if regexp-flag "regexp " "")
1188 from-string " with "
1189 next-replacement ".\n\n"
1190 (substitute-command-keys
1191 query-replace-help)))
1192 (with-current-buffer standard-output
1193 (help-mode))))
1194 ((eq def 'exit)
1195 (setq keep-going nil)
1196 (setq done t))
1197 ((eq def 'backup)
1198 (if stack
1199 (let ((elt (pop stack)))
1200 (goto-char (car elt))
1201 (setq replaced (eq t (cdr elt)))
1202 (or replaced
1203 (set-match-data (cdr elt))))
1204 (message "No previous match")
1205 (ding 'no-terminate)
1206 (sit-for 1)))
1207 ((eq def 'act)
1208 (or replaced
1209 (progn
1210 (replace-match next-replacement nocasify literal)
1211 (setq replace-count (1+ replace-count))))
1212 (setq done t replaced t))
1213 ((eq def 'act-and-exit)
1214 (or replaced
1215 (progn
1216 (replace-match next-replacement nocasify literal)
1217 (setq replace-count (1+ replace-count))))
1218 (setq keep-going nil)
1219 (setq done t replaced t))
1220 ((eq def 'act-and-show)
1221 (if (not replaced)
1222 (progn
1223 (replace-match next-replacement nocasify literal)
1224 (setq replace-count (1+ replace-count))
1225 (setq replaced t))))
1226 ((eq def 'automatic)
1227 (or replaced
1228 (progn
1229 (replace-match next-replacement nocasify literal)
1230 (setq replace-count (1+ replace-count))))
1231 (setq done t query-flag nil replaced t))
1232 ((eq def 'skip)
1233 (setq done t))
1234 ((eq def 'recenter)
1235 (recenter nil))
1236 ((eq def 'edit)
1237 (let ((opos (point-marker)))
1238 (goto-char (match-beginning 0))
1239 (save-excursion
1240 (funcall search-function search-string limit t)
1241 (setq real-match-data (match-data)))
1242 (save-excursion
1243 (save-window-excursion
1244 (recursive-edit)))
1245 (goto-char opos))
1246 (set-match-data real-match-data)
1247 ;; Before we make the replacement,
1248 ;; decide whether the search string
1249 ;; can match again just after this match.
1250 (if (and regexp-flag nonempty-match)
1251 (setq match-again (and (looking-at search-string)
1252 (match-data)))))
1253
1254 ;; Edit replacement.
1255 ((eq def 'edit-replacement)
1256 (setq next-replacement
1257 (read-input "Edit replacement string: "
1258 next-replacement))
1259 (or replaced
1260 (replace-match next-replacement nocasify literal))
1261 (setq done t))
1262
1263 ((eq def 'delete-and-edit)
1264 (delete-region (match-beginning 0) (match-end 0))
1265 (set-match-data
1266 (prog1 (match-data)
1267 (save-excursion (recursive-edit))))
1268 (setq replaced t))
1269 ;; Note: we do not need to treat `exit-prefix'
1270 ;; specially here, since we reread
1271 ;; any unrecognized character.
1272 (t
1273 (setq this-command 'mode-exited)
1274 (setq keep-going nil)
1275 (setq unread-command-events
1276 (append (listify-key-sequence key)
1277 unread-command-events))
1278 (setq done t))))
1279 ;; Record previous position for ^ when we move on.
1280 ;; Change markers to numbers in the match data
1281 ;; since lots of markers slow down editing.
1282 (setq stack
1283 (cons (cons (point)
1284 (or replaced (match-data t)))
1285 stack))))))
1286
1287 ;; The code preventing adjacent regexp matches in the condition
1288 ;; of the while-loop above will haven taken us one character
1289 ;; beyond the last replacement. Undo that.
1290 (when (and regexp-flag (not match-again) (> replace-count 0))
1291 (backward-char 1))
1292
1293 (replace-dehighlight))
1294 (or unread-command-events
1295 (message "Replaced %d occurrence%s"
1296 replace-count
1297 (if (= replace-count 1) "" "s")))
1298 (and keep-going stack)))
1299
1300 (defcustom query-replace-highlight t
1301 "*Non-nil means to highlight words during query replacement."
1302 :type 'boolean
1303 :group 'matching)
1304
1305 (defvar replace-overlay nil)
1306
1307 (defun replace-dehighlight ()
1308 (and replace-overlay
1309 (progn
1310 (delete-overlay replace-overlay)
1311 (setq replace-overlay nil))))
1312
1313 (defun replace-highlight (start end)
1314 (and query-replace-highlight
1315 (progn
1316 (or replace-overlay
1317 (progn
1318 (setq replace-overlay (make-overlay start end))
1319 (overlay-put replace-overlay 'face
1320 (if (facep 'query-replace)
1321 'query-replace 'region))))
1322 (move-overlay replace-overlay start end (current-buffer)))))
1323
1324 ;;; replace.el ends here