(isearch-query-replace, isearch-query-replace-regexp):
[bpt/emacs.git] / lisp / replace.el
1 ;;; replace.el --- replace commands for Emacs
2
3 ;; Copyright (C) 1985, 1986, 1987, 1992, 1994, 1996, 1997, 2000, 2001,
4 ;; 2002, 2003, 2004, 2005, 2006, 2007, 2008 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 3 of the License, or
13 ;; (at your option) 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. If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; This package supplies the string and regular-expression replace functions
26 ;; documented in the Emacs user's manual.
27
28 ;;; Code:
29
30 (defcustom case-replace t
31 "*Non-nil means `query-replace' should preserve case in replacements."
32 :type 'boolean
33 :group 'matching)
34
35 (defvar query-replace-history nil)
36
37 (defvar query-replace-defaults nil
38 "Default values of FROM-STRING and TO-STRING for `query-replace'.
39 This is a cons cell (FROM-STRING . TO-STRING), or nil if there is
40 no default value.")
41
42 (defvar query-replace-interactive nil
43 "Non-nil means `query-replace' uses the last search string.
44 That becomes the \"string to replace\".")
45
46 (defcustom query-replace-from-history-variable 'query-replace-history
47 "History list to use for the FROM argument of `query-replace' commands.
48 The value of this variable should be a symbol; that symbol
49 is used as a variable to hold a history list for the strings
50 or patterns to be replaced."
51 :group 'matching
52 :type 'symbol
53 :version "20.3")
54
55 (defcustom query-replace-to-history-variable 'query-replace-history
56 "History list to use for the TO argument of `query-replace' commands.
57 The value of this variable should be a symbol; that symbol
58 is used as a variable to hold a history list for replacement
59 strings or patterns."
60 :group 'matching
61 :type 'symbol
62 :version "20.3")
63
64 (defcustom query-replace-skip-read-only nil
65 "*Non-nil means `query-replace' and friends ignore read-only matches."
66 :type 'boolean
67 :group 'matching
68 :version "22.1")
69
70 (defcustom query-replace-show-replacement t
71 "*Non-nil means to show what actual replacement text will be."
72 :type 'boolean
73 :group 'matching
74 :version "23.1")
75
76 (defcustom query-replace-highlight t
77 "*Non-nil means to highlight matches during query replacement."
78 :type 'boolean
79 :group 'matching)
80
81 (defcustom query-replace-lazy-highlight t
82 "*Controls the lazy-highlighting during query replacements.
83 When non-nil, all text in the buffer matching the current match
84 is highlighted lazily using isearch lazy highlighting (see
85 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
86 :type 'boolean
87 :group 'lazy-highlight
88 :group 'matching
89 :version "22.1")
90
91 (defface query-replace
92 '((t (:inherit isearch)))
93 "Face for highlighting query replacement matches."
94 :group 'matching
95 :version "22.1")
96
97 (defun query-replace-descr (string)
98 (mapconcat 'isearch-text-char-description string ""))
99
100 (defun query-replace-read-from (prompt regexp-flag)
101 "Query and return the `from' argument of a query-replace operation.
102 The return value can also be a pair (FROM . TO) indicating that the user
103 wants to replace FROM with TO."
104 (if query-replace-interactive
105 (car (if regexp-flag regexp-search-ring search-ring))
106 (let* ((history-add-new-input nil)
107 (from
108 ;; The save-excursion here is in case the user marks and copies
109 ;; a region in order to specify the minibuffer input.
110 ;; That should not clobber the region for the query-replace itself.
111 (save-excursion
112 (read-from-minibuffer
113 (if query-replace-defaults
114 (format "%s (default %s -> %s): " prompt
115 (query-replace-descr (car query-replace-defaults))
116 (query-replace-descr (cdr query-replace-defaults)))
117 (format "%s: " prompt))
118 nil nil nil
119 query-replace-from-history-variable
120 nil t))))
121 (if (and (zerop (length from)) query-replace-defaults)
122 (cons (car query-replace-defaults)
123 (query-replace-compile-replacement
124 (cdr query-replace-defaults) regexp-flag))
125 (add-to-history query-replace-from-history-variable from nil t)
126 ;; Warn if user types \n or \t, but don't reject the input.
127 (and regexp-flag
128 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
129 (let ((match (match-string 3 from)))
130 (cond
131 ((string= match "\\n")
132 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
133 ((string= match "\\t")
134 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
135 (sit-for 2)))
136 from))))
137
138 (defun query-replace-compile-replacement (to regexp-flag)
139 "Maybe convert a regexp replacement TO to Lisp.
140 Returns a list suitable for `perform-replace' if necessary,
141 the original string if not."
142 (if (and regexp-flag
143 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
144 (let (pos list char)
145 (while
146 (progn
147 (setq pos (match-end 0))
148 (push (substring to 0 (- pos 2)) list)
149 (setq char (aref to (1- pos))
150 to (substring to pos))
151 (cond ((eq char ?\#)
152 (push '(number-to-string replace-count) list))
153 ((eq char ?\,)
154 (setq pos (read-from-string to))
155 (push `(replace-quote ,(car pos)) list)
156 (let ((end
157 ;; Swallow a space after a symbol
158 ;; if there is a space.
159 (if (and (or (symbolp (car pos))
160 ;; Swallow a space after 'foo
161 ;; but not after (quote foo).
162 (and (eq (car-safe (car pos)) 'quote)
163 (not (= ?\( (aref to 0)))))
164 (eq (string-match " " to (cdr pos))
165 (cdr pos)))
166 (1+ (cdr pos))
167 (cdr pos))))
168 (setq to (substring to end)))))
169 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
170 (setq to (nreverse (delete "" (cons to list))))
171 (replace-match-string-symbols to)
172 (cons 'replace-eval-replacement
173 (if (cdr to)
174 (cons 'concat to)
175 (car to))))
176 to))
177
178
179 (defun query-replace-read-to (from prompt regexp-flag)
180 "Query and return the `to' argument of a query-replace operation."
181 (query-replace-compile-replacement
182 (save-excursion
183 (let* ((history-add-new-input nil)
184 (to (read-from-minibuffer
185 (format "%s %s with: " prompt (query-replace-descr from))
186 nil nil nil
187 query-replace-to-history-variable from t)))
188 (add-to-history query-replace-to-history-variable to nil t)
189 (setq query-replace-defaults (cons from to))
190 to))
191 regexp-flag))
192
193 (defun query-replace-read-args (prompt regexp-flag &optional noerror)
194 (unless noerror
195 (barf-if-buffer-read-only))
196 (let* ((from (query-replace-read-from prompt regexp-flag))
197 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
198 (query-replace-read-to from prompt regexp-flag))))
199 (list from to current-prefix-arg)))
200
201 (defun query-replace (from-string to-string &optional delimited start end)
202 "Replace some occurrences of FROM-STRING with TO-STRING.
203 As each match is found, the user must type a character saying
204 what to do with it. For directions, type \\[help-command] at that time.
205
206 In Transient Mark mode, if the mark is active, operate on the contents
207 of the region. Otherwise, operate from point to the end of the buffer.
208
209 If `query-replace-interactive' is non-nil, the last incremental search
210 string is used as FROM-STRING--you don't have to specify it with the
211 minibuffer.
212
213 Matching is independent of case if `case-fold-search' is non-nil and
214 FROM-STRING has no uppercase letters. Replacement transfers the case
215 pattern of the old text to the new text, if `case-replace' and
216 `case-fold-search' are non-nil and FROM-STRING has no uppercase
217 letters. \(Transferring the case pattern means that if the old text
218 matched is all caps, or capitalized, then its replacement is upcased
219 or capitalized.)
220
221 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
222 only matches surrounded by word boundaries.
223 Fourth and fifth arg START and END specify the region to operate on.
224
225 To customize possible responses, change the \"bindings\" in `query-replace-map'."
226 (interactive (let ((common
227 (query-replace-read-args
228 (if (and transient-mark-mode mark-active)
229 "Query replace in region"
230 "Query replace")
231 nil)))
232 (list (nth 0 common) (nth 1 common) (nth 2 common)
233 ;; These are done separately here
234 ;; so that command-history will record these expressions
235 ;; rather than the values they had this time.
236 (if (and transient-mark-mode mark-active)
237 (region-beginning))
238 (if (and transient-mark-mode mark-active)
239 (region-end)))))
240 (perform-replace from-string to-string t nil delimited nil nil start end))
241
242 (define-key esc-map "%" 'query-replace)
243
244 (defun query-replace-regexp (regexp to-string &optional delimited start end)
245 "Replace some things after point matching REGEXP with TO-STRING.
246 As each match is found, the user must type a character saying
247 what to do with it. For directions, type \\[help-command] at that time.
248
249 In Transient Mark mode, if the mark is active, operate on the contents
250 of the region. Otherwise, operate from point to the end of the buffer.
251
252 If `query-replace-interactive' is non-nil, the last incremental search
253 regexp is used as REGEXP--you don't have to specify it with the
254 minibuffer.
255
256 Matching is independent of case if `case-fold-search' is non-nil and
257 REGEXP has no uppercase letters. Replacement transfers the case
258 pattern of the old text to the new text, if `case-replace' and
259 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
260 \(Transferring the case pattern means that if the old text matched is
261 all caps, or capitalized, then its replacement is upcased or
262 capitalized.)
263
264 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
265 only matches surrounded by word boundaries.
266 Fourth and fifth arg START and END specify the region to operate on.
267
268 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
269 and `\\=\\N' (where N is a digit) stands for
270 whatever what matched the Nth `\\(...\\)' in REGEXP.
271 `\\?' lets you edit the replacement text in the minibuffer
272 at the given position for each replacement.
273
274 In interactive calls, the replacement text can contain `\\,'
275 followed by a Lisp expression. Each
276 replacement evaluates that expression to compute the replacement
277 string. Inside of that expression, `\\&' is a string denoting the
278 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
279 for the whole or a partial match converted to a number with
280 `string-to-number', and `\\#' itself for the number of replacements
281 done so far (starting with zero).
282
283 If the replacement expression is a symbol, write a space after it
284 to terminate it. One space there, if any, will be discarded.
285
286 When using those Lisp features interactively in the replacement
287 text, TO-STRING is actually made a list instead of a string.
288 Use \\[repeat-complex-command] after this command for details."
289 (interactive
290 (let ((common
291 (query-replace-read-args
292 (if (and transient-mark-mode mark-active)
293 "Query replace regexp in region"
294 "Query replace regexp")
295 t)))
296 (list (nth 0 common) (nth 1 common) (nth 2 common)
297 ;; These are done separately here
298 ;; so that command-history will record these expressions
299 ;; rather than the values they had this time.
300 (if (and transient-mark-mode mark-active)
301 (region-beginning))
302 (if (and transient-mark-mode mark-active)
303 (region-end)))))
304 (perform-replace regexp to-string t t delimited nil nil start end))
305
306 (define-key esc-map [?\C-%] 'query-replace-regexp)
307
308 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
309 "Replace some things after point matching REGEXP with the result of TO-EXPR.
310
311 Interactive use of this function is deprecated in favor of the
312 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
313 using `search-forward-regexp' and `replace-match' is preferred.
314
315 As each match is found, the user must type a character saying
316 what to do with it. For directions, type \\[help-command] at that time.
317
318 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
319 reference `replace-count' to get the number of replacements already made.
320 If the result of TO-EXPR is not a string, it is converted to one using
321 `prin1-to-string' with the NOESCAPE argument (which see).
322
323 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
324 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
325 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
326 Use `\\#&' or `\\#N' if you want a number instead of a string.
327 In interactive use, `\\#' in itself stands for `replace-count'.
328
329 In Transient Mark mode, if the mark is active, operate on the contents
330 of the region. Otherwise, operate from point to the end of the buffer.
331
332 If `query-replace-interactive' is non-nil, the last incremental search
333 regexp is used as REGEXP--you don't have to specify it with the
334 minibuffer.
335
336 Preserves case in each replacement if `case-replace' and `case-fold-search'
337 are non-nil and REGEXP has no uppercase letters.
338
339 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
340 only matches that are surrounded by word boundaries.
341 Fourth and fifth arg START and END specify the region to operate on."
342 (interactive
343 (progn
344 (barf-if-buffer-read-only)
345 (let* ((from
346 ;; Let-bind the history var to disable the "foo -> bar" default.
347 ;; Maybe we shouldn't disable this default, but for now I'll
348 ;; leave it off. --Stef
349 (let ((query-replace-to-history-variable nil))
350 (query-replace-read-from "Query replace regexp" t)))
351 (to (list (read-from-minibuffer
352 (format "Query replace regexp %s with eval: "
353 (query-replace-descr from))
354 nil nil t query-replace-to-history-variable from t))))
355 ;; We make TO a list because replace-match-string-symbols requires one,
356 ;; and the user might enter a single token.
357 (replace-match-string-symbols to)
358 (list from (car to) current-prefix-arg
359 (if (and transient-mark-mode mark-active)
360 (region-beginning))
361 (if (and transient-mark-mode mark-active)
362 (region-end))))))
363 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
364 t 'literal delimited nil nil start end))
365
366 (make-obsolete 'query-replace-regexp-eval
367 "for interactive use, use the special `\\,' feature of
368 `query-replace-regexp' instead. Non-interactively, a loop
369 using `search-forward-regexp' and `replace-match' is preferred." "22.1")
370
371 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
372 "Replace some matches for REGEXP with various strings, in rotation.
373 The second argument TO-STRINGS contains the replacement strings, separated
374 by spaces. This command works like `query-replace-regexp' except that
375 each successive replacement uses the next successive replacement string,
376 wrapping around from the last such string to the first.
377
378 In Transient Mark mode, if the mark is active, operate on the contents
379 of the region. Otherwise, operate from point to the end of the buffer.
380
381 Non-interactively, TO-STRINGS may be a list of replacement strings.
382
383 If `query-replace-interactive' is non-nil, the last incremental search
384 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
385
386 A prefix argument N says to use each replacement string N times
387 before rotating to the next.
388 Fourth and fifth arg START and END specify the region to operate on."
389 (interactive
390 (let* ((from (if query-replace-interactive
391 (car regexp-search-ring)
392 (read-from-minibuffer "Map query replace (regexp): "
393 nil nil nil
394 'query-replace-history nil t)))
395 (to (read-from-minibuffer
396 (format "Query replace %s with (space-separated strings): "
397 (query-replace-descr from))
398 nil nil nil
399 'query-replace-history from t)))
400 (list from to
401 (and current-prefix-arg
402 (prefix-numeric-value current-prefix-arg))
403 (if (and transient-mark-mode mark-active)
404 (region-beginning))
405 (if (and transient-mark-mode mark-active)
406 (region-end)))))
407 (let (replacements)
408 (if (listp to-strings)
409 (setq replacements to-strings)
410 (while (/= (length to-strings) 0)
411 (if (string-match " " to-strings)
412 (setq replacements
413 (append replacements
414 (list (substring to-strings 0
415 (string-match " " to-strings))))
416 to-strings (substring to-strings
417 (1+ (string-match " " to-strings))))
418 (setq replacements (append replacements (list to-strings))
419 to-strings ""))))
420 (perform-replace regexp replacements t t nil n nil start end)))
421
422 (defun replace-string (from-string to-string &optional delimited start end)
423 "Replace occurrences of FROM-STRING with TO-STRING.
424 Preserve case in each match if `case-replace' and `case-fold-search'
425 are non-nil and FROM-STRING has no uppercase letters.
426 \(Preserving case means that if the string matched is all caps, or capitalized,
427 then its replacement is upcased or capitalized.)
428
429 In Transient Mark mode, if the mark is active, operate on the contents
430 of the region. Otherwise, operate from point to the end of the buffer.
431
432 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
433 only matches surrounded by word boundaries.
434 Fourth and fifth arg START and END specify the region to operate on.
435
436 If `query-replace-interactive' is non-nil, the last incremental search
437 string is used as FROM-STRING--you don't have to specify it with the
438 minibuffer.
439
440 This function is usually the wrong thing to use in a Lisp program.
441 What you probably want is a loop like this:
442 (while (search-forward FROM-STRING nil t)
443 (replace-match TO-STRING nil t))
444 which will run faster and will not set the mark or print anything.
445 \(You may need a more complex loop if FROM-STRING can match the null string
446 and TO-STRING is also null.)"
447 (interactive
448 (let ((common
449 (query-replace-read-args
450 (if (and transient-mark-mode mark-active)
451 "Replace string in region"
452 "Replace string")
453 nil)))
454 (list (nth 0 common) (nth 1 common) (nth 2 common)
455 (if (and transient-mark-mode mark-active)
456 (region-beginning))
457 (if (and transient-mark-mode mark-active)
458 (region-end)))))
459 (perform-replace from-string to-string nil nil delimited nil nil start end))
460
461 (defun replace-regexp (regexp to-string &optional delimited start end)
462 "Replace things after point matching REGEXP with TO-STRING.
463 Preserve case in each match if `case-replace' and `case-fold-search'
464 are non-nil and REGEXP has no uppercase letters.
465
466 In Transient Mark mode, if the mark is active, operate on the contents
467 of the region. Otherwise, operate from point to the end of the buffer.
468
469 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
470 only matches surrounded by word boundaries.
471 Fourth and fifth arg START and END specify the region to operate on.
472
473 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
474 and `\\=\\N' (where N is a digit) stands for
475 whatever what matched the Nth `\\(...\\)' in REGEXP.
476 `\\?' lets you edit the replacement text in the minibuffer
477 at the given position for each replacement.
478
479 In interactive calls, the replacement text may contain `\\,'
480 followed by a Lisp expression used as part of the replacement
481 text. Inside of that expression, `\\&' is a string denoting the
482 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
483 numeric values from `string-to-number', and `\\#' itself for
484 `replace-count', the number of replacements occurred so far.
485
486 If your Lisp expression is an identifier and the next letter in
487 the replacement string would be interpreted as part of it, you
488 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
489 for this particular case you may also enter `\\#' in the
490 replacement text directly.
491
492 When using those Lisp features interactively in the replacement
493 text, TO-STRING is actually made a list instead of a string.
494 Use \\[repeat-complex-command] after this command for details.
495
496 If `query-replace-interactive' is non-nil, the last incremental search
497 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
498
499 This function is usually the wrong thing to use in a Lisp program.
500 What you probably want is a loop like this:
501 (while (re-search-forward REGEXP nil t)
502 (replace-match TO-STRING nil nil))
503 which will run faster and will not set the mark or print anything."
504 (interactive
505 (let ((common
506 (query-replace-read-args
507 (if (and transient-mark-mode mark-active)
508 "Replace regexp in region"
509 "Replace regexp")
510 t)))
511 (list (nth 0 common) (nth 1 common) (nth 2 common)
512 (if (and transient-mark-mode mark-active)
513 (region-beginning))
514 (if (and transient-mark-mode mark-active)
515 (region-end)))))
516 (perform-replace regexp to-string nil t delimited nil nil start end))
517
518 \f
519 (defvar regexp-history nil
520 "History list for some commands that read regular expressions.
521
522 Maximum length of the history list is determined by the value
523 of `history-length', which see.")
524
525 (defun read-regexp (prompt &optional default-value)
526 "Read regexp as a string using the regexp history and some useful defaults.
527 Prompt for a regular expression with PROMPT (without a colon and
528 space) in the minibuffer. The optional argument DEFAULT-VALUE
529 provides the value to display in the minibuffer prompt that is
530 returned if the user just types RET.
531 Values available via M-n are the string at point, the last isearch
532 regexp, the last isearch string, and the last replacement regexp."
533 (let* ((defaults
534 (list (regexp-quote
535 (or (funcall (or find-tag-default-function
536 (get major-mode 'find-tag-default-function)
537 'find-tag-default))
538 ""))
539 (car regexp-search-ring)
540 (regexp-quote (or (car search-ring) ""))
541 (car (symbol-value
542 query-replace-from-history-variable))))
543 (defaults (delete-dups (delq nil (delete "" defaults))))
544 ;; Don't add automatically the car of defaults for empty input
545 (history-add-new-input nil)
546 (input
547 (read-from-minibuffer
548 (if default-value
549 (format "%s (default %s): " prompt
550 (query-replace-descr default-value))
551 (format "%s: " prompt))
552 nil nil nil 'regexp-history defaults t)))
553 (if (equal input "")
554 default-value
555 (prog1 input
556 (add-to-history 'regexp-history input)))))
557
558
559 (defalias 'delete-non-matching-lines 'keep-lines)
560 (defalias 'delete-matching-lines 'flush-lines)
561 (defalias 'count-matches 'how-many)
562
563
564 (defun keep-lines-read-args (prompt)
565 "Read arguments for `keep-lines' and friends.
566 Prompt for a regexp with PROMPT.
567 Value is a list, (REGEXP)."
568 (list (read-regexp prompt) nil nil t))
569
570 (defun keep-lines (regexp &optional rstart rend interactive)
571 "Delete all lines except those containing matches for REGEXP.
572 A match split across lines preserves all the lines it lies in.
573 When called from Lisp (and usually interactively as well, see below)
574 applies to all lines starting after point.
575
576 If REGEXP contains upper case characters (excluding those preceded by `\\')
577 and `search-upper-case' is non-nil, the matching is case-sensitive.
578
579 Second and third arg RSTART and REND specify the region to operate on.
580 This command operates on (the accessible part of) all lines whose
581 accessible part is entirely contained in the region determined by RSTART
582 and REND. (A newline ending a line counts as part of that line.)
583
584 Interactively, in Transient Mark mode when the mark is active, operate
585 on all lines whose accessible part is entirely contained in the region.
586 Otherwise, the command applies to all lines starting after point.
587 When calling this function from Lisp, you can pretend that it was
588 called interactively by passing a non-nil INTERACTIVE argument.
589
590 This function starts looking for the next match from the end of
591 the previous match. Hence, it ignores matches that overlap
592 a previously found match."
593
594 (interactive
595 (progn
596 (barf-if-buffer-read-only)
597 (keep-lines-read-args "Keep lines containing match for regexp")))
598 (if rstart
599 (progn
600 (goto-char (min rstart rend))
601 (setq rend
602 (progn
603 (save-excursion
604 (goto-char (max rstart rend))
605 (unless (or (bolp) (eobp))
606 (forward-line 0))
607 (point-marker)))))
608 (if (and interactive transient-mark-mode mark-active)
609 (setq rstart (region-beginning)
610 rend (progn
611 (goto-char (region-end))
612 (unless (or (bolp) (eobp))
613 (forward-line 0))
614 (point-marker)))
615 (setq rstart (point)
616 rend (point-max-marker)))
617 (goto-char rstart))
618 (save-excursion
619 (or (bolp) (forward-line 1))
620 (let ((start (point))
621 (case-fold-search
622 (if (and case-fold-search search-upper-case)
623 (isearch-no-upper-case-p regexp t)
624 case-fold-search)))
625 (while (< (point) rend)
626 ;; Start is first char not preserved by previous match.
627 (if (not (re-search-forward regexp rend 'move))
628 (delete-region start rend)
629 (let ((end (save-excursion (goto-char (match-beginning 0))
630 (forward-line 0)
631 (point))))
632 ;; Now end is first char preserved by the new match.
633 (if (< start end)
634 (delete-region start end))))
635
636 (setq start (save-excursion (forward-line 1) (point)))
637 ;; If the match was empty, avoid matching again at same place.
638 (and (< (point) rend)
639 (= (match-beginning 0) (match-end 0))
640 (forward-char 1)))))
641 (set-marker rend nil)
642 nil)
643
644
645 (defun flush-lines (regexp &optional rstart rend interactive)
646 "Delete lines containing matches for REGEXP.
647 When called from Lisp (and usually when called interactively as
648 well, see below), applies to the part of the buffer after point.
649 The line point is in is deleted if and only if it contains a
650 match for regexp starting after point.
651
652 If REGEXP contains upper case characters (excluding those preceded by `\\')
653 and `search-upper-case' is non-nil, the matching is case-sensitive.
654
655 Second and third arg RSTART and REND specify the region to operate on.
656 Lines partially contained in this region are deleted if and only if
657 they contain a match entirely contained in it.
658
659 Interactively, in Transient Mark mode when the mark is active, operate
660 on the contents of the region. Otherwise, operate from point to the
661 end of (the accessible portion of) the buffer. When calling this function
662 from Lisp, you can pretend that it was called interactively by passing
663 a non-nil INTERACTIVE argument.
664
665 If a match is split across lines, all the lines it lies in are deleted.
666 They are deleted _before_ looking for the next match. Hence, a match
667 starting on the same line at which another match ended is ignored."
668
669 (interactive
670 (progn
671 (barf-if-buffer-read-only)
672 (keep-lines-read-args "Flush lines containing match for regexp")))
673 (if rstart
674 (progn
675 (goto-char (min rstart rend))
676 (setq rend (copy-marker (max rstart rend))))
677 (if (and interactive transient-mark-mode mark-active)
678 (setq rstart (region-beginning)
679 rend (copy-marker (region-end)))
680 (setq rstart (point)
681 rend (point-max-marker)))
682 (goto-char rstart))
683 (let ((case-fold-search
684 (if (and case-fold-search search-upper-case)
685 (isearch-no-upper-case-p regexp t)
686 case-fold-search)))
687 (save-excursion
688 (while (and (< (point) rend)
689 (re-search-forward regexp rend t))
690 (delete-region (save-excursion (goto-char (match-beginning 0))
691 (forward-line 0)
692 (point))
693 (progn (forward-line 1) (point))))))
694 (set-marker rend nil)
695 nil)
696
697
698 (defun how-many (regexp &optional rstart rend interactive)
699 "Print and return number of matches for REGEXP following point.
700 When called from Lisp and INTERACTIVE is omitted or nil, just return
701 the number, do not print it; if INTERACTIVE is t, the function behaves
702 in all respects has if it had been called interactively.
703
704 If REGEXP contains upper case characters (excluding those preceded by `\\')
705 and `search-upper-case' is non-nil, the matching is case-sensitive.
706
707 Second and third arg RSTART and REND specify the region to operate on.
708
709 Interactively, in Transient Mark mode when the mark is active, operate
710 on the contents of the region. Otherwise, operate from point to the
711 end of (the accessible portion of) the buffer.
712
713 This function starts looking for the next match from the end of
714 the previous match. Hence, it ignores matches that overlap
715 a previously found match."
716
717 (interactive
718 (keep-lines-read-args "How many matches for regexp"))
719 (save-excursion
720 (if rstart
721 (progn
722 (goto-char (min rstart rend))
723 (setq rend (max rstart rend)))
724 (if (and interactive transient-mark-mode mark-active)
725 (setq rstart (region-beginning)
726 rend (region-end))
727 (setq rstart (point)
728 rend (point-max)))
729 (goto-char rstart))
730 (let ((count 0)
731 opoint
732 (case-fold-search
733 (if (and case-fold-search search-upper-case)
734 (isearch-no-upper-case-p regexp t)
735 case-fold-search)))
736 (while (and (< (point) rend)
737 (progn (setq opoint (point))
738 (re-search-forward regexp rend t)))
739 (if (= opoint (point))
740 (forward-char 1)
741 (setq count (1+ count))))
742 (when interactive (message "%d occurrence%s"
743 count
744 (if (= count 1) "" "s")))
745 count)))
746
747 \f
748 (defvar occur-mode-map
749 (let ((map (make-sparse-keymap)))
750 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
751 (define-key map [mouse-2] 'occur-mode-mouse-goto)
752 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
753 (define-key map "\C-m" 'occur-mode-goto-occurrence)
754 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
755 (define-key map "\C-o" 'occur-mode-display-occurrence)
756 (define-key map "\M-n" 'occur-next)
757 (define-key map "\M-p" 'occur-prev)
758 (define-key map "r" 'occur-rename-buffer)
759 (define-key map "c" 'clone-buffer)
760 (define-key map "g" 'revert-buffer)
761 (define-key map "q" 'quit-window)
762 (define-key map "z" 'kill-this-buffer)
763 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
764 (define-key map [menu-bar] (make-sparse-keymap))
765 (define-key map [menu-bar occur]
766 (cons "Occur" map))
767 (define-key map [next-error-follow-minor-mode]
768 (menu-bar-make-mm-toggle next-error-follow-minor-mode
769 "Auto Occurrence Display"
770 "Display another occurrence when moving the cursor"))
771 (define-key map [separator-1] '("--"))
772 (define-key map [kill-this-buffer]
773 '(menu-item "Kill occur buffer" kill-this-buffer
774 :help "Kill the current *Occur* buffer"))
775 (define-key map [quit-window]
776 '(menu-item "Quit occur window" quit-window
777 :help "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
778 (define-key map [revert-buffer]
779 '(menu-item "Revert occur buffer" revert-buffer
780 :help "Replace the text in the *Occur* buffer with the results of rerunning occur"))
781 (define-key map [clone-buffer]
782 '(menu-item "Clone occur buffer" clone-buffer
783 :help "Create and return a twin copy of the current *Occur* buffer"))
784 (define-key map [occur-rename-buffer]
785 '(menu-item "Rename occur buffer" occur-rename-buffer
786 :help "Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
787 (define-key map [separator-2] '("--"))
788 (define-key map [occur-mode-goto-occurrence-other-window]
789 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
790 :help "Go to the occurrence the current line describes, in another window"))
791 (define-key map [occur-mode-goto-occurrence]
792 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
793 :help "Go to the occurrence the current line describes"))
794 (define-key map [occur-mode-display-occurrence]
795 '(menu-item "Display Occurrence" occur-mode-display-occurrence
796 :help "Display in another window the occurrence the current line describes"))
797 (define-key map [occur-next]
798 '(menu-item "Move to next match" occur-next
799 :help "Move to the Nth (default 1) next match in an Occur mode buffer"))
800 (define-key map [occur-prev]
801 '(menu-item "Move to previous match" occur-prev
802 :help "Move to the Nth (default 1) previous match in an Occur mode buffer"))
803 map)
804 "Keymap for `occur-mode'.")
805
806 (defvar occur-revert-arguments nil
807 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
808 See `occur-revert-function'.")
809
810 (defcustom occur-mode-hook '(turn-on-font-lock)
811 "Hook run when entering Occur mode."
812 :type 'hook
813 :group 'matching)
814
815 (defcustom occur-hook nil
816 "Hook run by Occur when there are any matches."
817 :type 'hook
818 :group 'matching)
819
820 (defcustom occur-mode-find-occurrence-hook nil
821 "Hook run by Occur after locating an occurrence.
822 This will be called with the cursor position at the occurrence. An application
823 for this is to reveal context in an outline-mode when the occurrence is hidden."
824 :type 'hook
825 :group 'matching)
826
827 (put 'occur-mode 'mode-class 'special)
828 (defun occur-mode ()
829 "Major mode for output from \\[occur].
830 \\<occur-mode-map>Move point to one of the items in this buffer, then use
831 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
832 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
833
834 \\{occur-mode-map}"
835 (interactive)
836 (kill-all-local-variables)
837 (use-local-map occur-mode-map)
838 (setq major-mode 'occur-mode)
839 (setq mode-name "Occur")
840 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
841 (make-local-variable 'occur-revert-arguments)
842 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
843 (setq next-error-function 'occur-next-error)
844 (run-mode-hooks 'occur-mode-hook))
845
846 (defun occur-revert-function (ignore1 ignore2)
847 "Handle `revert-buffer' for Occur mode buffers."
848 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
849
850 (defun occur-mode-find-occurrence ()
851 (let ((pos (get-text-property (point) 'occur-target)))
852 (unless pos
853 (error "No occurrence on this line"))
854 (unless (buffer-live-p (marker-buffer pos))
855 (error "Buffer for this occurrence was killed"))
856 pos))
857
858 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
859 (defun occur-mode-goto-occurrence (&optional event)
860 "Go to the occurrence the current line describes."
861 (interactive (list last-nonmenu-event))
862 (let ((pos
863 (if (null event)
864 ;; Actually `event-end' works correctly with a nil argument as
865 ;; well, so we could dispense with this test, but let's not
866 ;; rely on this undocumented behavior.
867 (occur-mode-find-occurrence)
868 (with-current-buffer (window-buffer (posn-window (event-end event)))
869 (save-excursion
870 (goto-char (posn-point (event-end event)))
871 (occur-mode-find-occurrence)))))
872 same-window-buffer-names
873 same-window-regexps)
874 (pop-to-buffer (marker-buffer pos))
875 (goto-char pos)
876 (run-hooks 'occur-mode-find-occurrence-hook)))
877
878 (defun occur-mode-goto-occurrence-other-window ()
879 "Go to the occurrence the current line describes, in another window."
880 (interactive)
881 (let ((pos (occur-mode-find-occurrence)))
882 (switch-to-buffer-other-window (marker-buffer pos))
883 (goto-char pos)
884 (run-hooks 'occur-mode-find-occurrence-hook)))
885
886 (defun occur-mode-display-occurrence ()
887 "Display in another window the occurrence the current line describes."
888 (interactive)
889 (let ((pos (occur-mode-find-occurrence))
890 window
891 ;; Bind these to ensure `display-buffer' puts it in another window.
892 same-window-buffer-names
893 same-window-regexps)
894 (setq window (display-buffer (marker-buffer pos)))
895 ;; This is the way to set point in the proper window.
896 (save-selected-window
897 (select-window window)
898 (goto-char pos)
899 (run-hooks 'occur-mode-find-occurrence-hook))))
900
901 (defun occur-find-match (n search message)
902 (if (not n) (setq n 1))
903 (let ((r))
904 (while (> n 0)
905 (setq r (funcall search (point) 'occur-match))
906 (and r
907 (get-text-property r 'occur-match)
908 (setq r (funcall search r 'occur-match)))
909 (if r
910 (goto-char r)
911 (error message))
912 (setq n (1- n)))))
913
914 (defun occur-next (&optional n)
915 "Move to the Nth (default 1) next match in an Occur mode buffer."
916 (interactive "p")
917 (occur-find-match n #'next-single-property-change "No more matches"))
918
919 (defun occur-prev (&optional n)
920 "Move to the Nth (default 1) previous match in an Occur mode buffer."
921 (interactive "p")
922 (occur-find-match n #'previous-single-property-change "No earlier matches"))
923
924 (defun occur-next-error (&optional argp reset)
925 "Move to the Nth (default 1) next match in an Occur mode buffer.
926 Compatibility function for \\[next-error] invocations."
927 (interactive "p")
928 ;; we need to run occur-find-match from within the Occur buffer
929 (with-current-buffer
930 ;; Choose the buffer and make it current.
931 (if (next-error-buffer-p (current-buffer))
932 (current-buffer)
933 (next-error-find-buffer nil nil
934 (lambda ()
935 (eq major-mode 'occur-mode))))
936
937 (goto-char (cond (reset (point-min))
938 ((< argp 0) (line-beginning-position))
939 ((> argp 0) (line-end-position))
940 ((point))))
941 (occur-find-match
942 (abs argp)
943 (if (> 0 argp)
944 #'previous-single-property-change
945 #'next-single-property-change)
946 "No more matches")
947 ;; In case the *Occur* buffer is visible in a nonselected window.
948 (let ((win (get-buffer-window (current-buffer) t)))
949 (if win (set-window-point win (point))))
950 (occur-mode-goto-occurrence)))
951 \f
952 (defface match
953 '((((class color) (min-colors 88) (background light))
954 :background "yellow1")
955 (((class color) (min-colors 88) (background dark))
956 :background "RoyalBlue3")
957 (((class color) (min-colors 8) (background light))
958 :background "yellow" :foreground "black")
959 (((class color) (min-colors 8) (background dark))
960 :background "blue" :foreground "white")
961 (((type tty) (class mono))
962 :inverse-video t)
963 (t :background "gray"))
964 "Face used to highlight matches permanently."
965 :group 'matching
966 :version "22.1")
967
968 (defcustom list-matching-lines-default-context-lines 0
969 "*Default number of context lines included around `list-matching-lines' matches.
970 A negative number means to include that many lines before the match.
971 A positive number means to include that many lines both before and after."
972 :type 'integer
973 :group 'matching)
974
975 (defalias 'list-matching-lines 'occur)
976
977 (defcustom list-matching-lines-face 'match
978 "*Face used by \\[list-matching-lines] to show the text that matches.
979 If the value is nil, don't highlight the matching portions specially."
980 :type 'face
981 :group 'matching)
982
983 (defcustom list-matching-lines-buffer-name-face 'underline
984 "*Face used by \\[list-matching-lines] to show the names of buffers.
985 If the value is nil, don't highlight the buffer names specially."
986 :type 'face
987 :group 'matching)
988
989 (defcustom occur-excluded-properties
990 '(read-only invisible intangible field mouse-face help-echo local-map keymap
991 yank-handler follow-link)
992 "*Text properties to discard when copying lines to the *Occur* buffer.
993 The value should be a list of text properties to discard or t,
994 which means to discard all text properties."
995 :type '(choice (const :tag "All" t) (repeat symbol))
996 :group 'matching
997 :version "22.1")
998
999 (defun occur-accumulate-lines (count &optional keep-props)
1000 (save-excursion
1001 (let ((forwardp (> count 0))
1002 result beg end)
1003 (while (not (or (zerop count)
1004 (if forwardp
1005 (eobp)
1006 (bobp))))
1007 (setq count (+ count (if forwardp -1 1)))
1008 (setq beg (line-beginning-position)
1009 end (line-end-position))
1010 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1011 (text-property-not-all beg end 'fontified t))
1012 (if (fboundp 'jit-lock-fontify-now)
1013 (jit-lock-fontify-now beg end)))
1014 (push
1015 (if (and keep-props (not (eq occur-excluded-properties t)))
1016 (let ((str (buffer-substring beg end)))
1017 (remove-list-of-text-properties
1018 0 (length str) occur-excluded-properties str)
1019 str)
1020 (buffer-substring-no-properties beg end))
1021 result)
1022 (forward-line (if forwardp 1 -1)))
1023 (nreverse result))))
1024
1025 (defun occur-read-primary-args ()
1026 (list (read-regexp "List lines matching regexp"
1027 (car regexp-history))
1028 (when current-prefix-arg
1029 (prefix-numeric-value current-prefix-arg))))
1030
1031 (defun occur-rename-buffer (&optional unique-p interactive-p)
1032 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1033 Here `original-buffer-name' is the buffer name were Occur was originally run.
1034 When given the prefix argument, or called non-interactively, the renaming
1035 will not clobber the existing buffer(s) of that name, but use
1036 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1037 if you always want a separate *Occur* buffer for each buffer where you
1038 invoke `occur'."
1039 (interactive "P\np")
1040 (with-current-buffer
1041 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1042 (rename-buffer (concat "*Occur: "
1043 (mapconcat #'buffer-name
1044 (car (cddr occur-revert-arguments)) "/")
1045 "*")
1046 (or unique-p (not interactive-p)))))
1047
1048 (defun occur (regexp &optional nlines)
1049 "Show all lines in the current buffer containing a match for REGEXP.
1050 This function can not handle matches that span more than one line.
1051
1052 Each line is displayed with NLINES lines before and after, or -NLINES
1053 before if NLINES is negative.
1054 NLINES defaults to `list-matching-lines-default-context-lines'.
1055 Interactively it is the prefix arg.
1056
1057 The lines are shown in a buffer named `*Occur*'.
1058 It serves as a menu to find any of the occurrences in this buffer.
1059 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1060
1061 If REGEXP contains upper case characters (excluding those preceded by `\\')
1062 and `search-upper-case' is non-nil, the matching is case-sensitive."
1063 (interactive (occur-read-primary-args))
1064 (occur-1 regexp nlines (list (current-buffer))))
1065
1066 (defun multi-occur (bufs regexp &optional nlines)
1067 "Show all lines in buffers BUFS containing a match for REGEXP.
1068 This function acts on multiple buffers; otherwise, it is exactly like
1069 `occur'. When you invoke this command interactively, you must specify
1070 the buffer names that you want, one by one."
1071 (interactive
1072 (cons
1073 (let* ((bufs (list (read-buffer "First buffer to search: "
1074 (current-buffer) t)))
1075 (buf nil)
1076 (ido-ignore-item-temp-list bufs))
1077 (while (not (string-equal
1078 (setq buf (read-buffer
1079 (if (eq read-buffer-function 'ido-read-buffer)
1080 "Next buffer to search (C-j to end): "
1081 "Next buffer to search (RET to end): ")
1082 nil t))
1083 ""))
1084 (add-to-list 'bufs buf)
1085 (setq ido-ignore-item-temp-list bufs))
1086 (nreverse (mapcar #'get-buffer bufs)))
1087 (occur-read-primary-args)))
1088 (occur-1 regexp nlines bufs))
1089
1090 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1091 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1092 Normally BUFREGEXP matches against each buffer's visited file name,
1093 but if you specify a prefix argument, it matches against the buffer name.
1094 See also `multi-occur'."
1095 (interactive
1096 (cons
1097 (let* ((default (car regexp-history))
1098 (input
1099 (read-from-minibuffer
1100 (if current-prefix-arg
1101 "List lines in buffers whose names match regexp: "
1102 "List lines in buffers whose filenames match regexp: ")
1103 nil
1104 nil
1105 nil
1106 'regexp-history)))
1107 (if (equal input "")
1108 default
1109 input))
1110 (occur-read-primary-args)))
1111 (when bufregexp
1112 (occur-1 regexp nil
1113 (delq nil
1114 (mapcar (lambda (buf)
1115 (when (if allbufs
1116 (string-match bufregexp
1117 (buffer-name buf))
1118 (and (buffer-file-name buf)
1119 (string-match bufregexp
1120 (buffer-file-name buf))))
1121 buf))
1122 (buffer-list))))))
1123
1124 (defun occur-1 (regexp nlines bufs &optional buf-name)
1125 (unless (and regexp (not (equal regexp "")))
1126 (error "Occur doesn't work with the empty regexp"))
1127 (unless buf-name
1128 (setq buf-name "*Occur*"))
1129 (let (occur-buf
1130 (active-bufs (delq nil (mapcar #'(lambda (buf)
1131 (when (buffer-live-p buf) buf))
1132 bufs))))
1133 ;; Handle the case where one of the buffers we're searching is the
1134 ;; output buffer. Just rename it.
1135 (when (member buf-name (mapcar 'buffer-name active-bufs))
1136 (with-current-buffer (get-buffer buf-name)
1137 (rename-uniquely)))
1138
1139 ;; Now find or create the output buffer.
1140 ;; If we just renamed that buffer, we will make a new one here.
1141 (setq occur-buf (get-buffer-create buf-name))
1142
1143 (with-current-buffer occur-buf
1144 (occur-mode)
1145 (let ((inhibit-read-only t)
1146 ;; Don't generate undo entries for creation of the initial contents.
1147 (buffer-undo-list t))
1148 (erase-buffer)
1149 (let ((count (occur-engine
1150 regexp active-bufs occur-buf
1151 (or nlines list-matching-lines-default-context-lines)
1152 (if (and case-fold-search search-upper-case)
1153 (isearch-no-upper-case-p regexp t)
1154 case-fold-search)
1155 list-matching-lines-buffer-name-face
1156 nil list-matching-lines-face
1157 (not (eq occur-excluded-properties t)))))
1158 (let* ((bufcount (length active-bufs))
1159 (diff (- (length bufs) bufcount)))
1160 (message "Searched %d buffer%s%s; %s match%s for `%s'"
1161 bufcount (if (= bufcount 1) "" "s")
1162 (if (zerop diff) "" (format " (%d killed)" diff))
1163 (if (zerop count) "no" (format "%d" count))
1164 (if (= count 1) "" "es")
1165 regexp))
1166 (setq occur-revert-arguments (list regexp nlines bufs))
1167 (if (= count 0)
1168 (kill-buffer occur-buf)
1169 (display-buffer occur-buf)
1170 (setq next-error-last-buffer occur-buf)
1171 (setq buffer-read-only t)
1172 (set-buffer-modified-p nil)
1173 (run-hooks 'occur-hook)))))))
1174
1175 (defun occur-engine-add-prefix (lines)
1176 (mapcar
1177 #'(lambda (line)
1178 (concat " :" line "\n"))
1179 lines))
1180
1181 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
1182 title-face prefix-face match-face keep-props)
1183 (with-current-buffer out-buf
1184 (let ((globalcount 0)
1185 (coding nil))
1186 ;; Map over all the buffers
1187 (dolist (buf buffers)
1188 (when (buffer-live-p buf)
1189 (let ((matches 0) ;; count of matched lines
1190 (lines 1) ;; line count
1191 (matchbeg 0)
1192 (origpt nil)
1193 (begpt nil)
1194 (endpt nil)
1195 (marker nil)
1196 (curstring "")
1197 (inhibit-field-text-motion t)
1198 (headerpt (with-current-buffer out-buf (point))))
1199 (with-current-buffer buf
1200 (or coding
1201 ;; Set CODING only if the current buffer locally
1202 ;; binds buffer-file-coding-system.
1203 (not (local-variable-p 'buffer-file-coding-system))
1204 (setq coding buffer-file-coding-system))
1205 (save-excursion
1206 (goto-char (point-min)) ;; begin searching in the buffer
1207 (while (not (eobp))
1208 (setq origpt (point))
1209 (when (setq endpt (re-search-forward regexp nil t))
1210 (setq matches (1+ matches)) ;; increment match count
1211 (setq matchbeg (match-beginning 0))
1212 (setq lines (+ lines (1- (count-lines origpt endpt))))
1213 (save-excursion
1214 (goto-char matchbeg)
1215 (setq begpt (line-beginning-position)
1216 endpt (line-end-position)))
1217 (setq marker (make-marker))
1218 (set-marker marker matchbeg)
1219 (if (and keep-props
1220 (if (boundp 'jit-lock-mode) jit-lock-mode)
1221 (text-property-not-all begpt endpt 'fontified t))
1222 (if (fboundp 'jit-lock-fontify-now)
1223 (jit-lock-fontify-now begpt endpt)))
1224 (if (and keep-props (not (eq occur-excluded-properties t)))
1225 (progn
1226 (setq curstring (buffer-substring begpt endpt))
1227 (remove-list-of-text-properties
1228 0 (length curstring) occur-excluded-properties curstring))
1229 (setq curstring (buffer-substring-no-properties begpt endpt)))
1230 ;; Highlight the matches
1231 (let ((len (length curstring))
1232 (start 0))
1233 (while (and (< start len)
1234 (string-match regexp curstring start))
1235 (add-text-properties
1236 (match-beginning 0) (match-end 0)
1237 (append
1238 `(occur-match t)
1239 (when match-face
1240 ;; Use `face' rather than `font-lock-face' here
1241 ;; so as to override faces copied from the buffer.
1242 `(face ,match-face)))
1243 curstring)
1244 (setq start (match-end 0))))
1245 ;; Generate the string to insert for this match
1246 (let* ((out-line
1247 (concat
1248 ;; Using 7 digits aligns tabs properly.
1249 (apply #'propertize (format "%7d:" lines)
1250 (append
1251 (when prefix-face
1252 `(font-lock-face prefix-face))
1253 `(occur-prefix t mouse-face (highlight)
1254 occur-target ,marker follow-link t
1255 help-echo "mouse-2: go to this occurrence")))
1256 ;; We don't put `mouse-face' on the newline,
1257 ;; because that loses. And don't put it
1258 ;; on context lines to reduce flicker.
1259 (propertize curstring 'mouse-face (list 'highlight)
1260 'occur-target marker
1261 'follow-link t
1262 'help-echo
1263 "mouse-2: go to this occurrence")
1264 ;; Add marker at eol, but no mouse props.
1265 (propertize "\n" 'occur-target marker)))
1266 (data
1267 (if (= nlines 0)
1268 ;; The simple display style
1269 out-line
1270 ;; The complex multi-line display style.
1271 (occur-context-lines out-line nlines keep-props)
1272 )))
1273 ;; Actually insert the match display data
1274 (with-current-buffer out-buf
1275 (let ((beg (point))
1276 (end (progn (insert data) (point))))
1277 (unless (= nlines 0)
1278 (insert "-------\n")))))
1279 (goto-char endpt))
1280 (if endpt
1281 (progn
1282 (setq lines (1+ lines))
1283 ;; On to the next match...
1284 (forward-line 1))
1285 (goto-char (point-max))))))
1286 (when (not (zerop matches)) ;; is the count zero?
1287 (setq globalcount (+ globalcount matches))
1288 (with-current-buffer out-buf
1289 (goto-char headerpt)
1290 (let ((beg (point))
1291 end)
1292 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1293 matches (if (= matches 1) "" "es")
1294 regexp (buffer-name buf)))
1295 (setq end (point))
1296 (add-text-properties beg end
1297 (append
1298 (when title-face
1299 `(font-lock-face ,title-face))
1300 `(occur-title ,buf))))
1301 (goto-char (point-min)))))))
1302 (if coding
1303 ;; CODING is buffer-file-coding-system of the first buffer
1304 ;; that locally binds it. Let's use it also for the output
1305 ;; buffer.
1306 (set-buffer-file-coding-system coding))
1307 ;; Return the number of matches
1308 globalcount)))
1309
1310 ;; Generate context display for occur.
1311 ;; OUT-LINE is the line where the match is.
1312 ;; NLINES and KEEP-PROPS are args to occur-engine.
1313 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1314 ;; then concatenate them all together.
1315 (defun occur-context-lines (out-line nlines keep-props)
1316 (apply #'concat
1317 (nconc
1318 (occur-engine-add-prefix
1319 (nreverse (cdr (occur-accumulate-lines
1320 (- (1+ (abs nlines))) keep-props))))
1321 (list out-line)
1322 (if (> nlines 0)
1323 (occur-engine-add-prefix
1324 (cdr (occur-accumulate-lines (1+ nlines) keep-props)))))))
1325 \f
1326 ;; It would be nice to use \\[...], but there is no reasonable way
1327 ;; to make that display both SPC and Y.
1328 (defconst query-replace-help
1329 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1330 RET or `q' to exit, Period to replace one match and exit,
1331 Comma to replace but not move point immediately,
1332 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1333 C-w to delete match and recursive edit,
1334 C-l to clear the screen, redisplay, and offer same replacement again,
1335 ! to replace all remaining matches with no more questions,
1336 ^ to move point back to previous match,
1337 E to edit the replacement string"
1338 "Help message while in `query-replace'.")
1339
1340 (defvar query-replace-map
1341 (let ((map (make-sparse-keymap)))
1342 (define-key map " " 'act)
1343 (define-key map "\d" 'skip)
1344 (define-key map [delete] 'skip)
1345 (define-key map [backspace] 'skip)
1346 (define-key map "y" 'act)
1347 (define-key map "n" 'skip)
1348 (define-key map "Y" 'act)
1349 (define-key map "N" 'skip)
1350 (define-key map "e" 'edit-replacement)
1351 (define-key map "E" 'edit-replacement)
1352 (define-key map "," 'act-and-show)
1353 (define-key map "q" 'exit)
1354 (define-key map "\r" 'exit)
1355 (define-key map [return] 'exit)
1356 (define-key map "." 'act-and-exit)
1357 (define-key map "\C-r" 'edit)
1358 (define-key map "\C-w" 'delete-and-edit)
1359 (define-key map "\C-l" 'recenter)
1360 (define-key map "!" 'automatic)
1361 (define-key map "^" 'backup)
1362 (define-key map "\C-h" 'help)
1363 (define-key map [f1] 'help)
1364 (define-key map [help] 'help)
1365 (define-key map "?" 'help)
1366 (define-key map "\C-g" 'quit)
1367 (define-key map "\C-]" 'quit)
1368 (define-key map "\e" 'exit-prefix)
1369 (define-key map [escape] 'exit-prefix)
1370 map)
1371 "Keymap that defines the responses to questions in `query-replace'.
1372 The \"bindings\" in this map are not commands; they are answers.
1373 The valid answers include `act', `skip', `act-and-show',
1374 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1375 `automatic', `backup', `exit-prefix', and `help'.")
1376
1377 (defvar multi-query-replace-map
1378 (let ((map (make-sparse-keymap)))
1379 (set-keymap-parent map query-replace-map)
1380 (define-key map "Y" 'automatic-all)
1381 (define-key map "N" 'exit-current)
1382 map)
1383 "Keymap that defines additional bindings for multi-buffer replacements.
1384 It extends its parent map `query-replace-map' with new bindings to
1385 operate on a set of buffers/files. The difference with its parent map
1386 is the additional answers `automatic-all' to replace all remaining
1387 matches in all remaining buffers with no more questions, and
1388 `exit-current' to skip remaining matches in the current buffer
1389 and to continue with the next buffer in the sequence.")
1390
1391 (defun replace-match-string-symbols (n)
1392 "Process a list (and any sub-lists), expanding certain symbols.
1393 Symbol Expands To
1394 N (match-string N) (where N is a string of digits)
1395 #N (string-to-number (match-string N))
1396 & (match-string 0)
1397 #& (string-to-number (match-string 0))
1398 # replace-count
1399
1400 Note that these symbols must be preceeded by a backslash in order to
1401 type them using Lisp syntax."
1402 (while (consp n)
1403 (cond
1404 ((consp (car n))
1405 (replace-match-string-symbols (car n))) ;Process sub-list
1406 ((symbolp (car n))
1407 (let ((name (symbol-name (car n))))
1408 (cond
1409 ((string-match "^[0-9]+$" name)
1410 (setcar n (list 'match-string (string-to-number name))))
1411 ((string-match "^#[0-9]+$" name)
1412 (setcar n (list 'string-to-number
1413 (list 'match-string
1414 (string-to-number (substring name 1))))))
1415 ((string= "&" name)
1416 (setcar n '(match-string 0)))
1417 ((string= "#&" name)
1418 (setcar n '(string-to-number (match-string 0))))
1419 ((string= "#" name)
1420 (setcar n 'replace-count))))))
1421 (setq n (cdr n))))
1422
1423 (defun replace-eval-replacement (expression replace-count)
1424 (let ((replacement (eval expression)))
1425 (if (stringp replacement)
1426 replacement
1427 (prin1-to-string replacement t))))
1428
1429 (defun replace-quote (replacement)
1430 "Quote a replacement string.
1431 This just doubles all backslashes in REPLACEMENT and
1432 returns the resulting string. If REPLACEMENT is not
1433 a string, it is first passed through `prin1-to-string'
1434 with the `noescape' argument set.
1435
1436 `match-data' is preserved across the call."
1437 (save-match-data
1438 (replace-regexp-in-string "\\\\" "\\\\"
1439 (if (stringp replacement)
1440 replacement
1441 (prin1-to-string replacement t))
1442 t t)))
1443
1444 (defun replace-loop-through-replacements (data replace-count)
1445 ;; DATA is a vector contaning the following values:
1446 ;; 0 next-rotate-count
1447 ;; 1 repeat-count
1448 ;; 2 next-replacement
1449 ;; 3 replacements
1450 (if (= (aref data 0) replace-count)
1451 (progn
1452 (aset data 0 (+ replace-count (aref data 1)))
1453 (let ((next (cdr (aref data 2))))
1454 (aset data 2 (if (consp next) next (aref data 3))))))
1455 (car (aref data 2)))
1456
1457 (defun replace-match-data (integers reuse &optional new)
1458 "Like `match-data', but markers in REUSE get invalidated.
1459 If NEW is non-nil, it is set and returned instead of fresh data,
1460 but coerced to the correct value of INTEGERS."
1461 (or (and new
1462 (progn
1463 (set-match-data new)
1464 (and (eq new reuse)
1465 (eq (null integers) (markerp (car reuse)))
1466 new)))
1467 (match-data integers reuse t)))
1468
1469 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1470 "Make a replacement with `replace-match', editing `\\?'.
1471 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1472 check for `\\?' is made to save time. MATCH-DATA is used for the
1473 replacement. In case editing is done, it is changed to use markers.
1474
1475 The return value is non-nil if there has been no `\\?' or NOEDIT was
1476 passed in. If LITERAL is set, no checking is done, anyway."
1477 (unless (or literal noedit)
1478 (setq noedit t)
1479 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1480 newtext)
1481 (setq newtext
1482 (read-string "Edit replacement string: "
1483 (prog1
1484 (cons
1485 (replace-match "" t t newtext 3)
1486 (1+ (match-beginning 3)))
1487 (setq match-data
1488 (replace-match-data
1489 nil match-data match-data))))
1490 noedit nil)))
1491 (set-match-data match-data)
1492 (replace-match newtext fixedcase literal)
1493 noedit)
1494
1495 (defvar replace-search-function 'search-forward
1496 "Function to use when searching for strings to replace.
1497 It is used by `query-replace' and `replace-string', and is called
1498 with three arguments, as if it were `search-forward'.")
1499
1500 (defvar replace-re-search-function 're-search-forward
1501 "Function to use when searching for regexps to replace.
1502 It is used by `query-replace-regexp', `replace-regexp',
1503 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1504 It is called with three arguments, as if it were
1505 `re-search-forward'.")
1506
1507 (defun perform-replace (from-string replacements
1508 query-flag regexp-flag delimited-flag
1509 &optional repeat-count map start end)
1510 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1511 Don't use this in your own program unless you want to query and set the mark
1512 just as `query-replace' does. Instead, write a simple loop like this:
1513
1514 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1515 (replace-match \"foobar\" nil nil))
1516
1517 which will run faster and probably do exactly what you want. Please
1518 see the documentation of `replace-match' to find out how to simulate
1519 `case-replace'.
1520
1521 This function returns nil if and only if there were no matches to
1522 make, or the user didn't cancel the call."
1523 (or map (setq map query-replace-map))
1524 (and query-flag minibuffer-auto-raise
1525 (raise-frame (window-frame (minibuffer-window))))
1526 (let* ((case-fold-search
1527 (if (and case-fold-search search-upper-case)
1528 (isearch-no-upper-case-p from-string regexp-flag)
1529 case-fold-search))
1530 (nocasify (not (and case-replace case-fold-search)))
1531 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1532 (search-function
1533 (if regexp-flag
1534 replace-re-search-function
1535 replace-search-function))
1536 (search-string from-string)
1537 (real-match-data nil) ; The match data for the current match.
1538 (next-replacement nil)
1539 ;; This is non-nil if we know there is nothing for the user
1540 ;; to edit in the replacement.
1541 (noedit nil)
1542 (keep-going t)
1543 (stack nil)
1544 (replace-count 0)
1545 (nonempty-match nil)
1546 (multi-buffer nil)
1547
1548 ;; If non-nil, it is marker saying where in the buffer to stop.
1549 (limit nil)
1550
1551 ;; Data for the next match. If a cons, it has the same format as
1552 ;; (match-data); otherwise it is t if a match is possible at point.
1553 (match-again t)
1554
1555 (message
1556 (if query-flag
1557 (apply 'propertize
1558 (substitute-command-keys
1559 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1560 minibuffer-prompt-properties))))
1561
1562 ;; If region is active, in Transient Mark mode, operate on region.
1563 (when start
1564 (setq limit (copy-marker (max start end)))
1565 (goto-char (min start end))
1566 (deactivate-mark))
1567
1568 ;; If last typed key in previous call of multi-buffer perform-replace
1569 ;; was `automatic-all', don't ask more questions in next files
1570 (when (eq (lookup-key map (vector last-input-char)) 'automatic-all)
1571 (setq query-flag nil multi-buffer t))
1572
1573 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1574 ;; containing a function and its first argument. The function is
1575 ;; called to generate each replacement like this:
1576 ;; (funcall (car replacements) (cdr replacements) replace-count)
1577 ;; It must return a string.
1578 (cond
1579 ((stringp replacements)
1580 (setq next-replacement replacements
1581 replacements nil))
1582 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1583 (or repeat-count (setq repeat-count 1))
1584 (setq replacements (cons 'replace-loop-through-replacements
1585 (vector repeat-count repeat-count
1586 replacements replacements)))))
1587
1588 (if delimited-flag
1589 (setq search-function 're-search-forward
1590 search-string (concat "\\b"
1591 (if regexp-flag from-string
1592 (regexp-quote from-string))
1593 "\\b")))
1594 (when query-replace-lazy-highlight
1595 (setq isearch-lazy-highlight-last-string nil))
1596
1597 (push-mark)
1598 (undo-boundary)
1599 (unwind-protect
1600 ;; Loop finding occurrences that perhaps should be replaced.
1601 (while (and keep-going
1602 (not (or (eobp) (and limit (>= (point) limit))))
1603 ;; Use the next match if it is already known;
1604 ;; otherwise, search for a match after moving forward
1605 ;; one char if progress is required.
1606 (setq real-match-data
1607 (cond ((consp match-again)
1608 (goto-char (nth 1 match-again))
1609 (replace-match-data
1610 t real-match-data match-again))
1611 ;; MATCH-AGAIN non-nil means accept an
1612 ;; adjacent match.
1613 (match-again
1614 (and
1615 (funcall search-function search-string
1616 limit t)
1617 ;; For speed, use only integers and
1618 ;; reuse the list used last time.
1619 (replace-match-data t real-match-data)))
1620 ((and (< (1+ (point)) (point-max))
1621 (or (null limit)
1622 (< (1+ (point)) limit)))
1623 ;; If not accepting adjacent matches,
1624 ;; move one char to the right before
1625 ;; searching again. Undo the motion
1626 ;; if the search fails.
1627 (let ((opoint (point)))
1628 (forward-char 1)
1629 (if (funcall
1630 search-function search-string
1631 limit t)
1632 (replace-match-data
1633 t real-match-data)
1634 (goto-char opoint)
1635 nil))))))
1636
1637 ;; Record whether the match is nonempty, to avoid an infinite loop
1638 ;; repeatedly matching the same empty string.
1639 (setq nonempty-match
1640 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1641
1642 ;; If the match is empty, record that the next one can't be
1643 ;; adjacent.
1644
1645 ;; Otherwise, if matching a regular expression, do the next
1646 ;; match now, since the replacement for this match may
1647 ;; affect whether the next match is adjacent to this one.
1648 ;; If that match is empty, don't use it.
1649 (setq match-again
1650 (and nonempty-match
1651 (or (not regexp-flag)
1652 (and (looking-at search-string)
1653 (let ((match (match-data)))
1654 (and (/= (nth 0 match) (nth 1 match))
1655 match))))))
1656
1657 ;; Optionally ignore matches that have a read-only property.
1658 (unless (and query-replace-skip-read-only
1659 (text-property-not-all
1660 (nth 0 real-match-data) (nth 1 real-match-data)
1661 'read-only nil))
1662
1663 ;; Calculate the replacement string, if necessary.
1664 (when replacements
1665 (set-match-data real-match-data)
1666 (setq next-replacement
1667 (funcall (car replacements) (cdr replacements)
1668 replace-count)))
1669 (if (not query-flag)
1670 (progn
1671 (unless (or literal noedit)
1672 (replace-highlight
1673 (nth 0 real-match-data) (nth 1 real-match-data)
1674 start end search-string
1675 (or delimited-flag regexp-flag) case-fold-search))
1676 (setq noedit
1677 (replace-match-maybe-edit
1678 next-replacement nocasify literal
1679 noedit real-match-data)
1680 replace-count (1+ replace-count)))
1681 (undo-boundary)
1682 (let (done replaced key def)
1683 ;; Loop reading commands until one of them sets done,
1684 ;; which means it has finished handling this
1685 ;; occurrence. Any command that sets `done' should
1686 ;; leave behind proper match data for the stack.
1687 ;; Commands not setting `done' need to adjust
1688 ;; `real-match-data'.
1689 (while (not done)
1690 (set-match-data real-match-data)
1691 (replace-highlight
1692 (match-beginning 0) (match-end 0)
1693 start end search-string
1694 (or delimited-flag regexp-flag) case-fold-search)
1695 ;; Bind message-log-max so we don't fill up the message log
1696 ;; with a bunch of identical messages.
1697 (let ((message-log-max nil)
1698 (replacement-presentation
1699 (if query-replace-show-replacement
1700 (save-match-data
1701 (set-match-data real-match-data)
1702 (match-substitute-replacement next-replacement
1703 nocasify literal))
1704 next-replacement)))
1705 (message message
1706 (query-replace-descr from-string)
1707 (query-replace-descr replacement-presentation)))
1708 (setq key (read-event))
1709 ;; Necessary in case something happens during read-event
1710 ;; that clobbers the match data.
1711 (set-match-data real-match-data)
1712 (setq key (vector key))
1713 (setq def (lookup-key map key))
1714 ;; Restore the match data while we process the command.
1715 (cond ((eq def 'help)
1716 (with-output-to-temp-buffer "*Help*"
1717 (princ
1718 (concat "Query replacing "
1719 (if regexp-flag "regexp " "")
1720 from-string " with "
1721 next-replacement ".\n\n"
1722 (substitute-command-keys
1723 query-replace-help)))
1724 (with-current-buffer standard-output
1725 (help-mode))))
1726 ((eq def 'exit)
1727 (setq keep-going nil)
1728 (setq done t))
1729 ((eq def 'exit-current)
1730 (setq multi-buffer t keep-going nil done t))
1731 ((eq def 'backup)
1732 (if stack
1733 (let ((elt (pop stack)))
1734 (goto-char (nth 0 elt))
1735 (setq replaced (nth 1 elt)
1736 real-match-data
1737 (replace-match-data
1738 t real-match-data
1739 (nth 2 elt))))
1740 (message "No previous match")
1741 (ding 'no-terminate)
1742 (sit-for 1)))
1743 ((eq def 'act)
1744 (or replaced
1745 (setq noedit
1746 (replace-match-maybe-edit
1747 next-replacement nocasify literal
1748 noedit real-match-data)
1749 replace-count (1+ replace-count)))
1750 (setq done t replaced t))
1751 ((eq def 'act-and-exit)
1752 (or replaced
1753 (setq noedit
1754 (replace-match-maybe-edit
1755 next-replacement nocasify literal
1756 noedit real-match-data)
1757 replace-count (1+ replace-count)))
1758 (setq keep-going nil)
1759 (setq done t replaced t))
1760 ((eq def 'act-and-show)
1761 (if (not replaced)
1762 (setq noedit
1763 (replace-match-maybe-edit
1764 next-replacement nocasify literal
1765 noedit real-match-data)
1766 replace-count (1+ replace-count)
1767 real-match-data (replace-match-data
1768 t real-match-data)
1769 replaced t)))
1770 ((or (eq def 'automatic) (eq def 'automatic-all))
1771 (or replaced
1772 (setq noedit
1773 (replace-match-maybe-edit
1774 next-replacement nocasify literal
1775 noedit real-match-data)
1776 replace-count (1+ replace-count)))
1777 (setq done t query-flag nil replaced t)
1778 (if (eq def 'automatic-all) (setq multi-buffer t)))
1779 ((eq def 'skip)
1780 (setq done t))
1781 ((eq def 'recenter)
1782 (recenter nil))
1783 ((eq def 'edit)
1784 (let ((opos (point-marker)))
1785 (setq real-match-data (replace-match-data
1786 nil real-match-data
1787 real-match-data))
1788 (goto-char (match-beginning 0))
1789 (save-excursion
1790 (save-window-excursion
1791 (recursive-edit)))
1792 (goto-char opos)
1793 (set-marker opos nil))
1794 ;; Before we make the replacement,
1795 ;; decide whether the search string
1796 ;; can match again just after this match.
1797 (if (and regexp-flag nonempty-match)
1798 (setq match-again (and (looking-at search-string)
1799 (match-data)))))
1800 ;; Edit replacement.
1801 ((eq def 'edit-replacement)
1802 (setq real-match-data (replace-match-data
1803 nil real-match-data
1804 real-match-data)
1805 next-replacement
1806 (read-string "Edit replacement string: "
1807 next-replacement)
1808 noedit nil)
1809 (if replaced
1810 (set-match-data real-match-data)
1811 (setq noedit
1812 (replace-match-maybe-edit
1813 next-replacement nocasify literal noedit
1814 real-match-data)
1815 replaced t))
1816 (setq done t))
1817
1818 ((eq def 'delete-and-edit)
1819 (replace-match "" t t)
1820 (setq real-match-data (replace-match-data
1821 nil real-match-data))
1822 (replace-dehighlight)
1823 (save-excursion (recursive-edit))
1824 (setq replaced t))
1825 ;; Note: we do not need to treat `exit-prefix'
1826 ;; specially here, since we reread
1827 ;; any unrecognized character.
1828 (t
1829 (setq this-command 'mode-exited)
1830 (setq keep-going nil)
1831 (setq unread-command-events
1832 (append (listify-key-sequence key)
1833 unread-command-events))
1834 (setq done t)))
1835 (when query-replace-lazy-highlight
1836 ;; Force lazy rehighlighting only after replacements
1837 (if (not (memq def '(skip backup)))
1838 (setq isearch-lazy-highlight-last-string nil))))
1839 ;; Record previous position for ^ when we move on.
1840 ;; Change markers to numbers in the match data
1841 ;; since lots of markers slow down editing.
1842 (push (list (point) replaced
1843 ;;; If the replacement has already happened, all we need is the
1844 ;;; current match start and end. We could get this with a trivial
1845 ;;; match like
1846 ;;; (save-excursion (goto-char (match-beginning 0))
1847 ;;; (search-forward (match-string 0))
1848 ;;; (match-data t))
1849 ;;; if we really wanted to avoid manually constructing match data.
1850 ;;; Adding current-buffer is necessary so that match-data calls can
1851 ;;; return markers which are appropriate for editing.
1852 (if replaced
1853 (list
1854 (match-beginning 0)
1855 (match-end 0)
1856 (current-buffer))
1857 (match-data t)))
1858 stack)))))
1859
1860 (replace-dehighlight))
1861 (or unread-command-events
1862 (message "Replaced %d occurrence%s"
1863 replace-count
1864 (if (= replace-count 1) "" "s")))
1865 (or (and keep-going stack) multi-buffer)))
1866
1867 (defvar replace-overlay nil)
1868
1869 (defun replace-highlight (match-beg match-end range-beg range-end
1870 string regexp case-fold)
1871 (if query-replace-highlight
1872 (if replace-overlay
1873 (move-overlay replace-overlay match-beg match-end (current-buffer))
1874 (setq replace-overlay (make-overlay match-beg match-end))
1875 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
1876 (overlay-put replace-overlay 'face 'query-replace)))
1877 (if query-replace-lazy-highlight
1878 (let ((isearch-string string)
1879 (isearch-regexp regexp)
1880 (search-whitespace-regexp nil)
1881 (isearch-case-fold-search case-fold))
1882 (isearch-lazy-highlight-new-loop range-beg range-end))))
1883
1884 (defun replace-dehighlight ()
1885 (when replace-overlay
1886 (delete-overlay replace-overlay))
1887 (when query-replace-lazy-highlight
1888 (lazy-highlight-cleanup lazy-highlight-cleanup)
1889 (setq isearch-lazy-highlight-last-string nil)))
1890
1891 ;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1892 ;;; replace.el ends here