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