Add xref-pulse-on-jump
[emacs.git] / lisp / replace.el
blob8e71615ca14bba359e0967358a5e6a77a9eb8ca7
1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2015 Free
4 ;; Software Foundation, Inc.
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; This package supplies the string and regular-expression replace functions
27 ;; documented in the Emacs user's manual.
29 ;;; Code:
31 (defcustom case-replace t
32 "Non-nil means `query-replace' should preserve case in replacements."
33 :type 'boolean
34 :group 'matching)
36 (defcustom replace-lax-whitespace nil
37 "Non-nil means `query-replace' matches a sequence of whitespace chars.
38 When you enter a space or spaces in the strings to be replaced,
39 it will match any sequence matched by the regexp `search-whitespace-regexp'."
40 :type 'boolean
41 :group 'matching
42 :version "24.3")
44 (defcustom replace-regexp-lax-whitespace nil
45 "Non-nil means `query-replace-regexp' matches a sequence of whitespace chars.
46 When you enter a space or spaces in the regexps to be replaced,
47 it will match any sequence matched by the regexp `search-whitespace-regexp'."
48 :type 'boolean
49 :group 'matching
50 :version "24.3")
52 (defvar query-replace-history nil
53 "Default history list for query-replace commands.
54 See `query-replace-from-history-variable' and
55 `query-replace-to-history-variable'.")
57 (defvar query-replace-defaults nil
58 "Default values of FROM-STRING and TO-STRING for `query-replace'.
59 This is a list of cons cells (FROM-STRING . TO-STRING), or nil
60 if there are no default values.")
62 (defvar query-replace-interactive nil
63 "Non-nil means `query-replace' uses the last search string.
64 That becomes the \"string to replace\".")
65 (make-obsolete-variable 'query-replace-interactive
66 "use `M-n' to pull the last incremental search string
67 to the minibuffer that reads the string to replace, or invoke replacements
68 from Isearch by using a key sequence like `C-s C-s M-%'." "24.3")
70 (defcustom query-replace-from-to-separator
71 (propertize (if (char-displayable-p ?\u2192) " \u2192 " " -> ")
72 'face 'minibuffer-prompt)
73 "String that separates FROM and TO in the history of replacement pairs."
74 ;; Avoids error when attempt to autoload char-displayable-p fails
75 ;; while preparing to dump, also stops customize-rogue listing this.
76 :initialize 'custom-initialize-delay
77 :group 'matching
78 :type 'sexp
79 :version "25.1")
81 (defcustom query-replace-from-history-variable 'query-replace-history
82 "History list to use for the FROM argument of `query-replace' commands.
83 The value of this variable should be a symbol; that symbol
84 is used as a variable to hold a history list for the strings
85 or patterns to be replaced."
86 :group 'matching
87 :type 'symbol
88 :version "20.3")
90 (defcustom query-replace-to-history-variable 'query-replace-history
91 "History list to use for the TO argument of `query-replace' commands.
92 The value of this variable should be a symbol; that symbol
93 is used as a variable to hold a history list for replacement
94 strings or patterns."
95 :group 'matching
96 :type 'symbol
97 :version "20.3")
99 (defcustom query-replace-skip-read-only nil
100 "Non-nil means `query-replace' and friends ignore read-only matches."
101 :type 'boolean
102 :group 'matching
103 :version "22.1")
105 (defcustom query-replace-show-replacement t
106 "Non-nil means to show what actual replacement text will be."
107 :type 'boolean
108 :group 'matching
109 :version "23.1")
111 (defcustom query-replace-highlight t
112 "Non-nil means to highlight matches during query replacement."
113 :type 'boolean
114 :group 'matching)
116 (defcustom query-replace-lazy-highlight t
117 "Controls the lazy-highlighting during query replacements.
118 When non-nil, all text in the buffer matching the current match
119 is highlighted lazily using isearch lazy highlighting (see
120 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
121 :type 'boolean
122 :group 'lazy-highlight
123 :group 'matching
124 :version "22.1")
126 (defface query-replace
127 '((t (:inherit isearch)))
128 "Face for highlighting query replacement matches."
129 :group 'matching
130 :version "22.1")
132 (defvar replace-count 0
133 "Number of replacements done so far.
134 See `replace-regexp' and `query-replace-regexp-eval'.")
136 (defun query-replace-descr (string)
137 (mapconcat 'isearch-text-char-description string ""))
139 (defun query-replace-read-from (prompt regexp-flag)
140 "Query and return the `from' argument of a query-replace operation.
141 The return value can also be a pair (FROM . TO) indicating that the user
142 wants to replace FROM with TO."
143 (if query-replace-interactive
144 (car (if regexp-flag regexp-search-ring search-ring))
145 ;; Reevaluating will check char-displayable-p that is
146 ;; unavailable while preparing to dump.
147 (custom-reevaluate-setting 'query-replace-from-to-separator)
148 (let* ((history-add-new-input nil)
149 (separator
150 (when query-replace-from-to-separator
151 (propertize "\0"
152 'display query-replace-from-to-separator
153 'separator t)))
154 (query-replace-from-to-history
155 (append
156 (when separator
157 (mapcar (lambda (from-to)
158 (concat (query-replace-descr (car from-to))
159 separator
160 (query-replace-descr (cdr from-to))))
161 query-replace-defaults))
162 (symbol-value query-replace-from-history-variable)))
163 (minibuffer-allow-text-properties t) ; separator uses text-properties
164 (prompt
165 (if (and query-replace-defaults separator)
166 (format "%s (default %s): " prompt (car query-replace-from-to-history))
167 (format "%s: " prompt)))
168 (from
169 ;; The save-excursion here is in case the user marks and copies
170 ;; a region in order to specify the minibuffer input.
171 ;; That should not clobber the region for the query-replace itself.
172 (save-excursion
173 (if regexp-flag
174 (read-regexp prompt nil 'query-replace-from-to-history)
175 (read-from-minibuffer
176 prompt nil nil nil 'query-replace-from-to-history
177 (car (if regexp-flag regexp-search-ring search-ring)) t)))))
178 (if (and (zerop (length from)) query-replace-defaults)
179 (cons (caar query-replace-defaults)
180 (query-replace-compile-replacement
181 (cdar query-replace-defaults) regexp-flag))
182 (let* ((to (if (and (string-match separator from)
183 (get-text-property (match-beginning 0) 'separator from))
184 (substring-no-properties from (match-end 0))))
185 (from (if to (substring-no-properties from 0 (match-beginning 0))
186 (substring-no-properties from))))
187 (add-to-history query-replace-from-history-variable from nil t)
188 ;; Warn if user types \n or \t, but don't reject the input.
189 (and regexp-flag
190 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
191 (let ((match (match-string 3 from)))
192 (cond
193 ((string= match "\\n")
194 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
195 ((string= match "\\t")
196 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
197 (sit-for 2)))
198 (if (not to)
199 from
200 (add-to-history query-replace-to-history-variable to nil t)
201 (add-to-history 'query-replace-defaults (cons from to) nil t)
202 (cons from (query-replace-compile-replacement to regexp-flag))))))))
204 (defun query-replace-compile-replacement (to regexp-flag)
205 "Maybe convert a regexp replacement TO to Lisp.
206 Returns a list suitable for `perform-replace' if necessary,
207 the original string if not."
208 (if (and regexp-flag
209 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
210 (let (pos list char)
211 (while
212 (progn
213 (setq pos (match-end 0))
214 (push (substring to 0 (- pos 2)) list)
215 (setq char (aref to (1- pos))
216 to (substring to pos))
217 (cond ((eq char ?\#)
218 (push '(number-to-string replace-count) list))
219 ((eq char ?\,)
220 (setq pos (read-from-string to))
221 (push `(replace-quote ,(car pos)) list)
222 (let ((end
223 ;; Swallow a space after a symbol
224 ;; if there is a space.
225 (if (and (or (symbolp (car pos))
226 ;; Swallow a space after 'foo
227 ;; but not after (quote foo).
228 (and (eq (car-safe (car pos)) 'quote)
229 (not (= ?\( (aref to 0)))))
230 (eq (string-match " " to (cdr pos))
231 (cdr pos)))
232 (1+ (cdr pos))
233 (cdr pos))))
234 (setq to (substring to end)))))
235 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
236 (setq to (nreverse (delete "" (cons to list))))
237 (replace-match-string-symbols to)
238 (cons 'replace-eval-replacement
239 (if (cdr to)
240 (cons 'concat to)
241 (car to))))
242 to))
245 (defun query-replace-read-to (from prompt regexp-flag)
246 "Query and return the `to' argument of a query-replace operation."
247 (query-replace-compile-replacement
248 (save-excursion
249 (let* ((history-add-new-input nil)
250 (to (read-from-minibuffer
251 (format "%s %s with: " prompt (query-replace-descr from))
252 nil nil nil
253 query-replace-to-history-variable from t)))
254 (add-to-history query-replace-to-history-variable to nil t)
255 (add-to-history 'query-replace-defaults (cons from to) nil t)
256 to))
257 regexp-flag))
259 (defun query-replace-read-args (prompt regexp-flag &optional noerror)
260 (unless noerror
261 (barf-if-buffer-read-only))
262 (let* ((from (query-replace-read-from prompt regexp-flag))
263 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
264 (query-replace-read-to from prompt regexp-flag))))
265 (list from to
266 (and current-prefix-arg (not (eq current-prefix-arg '-)))
267 (and current-prefix-arg (eq current-prefix-arg '-)))))
269 (defun query-replace (from-string to-string &optional delimited start end backward)
270 "Replace some occurrences of FROM-STRING with TO-STRING.
271 As each match is found, the user must type a character saying
272 what to do with it. For directions, type \\[help-command] at that time.
274 In Transient Mark mode, if the mark is active, operate on the contents
275 of the region. Otherwise, operate from point to the end of the buffer.
277 Use \\<minibuffer-local-map>\\[next-history-element] \
278 to pull the last incremental search string to the minibuffer
279 that reads FROM-STRING, or invoke replacements from
280 incremental search with a key sequence like `C-s C-s M-%'
281 to use its current search string as the string to replace.
283 Matching is independent of case if `case-fold-search' is non-nil and
284 FROM-STRING has no uppercase letters. Replacement transfers the case
285 pattern of the old text to the new text, if `case-replace' and
286 `case-fold-search' are non-nil and FROM-STRING has no uppercase
287 letters. (Transferring the case pattern means that if the old text
288 matched is all caps, or capitalized, then its replacement is upcased
289 or capitalized.)
291 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
292 ignore hidden matches if `search-invisible' is nil, and ignore more
293 matches using `isearch-filter-predicate'.
295 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
296 to be replaced will match a sequence of whitespace chars defined by the
297 regexp in `search-whitespace-regexp'.
299 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
300 only matches surrounded by word boundaries. A negative prefix arg means
301 replace backward.
303 Fourth and fifth arg START and END specify the region to operate on.
305 To customize possible responses, change the bindings in `query-replace-map'."
306 (interactive
307 (let ((common
308 (query-replace-read-args
309 (concat "Query replace"
310 (if current-prefix-arg
311 (if (eq current-prefix-arg '-) " backward" " word")
313 (if (and transient-mark-mode mark-active) " in region" ""))
314 nil)))
315 (list (nth 0 common) (nth 1 common) (nth 2 common)
316 ;; These are done separately here
317 ;; so that command-history will record these expressions
318 ;; rather than the values they had this time.
319 (if (and transient-mark-mode mark-active)
320 (region-beginning))
321 (if (and transient-mark-mode mark-active)
322 (region-end))
323 (nth 3 common))))
324 (perform-replace from-string to-string t nil delimited nil nil start end backward))
326 (define-key esc-map "%" 'query-replace)
328 (defun query-replace-regexp (regexp to-string &optional delimited start end backward)
329 "Replace some things after point matching REGEXP with TO-STRING.
330 As each match is found, the user must type a character saying
331 what to do with it. For directions, type \\[help-command] at that time.
333 In Transient Mark mode, if the mark is active, operate on the contents
334 of the region. Otherwise, operate from point to the end of the buffer.
336 Use \\<minibuffer-local-map>\\[next-history-element] \
337 to pull the last incremental search regexp to the minibuffer
338 that reads REGEXP, or invoke replacements from
339 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
340 to use its current search regexp as the regexp to replace.
342 Matching is independent of case if `case-fold-search' is non-nil and
343 REGEXP has no uppercase letters. Replacement transfers the case
344 pattern of the old text to the new text, if `case-replace' and
345 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
346 \(Transferring the case pattern means that if the old text matched is
347 all caps, or capitalized, then its replacement is upcased or
348 capitalized.)
350 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
351 ignore hidden matches if `search-invisible' is nil, and ignore more
352 matches using `isearch-filter-predicate'.
354 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
355 to be replaced will match a sequence of whitespace chars defined by the
356 regexp in `search-whitespace-regexp'.
358 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
359 only matches surrounded by word boundaries. A negative prefix arg means
360 replace backward.
362 Fourth and fifth arg START and END specify the region to operate on.
364 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
365 and `\\=\\N' (where N is a digit) stands for
366 whatever what matched the Nth `\\(...\\)' in REGEXP.
367 `\\?' lets you edit the replacement text in the minibuffer
368 at the given position for each replacement.
370 In interactive calls, the replacement text can contain `\\,'
371 followed by a Lisp expression. Each
372 replacement evaluates that expression to compute the replacement
373 string. Inside of that expression, `\\&' is a string denoting the
374 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
375 for the whole or a partial match converted to a number with
376 `string-to-number', and `\\#' itself for the number of replacements
377 done so far (starting with zero).
379 If the replacement expression is a symbol, write a space after it
380 to terminate it. One space there, if any, will be discarded.
382 When using those Lisp features interactively in the replacement
383 text, TO-STRING is actually made a list instead of a string.
384 Use \\[repeat-complex-command] after this command for details."
385 (interactive
386 (let ((common
387 (query-replace-read-args
388 (concat "Query replace"
389 (if current-prefix-arg
390 (if (eq current-prefix-arg '-) " backward" " word")
392 " regexp"
393 (if (and transient-mark-mode mark-active) " in region" ""))
394 t)))
395 (list (nth 0 common) (nth 1 common) (nth 2 common)
396 ;; These are done separately here
397 ;; so that command-history will record these expressions
398 ;; rather than the values they had this time.
399 (if (and transient-mark-mode mark-active)
400 (region-beginning))
401 (if (and transient-mark-mode mark-active)
402 (region-end))
403 (nth 3 common))))
404 (perform-replace regexp to-string t t delimited nil nil start end backward))
406 (define-key esc-map [?\C-%] 'query-replace-regexp)
408 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
409 "Replace some things after point matching REGEXP with the result of TO-EXPR.
411 Interactive use of this function is deprecated in favor of the
412 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
413 using `search-forward-regexp' and `replace-match' is preferred.
415 As each match is found, the user must type a character saying
416 what to do with it. For directions, type \\[help-command] at that time.
418 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
419 reference `replace-count' to get the number of replacements already made.
420 If the result of TO-EXPR is not a string, it is converted to one using
421 `prin1-to-string' with the NOESCAPE argument (which see).
423 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
424 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
425 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
426 Use `\\#&' or `\\#N' if you want a number instead of a string.
427 In interactive use, `\\#' in itself stands for `replace-count'.
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.
432 Use \\<minibuffer-local-map>\\[next-history-element] \
433 to pull the last incremental search regexp to the minibuffer
434 that reads REGEXP.
436 Preserves case in each replacement if `case-replace' and `case-fold-search'
437 are non-nil and REGEXP has no uppercase letters.
439 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
440 ignore hidden matches if `search-invisible' is nil, and ignore more
441 matches using `isearch-filter-predicate'.
443 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
444 to be replaced will match a sequence of whitespace chars defined by the
445 regexp in `search-whitespace-regexp'.
447 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
448 only matches that are surrounded by word boundaries.
449 Fourth and fifth arg START and END specify the region to operate on."
450 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
451 for interactive calls, and `search-forward-regexp'/`replace-match'
452 for Lisp calls." "22.1"))
453 (interactive
454 (progn
455 (barf-if-buffer-read-only)
456 (let* ((from
457 ;; Let-bind the history var to disable the "foo -> bar"
458 ;; default. Maybe we shouldn't disable this default, but
459 ;; for now I'll leave it off. --Stef
460 (let ((query-replace-defaults nil))
461 (query-replace-read-from "Query replace regexp" t)))
462 (to (list (read-from-minibuffer
463 (format "Query replace regexp %s with eval: "
464 (query-replace-descr from))
465 nil nil t query-replace-to-history-variable from t))))
466 ;; We make TO a list because replace-match-string-symbols requires one,
467 ;; and the user might enter a single token.
468 (replace-match-string-symbols to)
469 (list from (car to) current-prefix-arg
470 (if (and transient-mark-mode mark-active)
471 (region-beginning))
472 (if (and transient-mark-mode mark-active)
473 (region-end))))))
474 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
475 t 'literal delimited nil nil start end))
477 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
478 "Replace some matches for REGEXP with various strings, in rotation.
479 The second argument TO-STRINGS contains the replacement strings, separated
480 by spaces. This command works like `query-replace-regexp' except that
481 each successive replacement uses the next successive replacement string,
482 wrapping around from the last such string to the first.
484 In Transient Mark mode, if the mark is active, operate on the contents
485 of the region. Otherwise, operate from point to the end of the buffer.
487 Non-interactively, TO-STRINGS may be a list of replacement strings.
489 Interactively, reads the regexp using `read-regexp'.
490 Use \\<minibuffer-local-map>\\[next-history-element] \
491 to pull the last incremental search regexp to the minibuffer
492 that reads REGEXP.
494 A prefix argument N says to use each replacement string N times
495 before rotating to the next.
496 Fourth and fifth arg START and END specify the region to operate on."
497 (interactive
498 (let* ((from (read-regexp "Map query replace (regexp): " nil
499 query-replace-from-history-variable))
500 (to (read-from-minibuffer
501 (format "Query replace %s with (space-separated strings): "
502 (query-replace-descr from))
503 nil nil nil
504 query-replace-to-history-variable from t)))
505 (list from to
506 (and current-prefix-arg
507 (prefix-numeric-value current-prefix-arg))
508 (if (and transient-mark-mode mark-active)
509 (region-beginning))
510 (if (and transient-mark-mode mark-active)
511 (region-end)))))
512 (let (replacements)
513 (if (listp to-strings)
514 (setq replacements to-strings)
515 (while (/= (length to-strings) 0)
516 (if (string-match " " to-strings)
517 (setq replacements
518 (append replacements
519 (list (substring to-strings 0
520 (string-match " " to-strings))))
521 to-strings (substring to-strings
522 (1+ (string-match " " to-strings))))
523 (setq replacements (append replacements (list to-strings))
524 to-strings ""))))
525 (perform-replace regexp replacements t t nil n nil start end)))
527 (defun replace-string (from-string to-string &optional delimited start end backward)
528 "Replace occurrences of FROM-STRING with TO-STRING.
529 Preserve case in each match if `case-replace' and `case-fold-search'
530 are non-nil and FROM-STRING has no uppercase letters.
531 \(Preserving case means that if the string matched is all caps, or capitalized,
532 then its replacement is upcased or capitalized.)
534 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
535 ignore hidden matches if `search-invisible' is nil, and ignore more
536 matches using `isearch-filter-predicate'.
538 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
539 to be replaced will match a sequence of whitespace chars defined by the
540 regexp in `search-whitespace-regexp'.
542 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
543 only matches surrounded by word boundaries. A negative prefix arg means
544 replace backward.
546 Operates on the region between START and END (if both are nil, from point
547 to the end of the buffer). Interactively, if Transient Mark mode is
548 enabled and the mark is active, operates on the contents of the region;
549 otherwise from point to the end of the buffer.
551 Use \\<minibuffer-local-map>\\[next-history-element] \
552 to pull the last incremental search string to the minibuffer
553 that reads FROM-STRING.
555 This function is usually the wrong thing to use in a Lisp program.
556 What you probably want is a loop like this:
557 (while (search-forward FROM-STRING nil t)
558 (replace-match TO-STRING nil t))
559 which will run faster and will not set the mark or print anything.
560 \(You may need a more complex loop if FROM-STRING can match the null string
561 and TO-STRING is also null.)"
562 (declare (interactive-only
563 "use `search-forward' and `replace-match' instead."))
564 (interactive
565 (let ((common
566 (query-replace-read-args
567 (concat "Replace"
568 (if current-prefix-arg
569 (if (eq current-prefix-arg '-) " backward" " word")
571 " string"
572 (if (and transient-mark-mode mark-active) " in region" ""))
573 nil)))
574 (list (nth 0 common) (nth 1 common) (nth 2 common)
575 (if (and transient-mark-mode mark-active)
576 (region-beginning))
577 (if (and transient-mark-mode mark-active)
578 (region-end))
579 (nth 3 common))))
580 (perform-replace from-string to-string nil nil delimited nil nil start end backward))
582 (defun replace-regexp (regexp to-string &optional delimited start end backward)
583 "Replace things after point matching REGEXP with TO-STRING.
584 Preserve case in each match if `case-replace' and `case-fold-search'
585 are non-nil and REGEXP has no uppercase letters.
587 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
588 ignore hidden matches if `search-invisible' is nil, and ignore more
589 matches using `isearch-filter-predicate'.
591 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
592 to be replaced will match a sequence of whitespace chars defined by the
593 regexp in `search-whitespace-regexp'.
595 In Transient Mark mode, if the mark is active, operate on the contents
596 of the region. Otherwise, operate from point to the end of the buffer.
598 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
599 only matches surrounded by word boundaries. A negative prefix arg means
600 replace backward.
602 Fourth and fifth arg START and END specify the region to operate on.
604 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
605 and `\\=\\N' (where N is a digit) stands for
606 whatever what matched the Nth `\\(...\\)' in REGEXP.
607 `\\?' lets you edit the replacement text in the minibuffer
608 at the given position for each replacement.
610 In interactive calls, the replacement text may contain `\\,'
611 followed by a Lisp expression used as part of the replacement
612 text. Inside of that expression, `\\&' is a string denoting the
613 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
614 numeric values from `string-to-number', and `\\#' itself for
615 `replace-count', the number of replacements occurred so far.
617 If your Lisp expression is an identifier and the next letter in
618 the replacement string would be interpreted as part of it, you
619 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
620 for this particular case you may also enter `\\#' in the
621 replacement text directly.
623 When using those Lisp features interactively in the replacement
624 text, TO-STRING is actually made a list instead of a string.
625 Use \\[repeat-complex-command] after this command for details.
627 Use \\<minibuffer-local-map>\\[next-history-element] \
628 to pull the last incremental search regexp to the minibuffer
629 that reads REGEXP.
631 This function is usually the wrong thing to use in a Lisp program.
632 What you probably want is a loop like this:
633 (while (re-search-forward REGEXP nil t)
634 (replace-match TO-STRING nil nil))
635 which will run faster and will not set the mark or print anything."
636 (declare (interactive-only
637 "use `re-search-forward' and `replace-match' instead."))
638 (interactive
639 (let ((common
640 (query-replace-read-args
641 (concat "Replace"
642 (if current-prefix-arg
643 (if (eq current-prefix-arg '-) " backward" " word")
645 " regexp"
646 (if (and transient-mark-mode mark-active) " in region" ""))
647 t)))
648 (list (nth 0 common) (nth 1 common) (nth 2 common)
649 (if (and transient-mark-mode mark-active)
650 (region-beginning))
651 (if (and transient-mark-mode mark-active)
652 (region-end))
653 (nth 3 common))))
654 (perform-replace regexp to-string nil t delimited nil nil start end backward))
657 (defvar regexp-history nil
658 "History list for some commands that read regular expressions.
660 Maximum length of the history list is determined by the value
661 of `history-length', which see.")
663 (defvar occur-collect-regexp-history '("\\1")
664 "History of regexp for occur's collect operation")
666 (defcustom read-regexp-defaults-function nil
667 "Function that provides default regexp(s) for `read-regexp'.
668 This function should take no arguments and return one of: nil, a
669 regexp, or a list of regexps. Interactively, `read-regexp' uses
670 the return value of this function for its DEFAULT argument.
672 As an example, set this variable to `find-tag-default-as-regexp'
673 to default to the symbol at point.
675 To provide different default regexps for different commands,
676 the function that you set this to can check `this-command'."
677 :type '(choice
678 (const :tag "No default regexp reading function" nil)
679 (const :tag "Latest regexp history" regexp-history-last)
680 (function-item :tag "Tag at point"
681 find-tag-default)
682 (function-item :tag "Tag at point as regexp"
683 find-tag-default-as-regexp)
684 (function-item :tag "Tag at point as symbol regexp"
685 find-tag-default-as-symbol-regexp)
686 (function :tag "Your choice of function"))
687 :group 'matching
688 :version "24.4")
690 (defun read-regexp-suggestions ()
691 "Return a list of standard suggestions for `read-regexp'.
692 By default, the list includes the tag at point, the last isearch regexp,
693 the last isearch string, and the last replacement regexp. `read-regexp'
694 appends the list returned by this function to the end of values available
695 via \\<minibuffer-local-map>\\[next-history-element]."
696 (list
697 (find-tag-default-as-regexp)
698 (find-tag-default-as-symbol-regexp)
699 (car regexp-search-ring)
700 (regexp-quote (or (car search-ring) ""))
701 (car (symbol-value query-replace-from-history-variable))))
703 (defun read-regexp (prompt &optional defaults history)
704 "Read and return a regular expression as a string.
705 Prompt with the string PROMPT. If PROMPT ends in \":\" (followed by
706 optional whitespace), use it as-is. Otherwise, add \": \" to the end,
707 possibly preceded by the default result (see below).
709 The optional argument DEFAULTS can be either: nil, a string, a list
710 of strings, or a symbol. We use DEFAULTS to construct the default
711 return value in case of empty input.
713 If DEFAULTS is a string, we use it as-is.
715 If DEFAULTS is a list of strings, the first element is the
716 default return value, but all the elements are accessible
717 using the history command \\<minibuffer-local-map>\\[next-history-element].
719 If DEFAULTS is a non-nil symbol, then if `read-regexp-defaults-function'
720 is non-nil, we use that in place of DEFAULTS in the following:
721 If DEFAULTS is the symbol `regexp-history-last', we use the first
722 element of HISTORY (if specified) or `regexp-history'.
723 If DEFAULTS is a function, we call it with no arguments and use
724 what it returns, which should be either nil, a string, or a list of strings.
726 We append the standard values from `read-regexp-suggestions' to DEFAULTS
727 before using it.
729 If the first element of DEFAULTS is non-nil (and if PROMPT does not end
730 in \":\", followed by optional whitespace), we add it to the prompt.
732 The optional argument HISTORY is a symbol to use for the history list.
733 If nil, uses `regexp-history'."
734 (let* ((defaults
735 (if (and defaults (symbolp defaults))
736 (cond
737 ((eq (or read-regexp-defaults-function defaults)
738 'regexp-history-last)
739 (car (symbol-value (or history 'regexp-history))))
740 ((functionp (or read-regexp-defaults-function defaults))
741 (funcall (or read-regexp-defaults-function defaults))))
742 defaults))
743 (default (if (consp defaults) (car defaults) defaults))
744 (suggestions (if (listp defaults) defaults (list defaults)))
745 (suggestions (append suggestions (read-regexp-suggestions)))
746 (suggestions (delete-dups (delq nil (delete "" suggestions))))
747 ;; Do not automatically add default to the history for empty input.
748 (history-add-new-input nil)
749 (input (read-from-minibuffer
750 (cond ((string-match-p ":[ \t]*\\'" prompt)
751 prompt)
752 ((and default (> (length default) 0))
753 (format "%s (default %s): " prompt
754 (query-replace-descr default)))
756 (format "%s: " prompt)))
757 nil nil nil (or history 'regexp-history) suggestions t)))
758 (if (equal input "")
759 ;; Return the default value when the user enters empty input.
760 (prog1 (or default input)
761 (when default
762 (add-to-history (or history 'regexp-history) default)))
763 ;; Otherwise, add non-empty input to the history and return input.
764 (prog1 input
765 (add-to-history (or history 'regexp-history) input)))))
768 (defalias 'delete-non-matching-lines 'keep-lines)
769 (defalias 'delete-matching-lines 'flush-lines)
770 (defalias 'count-matches 'how-many)
773 (defun keep-lines-read-args (prompt)
774 "Read arguments for `keep-lines' and friends.
775 Prompt for a regexp with PROMPT.
776 Value is a list, (REGEXP)."
777 (list (read-regexp prompt) nil nil t))
779 (defun keep-lines (regexp &optional rstart rend interactive)
780 "Delete all lines except those containing matches for REGEXP.
781 A match split across lines preserves all the lines it lies in.
782 When called from Lisp (and usually interactively as well, see below)
783 applies to all lines starting after point.
785 If REGEXP contains upper case characters (excluding those preceded by `\\')
786 and `search-upper-case' is non-nil, the matching is case-sensitive.
788 Second and third arg RSTART and REND specify the region to operate on.
789 This command operates on (the accessible part of) all lines whose
790 accessible part is entirely contained in the region determined by RSTART
791 and REND. (A newline ending a line counts as part of that line.)
793 Interactively, in Transient Mark mode when the mark is active, operate
794 on all lines whose accessible part is entirely contained in the region.
795 Otherwise, the command applies to all lines starting after point.
796 When calling this function from Lisp, you can pretend that it was
797 called interactively by passing a non-nil INTERACTIVE argument.
799 This function starts looking for the next match from the end of
800 the previous match. Hence, it ignores matches that overlap
801 a previously found match."
803 (interactive
804 (progn
805 (barf-if-buffer-read-only)
806 (keep-lines-read-args "Keep lines containing match for regexp")))
807 (if rstart
808 (progn
809 (goto-char (min rstart rend))
810 (setq rend
811 (progn
812 (save-excursion
813 (goto-char (max rstart rend))
814 (unless (or (bolp) (eobp))
815 (forward-line 0))
816 (point-marker)))))
817 (if (and interactive transient-mark-mode mark-active)
818 (setq rstart (region-beginning)
819 rend (progn
820 (goto-char (region-end))
821 (unless (or (bolp) (eobp))
822 (forward-line 0))
823 (point-marker)))
824 (setq rstart (point)
825 rend (point-max-marker)))
826 (goto-char rstart))
827 (save-excursion
828 (or (bolp) (forward-line 1))
829 (let ((start (point))
830 (case-fold-search
831 (if (and case-fold-search search-upper-case)
832 (isearch-no-upper-case-p regexp t)
833 case-fold-search)))
834 (while (< (point) rend)
835 ;; Start is first char not preserved by previous match.
836 (if (not (re-search-forward regexp rend 'move))
837 (delete-region start rend)
838 (let ((end (save-excursion (goto-char (match-beginning 0))
839 (forward-line 0)
840 (point))))
841 ;; Now end is first char preserved by the new match.
842 (if (< start end)
843 (delete-region start end))))
845 (setq start (save-excursion (forward-line 1) (point)))
846 ;; If the match was empty, avoid matching again at same place.
847 (and (< (point) rend)
848 (= (match-beginning 0) (match-end 0))
849 (forward-char 1)))))
850 (set-marker rend nil)
851 nil)
854 (defun flush-lines (regexp &optional rstart rend interactive)
855 "Delete lines containing matches for REGEXP.
856 When called from Lisp (and usually when called interactively as
857 well, see below), applies to the part of the buffer after point.
858 The line point is in is deleted if and only if it contains a
859 match for regexp starting after point.
861 If REGEXP contains upper case characters (excluding those preceded by `\\')
862 and `search-upper-case' is non-nil, the matching is case-sensitive.
864 Second and third arg RSTART and REND specify the region to operate on.
865 Lines partially contained in this region are deleted if and only if
866 they contain a match entirely contained in it.
868 Interactively, in Transient Mark mode when the mark is active, operate
869 on the contents of the region. Otherwise, operate from point to the
870 end of (the accessible portion of) the buffer. When calling this function
871 from Lisp, you can pretend that it was called interactively by passing
872 a non-nil INTERACTIVE argument.
874 If a match is split across lines, all the lines it lies in are deleted.
875 They are deleted _before_ looking for the next match. Hence, a match
876 starting on the same line at which another match ended is ignored."
878 (interactive
879 (progn
880 (barf-if-buffer-read-only)
881 (keep-lines-read-args "Flush lines containing match for regexp")))
882 (if rstart
883 (progn
884 (goto-char (min rstart rend))
885 (setq rend (copy-marker (max rstart rend))))
886 (if (and interactive transient-mark-mode mark-active)
887 (setq rstart (region-beginning)
888 rend (copy-marker (region-end)))
889 (setq rstart (point)
890 rend (point-max-marker)))
891 (goto-char rstart))
892 (let ((case-fold-search
893 (if (and case-fold-search search-upper-case)
894 (isearch-no-upper-case-p regexp t)
895 case-fold-search)))
896 (save-excursion
897 (while (and (< (point) rend)
898 (re-search-forward regexp rend t))
899 (delete-region (save-excursion (goto-char (match-beginning 0))
900 (forward-line 0)
901 (point))
902 (progn (forward-line 1) (point))))))
903 (set-marker rend nil)
904 nil)
907 (defun how-many (regexp &optional rstart rend interactive)
908 "Print and return number of matches for REGEXP following point.
909 When called from Lisp and INTERACTIVE is omitted or nil, just return
910 the number, do not print it; if INTERACTIVE is t, the function behaves
911 in all respects as if it had been called interactively.
913 If REGEXP contains upper case characters (excluding those preceded by `\\')
914 and `search-upper-case' is non-nil, the matching is case-sensitive.
916 Second and third arg RSTART and REND specify the region to operate on.
918 Interactively, in Transient Mark mode when the mark is active, operate
919 on the contents of the region. Otherwise, operate from point to the
920 end of (the accessible portion of) the buffer.
922 This function starts looking for the next match from the end of
923 the previous match. Hence, it ignores matches that overlap
924 a previously found match."
926 (interactive
927 (keep-lines-read-args "How many matches for regexp"))
928 (save-excursion
929 (if rstart
930 (if rend
931 (progn
932 (goto-char (min rstart rend))
933 (setq rend (max rstart rend)))
934 (goto-char rstart)
935 (setq rend (point-max)))
936 (if (and interactive transient-mark-mode mark-active)
937 (setq rstart (region-beginning)
938 rend (region-end))
939 (setq rstart (point)
940 rend (point-max)))
941 (goto-char rstart))
942 (let ((count 0)
943 opoint
944 (case-fold-search
945 (if (and case-fold-search search-upper-case)
946 (isearch-no-upper-case-p regexp t)
947 case-fold-search)))
948 (while (and (< (point) rend)
949 (progn (setq opoint (point))
950 (re-search-forward regexp rend t)))
951 (if (= opoint (point))
952 (forward-char 1)
953 (setq count (1+ count))))
954 (when interactive (message "%d occurrence%s"
955 count
956 (if (= count 1) "" "s")))
957 count)))
960 (defvar occur-menu-map
961 (let ((map (make-sparse-keymap)))
962 (bindings--define-key map [next-error-follow-minor-mode]
963 '(menu-item "Auto Occurrence Display"
964 next-error-follow-minor-mode
965 :help "Display another occurrence when moving the cursor"
966 :button (:toggle . (and (boundp 'next-error-follow-minor-mode)
967 next-error-follow-minor-mode))))
968 (bindings--define-key map [separator-1] menu-bar-separator)
969 (bindings--define-key map [kill-this-buffer]
970 '(menu-item "Kill Occur Buffer" kill-this-buffer
971 :help "Kill the current *Occur* buffer"))
972 (bindings--define-key map [quit-window]
973 '(menu-item "Quit Occur Window" quit-window
974 :help "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
975 (bindings--define-key map [revert-buffer]
976 '(menu-item "Revert Occur Buffer" revert-buffer
977 :help "Replace the text in the *Occur* buffer with the results of rerunning occur"))
978 (bindings--define-key map [clone-buffer]
979 '(menu-item "Clone Occur Buffer" clone-buffer
980 :help "Create and return a twin copy of the current *Occur* buffer"))
981 (bindings--define-key map [occur-rename-buffer]
982 '(menu-item "Rename Occur Buffer" occur-rename-buffer
983 :help "Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
984 (bindings--define-key map [occur-edit-buffer]
985 '(menu-item "Edit Occur Buffer" occur-edit-mode
986 :help "Edit the *Occur* buffer and apply changes to the original buffers."))
987 (bindings--define-key map [separator-2] menu-bar-separator)
988 (bindings--define-key map [occur-mode-goto-occurrence-other-window]
989 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
990 :help "Go to the occurrence the current line describes, in another window"))
991 (bindings--define-key map [occur-mode-goto-occurrence]
992 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
993 :help "Go to the occurrence the current line describes"))
994 (bindings--define-key map [occur-mode-display-occurrence]
995 '(menu-item "Display Occurrence" occur-mode-display-occurrence
996 :help "Display in another window the occurrence the current line describes"))
997 (bindings--define-key map [occur-next]
998 '(menu-item "Move to Next Match" occur-next
999 :help "Move to the Nth (default 1) next match in an Occur mode buffer"))
1000 (bindings--define-key map [occur-prev]
1001 '(menu-item "Move to Previous Match" occur-prev
1002 :help "Move to the Nth (default 1) previous match in an Occur mode buffer"))
1003 map)
1004 "Menu keymap for `occur-mode'.")
1006 (defvar occur-mode-map
1007 (let ((map (make-sparse-keymap)))
1008 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
1009 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1010 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
1011 (define-key map "e" 'occur-edit-mode)
1012 (define-key map "\C-m" 'occur-mode-goto-occurrence)
1013 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
1014 (define-key map "\C-o" 'occur-mode-display-occurrence)
1015 (define-key map "\M-n" 'occur-next)
1016 (define-key map "\M-p" 'occur-prev)
1017 (define-key map "r" 'occur-rename-buffer)
1018 (define-key map "c" 'clone-buffer)
1019 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1020 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1021 map)
1022 "Keymap for `occur-mode'.")
1024 (defvar occur-revert-arguments nil
1025 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
1026 See `occur-revert-function'.")
1027 (make-variable-buffer-local 'occur-revert-arguments)
1028 (put 'occur-revert-arguments 'permanent-local t)
1030 (defcustom occur-mode-hook '(turn-on-font-lock)
1031 "Hook run when entering Occur mode."
1032 :type 'hook
1033 :group 'matching)
1035 (defcustom occur-hook nil
1036 "Hook run by Occur when there are any matches."
1037 :type 'hook
1038 :group 'matching)
1040 (defcustom occur-mode-find-occurrence-hook nil
1041 "Hook run by Occur after locating an occurrence.
1042 This will be called with the cursor position at the occurrence. An application
1043 for this is to reveal context in an outline-mode when the occurrence is hidden."
1044 :type 'hook
1045 :group 'matching)
1047 (put 'occur-mode 'mode-class 'special)
1048 (define-derived-mode occur-mode special-mode "Occur"
1049 "Major mode for output from \\[occur].
1050 \\<occur-mode-map>Move point to one of the items in this buffer, then use
1051 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
1052 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
1054 \\{occur-mode-map}"
1055 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
1056 (setq next-error-function 'occur-next-error))
1059 ;;; Occur Edit mode
1061 (defvar occur-edit-mode-map
1062 (let ((map (make-sparse-keymap)))
1063 (set-keymap-parent map text-mode-map)
1064 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1065 (define-key map "\C-c\C-c" 'occur-cease-edit)
1066 (define-key map "\C-o" 'occur-mode-display-occurrence)
1067 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1068 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1069 map)
1070 "Keymap for `occur-edit-mode'.")
1072 (define-derived-mode occur-edit-mode occur-mode "Occur-Edit"
1073 "Major mode for editing *Occur* buffers.
1074 In this mode, changes to the *Occur* buffer are also applied to
1075 the originating buffer.
1077 To return to ordinary Occur mode, use \\[occur-cease-edit]."
1078 (setq buffer-read-only nil)
1079 (add-hook 'after-change-functions 'occur-after-change-function nil t)
1080 (message (substitute-command-keys
1081 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
1083 (defun occur-cease-edit ()
1084 "Switch from Occur Edit mode to Occur mode."
1085 (interactive)
1086 (when (derived-mode-p 'occur-edit-mode)
1087 (occur-mode)
1088 (message "Switching to Occur mode.")))
1090 (defun occur-after-change-function (beg end length)
1091 (save-excursion
1092 (goto-char beg)
1093 (let* ((line-beg (line-beginning-position))
1094 (m (get-text-property line-beg 'occur-target))
1095 (buf (marker-buffer m))
1096 col)
1097 (when (and (get-text-property line-beg 'occur-prefix)
1098 (not (get-text-property end 'occur-prefix)))
1099 (when (= length 0)
1100 ;; Apply occur-target property to inserted (e.g. yanked) text.
1101 (put-text-property beg end 'occur-target m)
1102 ;; Did we insert a newline? Occur Edit mode can't create new
1103 ;; Occur entries; just discard everything after the newline.
1104 (save-excursion
1105 (and (search-forward "\n" end t)
1106 (delete-region (1- (point)) end))))
1107 (let* ((line (- (line-number-at-pos)
1108 (line-number-at-pos (window-start))))
1109 (readonly (with-current-buffer buf buffer-read-only))
1110 (win (or (get-buffer-window buf)
1111 (display-buffer buf
1112 '(nil (inhibit-same-window . t)
1113 (inhibit-switch-frame . t)))))
1114 (line-end (line-end-position))
1115 (text (save-excursion
1116 (goto-char (next-single-property-change
1117 line-beg 'occur-prefix nil
1118 line-end))
1119 (setq col (- (point) line-beg))
1120 (buffer-substring-no-properties (point) line-end))))
1121 (with-selected-window win
1122 (goto-char m)
1123 (recenter line)
1124 (if readonly
1125 (message "Buffer `%s' is read only." buf)
1126 (delete-region (line-beginning-position) (line-end-position))
1127 (insert text))
1128 (move-to-column col)))))))
1131 (defun occur-revert-function (_ignore1 _ignore2)
1132 "Handle `revert-buffer' for Occur mode buffers."
1133 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
1135 (defun occur-mode-find-occurrence ()
1136 (let ((pos (get-text-property (point) 'occur-target)))
1137 (unless pos
1138 (error "No occurrence on this line"))
1139 (unless (buffer-live-p (marker-buffer pos))
1140 (error "Buffer for this occurrence was killed"))
1141 pos))
1143 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
1144 (defun occur-mode-goto-occurrence (&optional event)
1145 "Go to the occurrence on the current line."
1146 (interactive (list last-nonmenu-event))
1147 (let ((pos
1148 (if (null event)
1149 ;; Actually `event-end' works correctly with a nil argument as
1150 ;; well, so we could dispense with this test, but let's not
1151 ;; rely on this undocumented behavior.
1152 (occur-mode-find-occurrence)
1153 (with-current-buffer (window-buffer (posn-window (event-end event)))
1154 (save-excursion
1155 (goto-char (posn-point (event-end event)))
1156 (occur-mode-find-occurrence))))))
1157 (pop-to-buffer (marker-buffer pos))
1158 (goto-char pos)
1159 (run-hooks 'occur-mode-find-occurrence-hook)))
1161 (defun occur-mode-goto-occurrence-other-window ()
1162 "Go to the occurrence the current line describes, in another window."
1163 (interactive)
1164 (let ((pos (occur-mode-find-occurrence)))
1165 (switch-to-buffer-other-window (marker-buffer pos))
1166 (goto-char pos)
1167 (run-hooks 'occur-mode-find-occurrence-hook)))
1169 (defun occur-mode-display-occurrence ()
1170 "Display in another window the occurrence the current line describes."
1171 (interactive)
1172 (let ((pos (occur-mode-find-occurrence))
1173 window)
1174 (setq window (display-buffer (marker-buffer pos) t))
1175 ;; This is the way to set point in the proper window.
1176 (save-selected-window
1177 (select-window window)
1178 (goto-char pos)
1179 (run-hooks 'occur-mode-find-occurrence-hook))))
1181 (defun occur-find-match (n search message)
1182 (if (not n) (setq n 1))
1183 (let ((r))
1184 (while (> n 0)
1185 (setq r (funcall search (point) 'occur-match))
1186 (and r
1187 (get-text-property r 'occur-match)
1188 (setq r (funcall search r 'occur-match)))
1189 (if r
1190 (goto-char r)
1191 (error message))
1192 (setq n (1- n)))))
1194 (defun occur-next (&optional n)
1195 "Move to the Nth (default 1) next match in an Occur mode buffer."
1196 (interactive "p")
1197 (occur-find-match n #'next-single-property-change "No more matches"))
1199 (defun occur-prev (&optional n)
1200 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1201 (interactive "p")
1202 (occur-find-match n #'previous-single-property-change "No earlier matches"))
1204 (defun occur-next-error (&optional argp reset)
1205 "Move to the Nth (default 1) next match in an Occur mode buffer.
1206 Compatibility function for \\[next-error] invocations."
1207 (interactive "p")
1208 ;; we need to run occur-find-match from within the Occur buffer
1209 (with-current-buffer
1210 ;; Choose the buffer and make it current.
1211 (if (next-error-buffer-p (current-buffer))
1212 (current-buffer)
1213 (next-error-find-buffer nil nil
1214 (lambda ()
1215 (eq major-mode 'occur-mode))))
1217 (goto-char (cond (reset (point-min))
1218 ((< argp 0) (line-beginning-position))
1219 ((> argp 0) (line-end-position))
1220 ((point))))
1221 (occur-find-match
1222 (abs argp)
1223 (if (> 0 argp)
1224 #'previous-single-property-change
1225 #'next-single-property-change)
1226 "No more matches")
1227 ;; In case the *Occur* buffer is visible in a nonselected window.
1228 (let ((win (get-buffer-window (current-buffer) t)))
1229 (if win (set-window-point win (point))))
1230 (occur-mode-goto-occurrence)))
1232 (defface match
1233 '((((class color) (min-colors 88) (background light))
1234 :background "yellow1")
1235 (((class color) (min-colors 88) (background dark))
1236 :background "RoyalBlue3")
1237 (((class color) (min-colors 8) (background light))
1238 :background "yellow" :foreground "black")
1239 (((class color) (min-colors 8) (background dark))
1240 :background "blue" :foreground "white")
1241 (((type tty) (class mono))
1242 :inverse-video t)
1243 (t :background "gray"))
1244 "Face used to highlight matches permanently."
1245 :group 'matching
1246 :version "22.1")
1248 (defcustom list-matching-lines-default-context-lines 0
1249 "Default number of context lines included around `list-matching-lines' matches.
1250 A negative number means to include that many lines before the match.
1251 A positive number means to include that many lines both before and after."
1252 :type 'integer
1253 :group 'matching)
1255 (defalias 'list-matching-lines 'occur)
1257 (defcustom list-matching-lines-face 'match
1258 "Face used by \\[list-matching-lines] to show the text that matches.
1259 If the value is nil, don't highlight the matching portions specially."
1260 :type 'face
1261 :group 'matching)
1263 (defcustom list-matching-lines-buffer-name-face 'underline
1264 "Face used by \\[list-matching-lines] to show the names of buffers.
1265 If the value is nil, don't highlight the buffer names specially."
1266 :type 'face
1267 :group 'matching)
1269 (defcustom list-matching-lines-prefix-face 'shadow
1270 "Face used by \\[list-matching-lines] to show the prefix column.
1271 If the face doesn't differ from the default face,
1272 don't highlight the prefix with line numbers specially."
1273 :type 'face
1274 :group 'matching
1275 :version "24.4")
1277 (defcustom occur-excluded-properties
1278 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1279 yank-handler follow-link)
1280 "Text properties to discard when copying lines to the *Occur* buffer.
1281 The value should be a list of text properties to discard or t,
1282 which means to discard all text properties."
1283 :type '(choice (const :tag "All" t) (repeat symbol))
1284 :group 'matching
1285 :version "22.1")
1287 (defun occur-read-primary-args ()
1288 (let* ((perform-collect (consp current-prefix-arg))
1289 (regexp (read-regexp (if perform-collect
1290 "Collect strings matching regexp"
1291 "List lines matching regexp")
1292 'regexp-history-last)))
1293 (list regexp
1294 (if perform-collect
1295 ;; Perform collect operation
1296 (if (zerop (regexp-opt-depth regexp))
1297 ;; No subexpression so collect the entire match.
1298 "\\&"
1299 ;; Get the regexp for collection pattern.
1300 (let ((default (car occur-collect-regexp-history)))
1301 (read-regexp
1302 (format "Regexp to collect (default %s): " default)
1303 default 'occur-collect-regexp-history)))
1304 ;; Otherwise normal occur takes numerical prefix argument.
1305 (when current-prefix-arg
1306 (prefix-numeric-value current-prefix-arg))))))
1308 (defun occur-rename-buffer (&optional unique-p interactive-p)
1309 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1310 Here `original-buffer-name' is the buffer name where Occur was originally run.
1311 When given the prefix argument, or called non-interactively, the renaming
1312 will not clobber the existing buffer(s) of that name, but use
1313 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1314 if you always want a separate *Occur* buffer for each buffer where you
1315 invoke `occur'."
1316 (interactive "P\np")
1317 (with-current-buffer
1318 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1319 (rename-buffer (concat "*Occur: "
1320 (mapconcat #'buffer-name
1321 (car (cddr occur-revert-arguments)) "/")
1322 "*")
1323 (or unique-p (not interactive-p)))))
1325 (defun occur (regexp &optional nlines)
1326 "Show all lines in the current buffer containing a match for REGEXP.
1327 If a match spreads across multiple lines, all those lines are shown.
1329 Each line is displayed with NLINES lines before and after, or -NLINES
1330 before if NLINES is negative.
1331 NLINES defaults to `list-matching-lines-default-context-lines'.
1332 Interactively it is the prefix arg.
1334 The lines are shown in a buffer named `*Occur*'.
1335 It serves as a menu to find any of the occurrences in this buffer.
1336 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1338 If REGEXP contains upper case characters (excluding those preceded by `\\')
1339 and `search-upper-case' is non-nil, the matching is case-sensitive.
1341 When NLINES is a string or when the function is called
1342 interactively with prefix argument without a number (`C-u' alone
1343 as prefix) the matching strings are collected into the `*Occur*'
1344 buffer by using NLINES as a replacement regexp. NLINES may
1345 contain \\& and \\N which convention follows `replace-match'.
1346 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1347 \"\\1\" for NLINES collects all the function names in a lisp
1348 program. When there is no parenthesized subexpressions in REGEXP
1349 the entire match is collected. In any case the searched buffer
1350 is not modified."
1351 (interactive (occur-read-primary-args))
1352 (occur-1 regexp nlines (list (current-buffer))))
1354 (defvar ido-ignore-item-temp-list)
1356 (defun multi-occur (bufs regexp &optional nlines)
1357 "Show all lines in buffers BUFS containing a match for REGEXP.
1358 This function acts on multiple buffers; otherwise, it is exactly like
1359 `occur'. When you invoke this command interactively, you must specify
1360 the buffer names that you want, one by one.
1361 See also `multi-occur-in-matching-buffers'."
1362 (interactive
1363 (cons
1364 (let* ((bufs (list (read-buffer "First buffer to search: "
1365 (current-buffer) t)))
1366 (buf nil)
1367 (ido-ignore-item-temp-list bufs))
1368 (while (not (string-equal
1369 (setq buf (read-buffer
1370 (if (eq read-buffer-function #'ido-read-buffer)
1371 "Next buffer to search (C-j to end): "
1372 "Next buffer to search (RET to end): ")
1373 nil t))
1374 ""))
1375 (add-to-list 'bufs buf)
1376 (setq ido-ignore-item-temp-list bufs))
1377 (nreverse (mapcar #'get-buffer bufs)))
1378 (occur-read-primary-args)))
1379 (occur-1 regexp nlines bufs))
1381 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1382 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1383 Normally BUFREGEXP matches against each buffer's visited file name,
1384 but if you specify a prefix argument, it matches against the buffer name.
1385 See also `multi-occur'."
1386 (interactive
1387 (cons
1388 (let* ((default (car regexp-history))
1389 (input
1390 (read-regexp
1391 (if current-prefix-arg
1392 "List lines in buffers whose names match regexp: "
1393 "List lines in buffers whose filenames match regexp: "))))
1394 (if (equal input "")
1395 default
1396 input))
1397 (occur-read-primary-args)))
1398 (when bufregexp
1399 (occur-1 regexp nil
1400 (delq nil
1401 (mapcar (lambda (buf)
1402 (when (if allbufs
1403 (string-match bufregexp
1404 (buffer-name buf))
1405 (and (buffer-file-name buf)
1406 (string-match bufregexp
1407 (buffer-file-name buf))))
1408 buf))
1409 (buffer-list))))))
1411 (defun occur-1 (regexp nlines bufs &optional buf-name)
1412 (unless (and regexp (not (equal regexp "")))
1413 (error "Occur doesn't work with the empty regexp"))
1414 (unless buf-name
1415 (setq buf-name "*Occur*"))
1416 (let (occur-buf
1417 (active-bufs (delq nil (mapcar #'(lambda (buf)
1418 (when (buffer-live-p buf) buf))
1419 bufs))))
1420 ;; Handle the case where one of the buffers we're searching is the
1421 ;; output buffer. Just rename it.
1422 (when (member buf-name (mapcar 'buffer-name active-bufs))
1423 (with-current-buffer (get-buffer buf-name)
1424 (rename-uniquely)))
1426 ;; Now find or create the output buffer.
1427 ;; If we just renamed that buffer, we will make a new one here.
1428 (setq occur-buf (get-buffer-create buf-name))
1430 (with-current-buffer occur-buf
1431 (if (stringp nlines)
1432 (fundamental-mode) ;; This is for collect operation.
1433 (occur-mode))
1434 (let ((inhibit-read-only t)
1435 ;; Don't generate undo entries for creation of the initial contents.
1436 (buffer-undo-list t))
1437 (erase-buffer)
1438 (let ((count
1439 (if (stringp nlines)
1440 ;; Treat nlines as a regexp to collect.
1441 (let ((bufs active-bufs)
1442 (count 0))
1443 (while bufs
1444 (with-current-buffer (car bufs)
1445 (save-excursion
1446 (goto-char (point-min))
1447 (while (re-search-forward regexp nil t)
1448 ;; Insert the replacement regexp.
1449 (let ((str (match-substitute-replacement nlines)))
1450 (if str
1451 (with-current-buffer occur-buf
1452 (insert str)
1453 (setq count (1+ count))
1454 (or (zerop (current-column))
1455 (insert "\n"))))))))
1456 (setq bufs (cdr bufs)))
1457 count)
1458 ;; Perform normal occur.
1459 (occur-engine
1460 regexp active-bufs occur-buf
1461 (or nlines list-matching-lines-default-context-lines)
1462 (if (and case-fold-search search-upper-case)
1463 (isearch-no-upper-case-p regexp t)
1464 case-fold-search)
1465 list-matching-lines-buffer-name-face
1466 (if (face-differs-from-default-p list-matching-lines-prefix-face)
1467 list-matching-lines-prefix-face)
1468 list-matching-lines-face
1469 (not (eq occur-excluded-properties t))))))
1470 (let* ((bufcount (length active-bufs))
1471 (diff (- (length bufs) bufcount)))
1472 (message "Searched %d buffer%s%s; %s match%s%s"
1473 bufcount (if (= bufcount 1) "" "s")
1474 (if (zerop diff) "" (format " (%d killed)" diff))
1475 (if (zerop count) "no" (format "%d" count))
1476 (if (= count 1) "" "es")
1477 ;; Don't display regexp if with remaining text
1478 ;; it is longer than window-width.
1479 (if (> (+ (length regexp) 42) (window-width))
1480 "" (format " for `%s'" (query-replace-descr regexp)))))
1481 (setq occur-revert-arguments (list regexp nlines bufs))
1482 (if (= count 0)
1483 (kill-buffer occur-buf)
1484 (display-buffer occur-buf)
1485 (setq next-error-last-buffer occur-buf)
1486 (setq buffer-read-only t)
1487 (set-buffer-modified-p nil)
1488 (run-hooks 'occur-hook)))))))
1490 (defun occur-engine (regexp buffers out-buf nlines case-fold
1491 title-face prefix-face match-face keep-props)
1492 (with-current-buffer out-buf
1493 (let ((global-lines 0) ;; total count of matching lines
1494 (global-matches 0) ;; total count of matches
1495 (coding nil)
1496 (case-fold-search case-fold))
1497 ;; Map over all the buffers
1498 (dolist (buf buffers)
1499 (when (buffer-live-p buf)
1500 (let ((lines 0) ;; count of matching lines
1501 (matches 0) ;; count of matches
1502 (curr-line 1) ;; line count
1503 (prev-line nil) ;; line number of prev match endpt
1504 (prev-after-lines nil) ;; context lines of prev match
1505 (matchbeg 0)
1506 (origpt nil)
1507 (begpt nil)
1508 (endpt nil)
1509 (marker nil)
1510 (curstring "")
1511 (ret nil)
1512 (inhibit-field-text-motion t)
1513 (headerpt (with-current-buffer out-buf (point))))
1514 (with-current-buffer buf
1515 (or coding
1516 ;; Set CODING only if the current buffer locally
1517 ;; binds buffer-file-coding-system.
1518 (not (local-variable-p 'buffer-file-coding-system))
1519 (setq coding buffer-file-coding-system))
1520 (save-excursion
1521 (goto-char (point-min)) ;; begin searching in the buffer
1522 (while (not (eobp))
1523 (setq origpt (point))
1524 (when (setq endpt (re-search-forward regexp nil t))
1525 (setq lines (1+ lines)) ;; increment matching lines count
1526 (setq matchbeg (match-beginning 0))
1527 ;; Get beginning of first match line and end of the last.
1528 (save-excursion
1529 (goto-char matchbeg)
1530 (setq begpt (line-beginning-position))
1531 (goto-char endpt)
1532 (setq endpt (line-end-position)))
1533 ;; Sum line numbers up to the first match line.
1534 (setq curr-line (+ curr-line (count-lines origpt begpt)))
1535 (setq marker (make-marker))
1536 (set-marker marker matchbeg)
1537 (setq curstring (occur-engine-line begpt endpt keep-props))
1538 ;; Highlight the matches
1539 (let ((len (length curstring))
1540 (start 0))
1541 (while (and (< start len)
1542 (string-match regexp curstring start))
1543 (setq matches (1+ matches))
1544 (add-text-properties
1545 (match-beginning 0) (match-end 0)
1546 '(occur-match t) curstring)
1547 (when match-face
1548 ;; Add `match-face' to faces copied from the buffer.
1549 (add-face-text-property
1550 (match-beginning 0) (match-end 0)
1551 match-face nil curstring))
1552 ;; Avoid infloop (Bug#7593).
1553 (let ((end (match-end 0)))
1554 (setq start (if (= start end) (1+ start) end)))))
1555 ;; Generate the string to insert for this match
1556 (let* ((match-prefix
1557 ;; Using 7 digits aligns tabs properly.
1558 (apply #'propertize (format "%7d:" curr-line)
1559 (append
1560 (when prefix-face
1561 `(font-lock-face ,prefix-face))
1562 `(occur-prefix t mouse-face (highlight)
1563 ;; Allow insertion of text at
1564 ;; the end of the prefix (for
1565 ;; Occur Edit mode).
1566 front-sticky t rear-nonsticky t
1567 occur-target ,marker follow-link t
1568 help-echo "mouse-2: go to this occurrence"))))
1569 (match-str
1570 ;; We don't put `mouse-face' on the newline,
1571 ;; because that loses. And don't put it
1572 ;; on context lines to reduce flicker.
1573 (propertize curstring 'mouse-face (list 'highlight)
1574 'occur-target marker
1575 'follow-link t
1576 'help-echo
1577 "mouse-2: go to this occurrence"))
1578 (out-line
1579 (concat
1580 match-prefix
1581 ;; Add non-numeric prefix to all non-first lines
1582 ;; of multi-line matches.
1583 (replace-regexp-in-string
1584 "\n"
1585 (if prefix-face
1586 (propertize "\n :" 'font-lock-face prefix-face)
1587 "\n :")
1588 match-str)
1589 ;; Add marker at eol, but no mouse props.
1590 (propertize "\n" 'occur-target marker)))
1591 (data
1592 (if (= nlines 0)
1593 ;; The simple display style
1594 out-line
1595 ;; The complex multi-line display style.
1596 (setq ret (occur-context-lines
1597 out-line nlines keep-props begpt endpt
1598 curr-line prev-line prev-after-lines
1599 prefix-face))
1600 ;; Set first elem of the returned list to `data',
1601 ;; and the second elem to `prev-after-lines'.
1602 (setq prev-after-lines (nth 1 ret))
1603 (nth 0 ret))))
1604 ;; Actually insert the match display data
1605 (with-current-buffer out-buf
1606 (insert data)))
1607 (goto-char endpt))
1608 (if endpt
1609 (progn
1610 ;; Sum line numbers between first and last match lines.
1611 (setq curr-line (+ curr-line (count-lines begpt endpt)
1612 ;; Add 1 for empty last match line since
1613 ;; count-lines returns 1 line less.
1614 (if (and (bolp) (eolp)) 1 0)))
1615 ;; On to the next match...
1616 (forward-line 1))
1617 (goto-char (point-max)))
1618 (setq prev-line (1- curr-line)))
1619 ;; Flush remaining context after-lines.
1620 (when prev-after-lines
1621 (with-current-buffer out-buf
1622 (insert (apply #'concat (occur-engine-add-prefix
1623 prev-after-lines prefix-face)))))))
1624 (when (not (zerop lines)) ;; is the count zero?
1625 (setq global-lines (+ global-lines lines)
1626 global-matches (+ global-matches matches))
1627 (with-current-buffer out-buf
1628 (goto-char headerpt)
1629 (let ((beg (point))
1630 end)
1631 (insert (propertize
1632 (format "%d match%s%s%s in buffer: %s\n"
1633 matches (if (= matches 1) "" "es")
1634 ;; Don't display the same number of lines
1635 ;; and matches in case of 1 match per line.
1636 (if (= lines matches)
1637 "" (format " in %d line%s"
1638 lines (if (= lines 1) "" "s")))
1639 ;; Don't display regexp for multi-buffer.
1640 (if (> (length buffers) 1)
1641 "" (format " for \"%s\""
1642 (query-replace-descr regexp)))
1643 (buffer-name buf))
1644 'read-only t))
1645 (setq end (point))
1646 (add-text-properties beg end `(occur-title ,buf))
1647 (when title-face
1648 (add-face-text-property beg end title-face)))
1649 (goto-char (point-min)))))))
1650 ;; Display total match count and regexp for multi-buffer.
1651 (when (and (not (zerop global-lines)) (> (length buffers) 1))
1652 (goto-char (point-min))
1653 (let ((beg (point))
1654 end)
1655 (insert (format "%d match%s%s total for \"%s\":\n"
1656 global-matches (if (= global-matches 1) "" "es")
1657 ;; Don't display the same number of lines
1658 ;; and matches in case of 1 match per line.
1659 (if (= global-lines global-matches)
1660 "" (format " in %d line%s"
1661 global-lines (if (= global-lines 1) "" "s")))
1662 (query-replace-descr regexp)))
1663 (setq end (point))
1664 (when title-face
1665 (add-face-text-property beg end title-face)))
1666 (goto-char (point-min)))
1667 (if coding
1668 ;; CODING is buffer-file-coding-system of the first buffer
1669 ;; that locally binds it. Let's use it also for the output
1670 ;; buffer.
1671 (set-buffer-file-coding-system coding))
1672 ;; Return the number of matches
1673 global-matches)))
1675 (defun occur-engine-line (beg end &optional keep-props)
1676 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1677 (text-property-not-all beg end 'fontified t))
1678 (if (fboundp 'jit-lock-fontify-now)
1679 (jit-lock-fontify-now beg end)))
1680 (if (and keep-props (not (eq occur-excluded-properties t)))
1681 (let ((str (buffer-substring beg end)))
1682 (remove-list-of-text-properties
1683 0 (length str) occur-excluded-properties str)
1684 str)
1685 (buffer-substring-no-properties beg end)))
1687 (defun occur-engine-add-prefix (lines &optional prefix-face)
1688 (mapcar
1689 #'(lambda (line)
1690 (concat (if prefix-face
1691 (propertize " :" 'font-lock-face prefix-face)
1692 " :")
1693 line "\n"))
1694 lines))
1696 (defun occur-accumulate-lines (count &optional keep-props pt)
1697 (save-excursion
1698 (when pt
1699 (goto-char pt))
1700 (let ((forwardp (> count 0))
1701 result beg end moved)
1702 (while (not (or (zerop count)
1703 (if forwardp
1704 (eobp)
1705 (and (bobp) (not moved)))))
1706 (setq count (+ count (if forwardp -1 1)))
1707 (setq beg (line-beginning-position)
1708 end (line-end-position))
1709 (push (occur-engine-line beg end keep-props) result)
1710 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1711 (nreverse result))))
1713 ;; Generate context display for occur.
1714 ;; OUT-LINE is the line where the match is.
1715 ;; NLINES and KEEP-PROPS are args to occur-engine.
1716 ;; CURR-LINE is line count of the current match,
1717 ;; PREV-LINE is line count of the previous match,
1718 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1719 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1720 ;; then concatenate them all together.
1721 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1722 curr-line prev-line prev-after-lines
1723 &optional prefix-face)
1724 ;; Find after- and before-context lines of the current match.
1725 (let ((before-lines
1726 (nreverse (cdr (occur-accumulate-lines
1727 (- (1+ (abs nlines))) keep-props begpt))))
1728 (after-lines
1729 (cdr (occur-accumulate-lines
1730 (1+ nlines) keep-props endpt)))
1731 separator)
1733 ;; Combine after-lines of the previous match
1734 ;; with before-lines of the current match.
1736 (when prev-after-lines
1737 ;; Don't overlap prev after-lines with current before-lines.
1738 (if (>= (+ prev-line (length prev-after-lines))
1739 (- curr-line (length before-lines)))
1740 (setq prev-after-lines
1741 (butlast prev-after-lines
1742 (- (length prev-after-lines)
1743 (- curr-line prev-line (length before-lines) 1))))
1744 ;; Separate non-overlapping context lines with a dashed line.
1745 (setq separator "-------\n")))
1747 (when prev-line
1748 ;; Don't overlap current before-lines with previous match line.
1749 (if (<= (- curr-line (length before-lines))
1750 prev-line)
1751 (setq before-lines
1752 (nthcdr (- (length before-lines)
1753 (- curr-line prev-line 1))
1754 before-lines))
1755 ;; Separate non-overlapping before-context lines.
1756 (unless (> nlines 0)
1757 (setq separator "-------\n"))))
1759 (list
1760 ;; Return a list where the first element is the output line.
1761 (apply #'concat
1762 (append
1763 (if prev-after-lines
1764 (occur-engine-add-prefix prev-after-lines prefix-face))
1765 (if separator
1766 (list (if prefix-face
1767 (propertize separator 'font-lock-face prefix-face)
1768 separator)))
1769 (occur-engine-add-prefix before-lines prefix-face)
1770 (list out-line)))
1771 ;; And the second element is the list of context after-lines.
1772 (if (> nlines 0) after-lines))))
1775 ;; It would be nice to use \\[...], but there is no reasonable way
1776 ;; to make that display both SPC and Y.
1777 (defconst query-replace-help
1778 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1779 RET or `q' to exit, Period to replace one match and exit,
1780 Comma to replace but not move point immediately,
1781 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1782 C-w to delete match and recursive edit,
1783 C-l to clear the screen, redisplay, and offer same replacement again,
1784 ! to replace all remaining matches in this buffer with no more questions,
1785 ^ to move point back to previous match,
1786 E to edit the replacement string.
1787 In multi-buffer replacements type `Y' to replace all remaining
1788 matches in all remaining buffers with no more questions,
1789 `N' to skip to the next buffer without replacing remaining matches
1790 in the current buffer."
1791 "Help message while in `query-replace'.")
1793 (defvar query-replace-map
1794 (let ((map (make-sparse-keymap)))
1795 (define-key map " " 'act)
1796 (define-key map "\d" 'skip)
1797 (define-key map [delete] 'skip)
1798 (define-key map [backspace] 'skip)
1799 (define-key map "y" 'act)
1800 (define-key map "n" 'skip)
1801 (define-key map "Y" 'act)
1802 (define-key map "N" 'skip)
1803 (define-key map "e" 'edit-replacement)
1804 (define-key map "E" 'edit-replacement)
1805 (define-key map "," 'act-and-show)
1806 (define-key map "q" 'exit)
1807 (define-key map "\r" 'exit)
1808 (define-key map [return] 'exit)
1809 (define-key map "." 'act-and-exit)
1810 (define-key map "\C-r" 'edit)
1811 (define-key map "\C-w" 'delete-and-edit)
1812 (define-key map "\C-l" 'recenter)
1813 (define-key map "!" 'automatic)
1814 (define-key map "^" 'backup)
1815 (define-key map "\C-h" 'help)
1816 (define-key map [f1] 'help)
1817 (define-key map [help] 'help)
1818 (define-key map "?" 'help)
1819 (define-key map "\C-g" 'quit)
1820 (define-key map "\C-]" 'quit)
1821 (define-key map "\C-v" 'scroll-up)
1822 (define-key map "\M-v" 'scroll-down)
1823 (define-key map [next] 'scroll-up)
1824 (define-key map [prior] 'scroll-down)
1825 (define-key map [?\C-\M-v] 'scroll-other-window)
1826 (define-key map [M-next] 'scroll-other-window)
1827 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1828 (define-key map [M-prior] 'scroll-other-window-down)
1829 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1830 ;; should check for ESC specially.
1831 ;; (define-key map "\e" 'exit-prefix)
1832 (define-key map [escape] 'exit-prefix)
1833 map)
1834 "Keymap of responses to questions posed by commands like `query-replace'.
1835 The \"bindings\" in this map are not commands; they are answers.
1836 The valid answers include `act', `skip', `act-and-show',
1837 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1838 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1839 `edit', `edit-replacement', `delete-and-edit', `automatic',
1840 `backup', `quit', and `help'.
1842 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1844 (defvar multi-query-replace-map
1845 (let ((map (make-sparse-keymap)))
1846 (set-keymap-parent map query-replace-map)
1847 (define-key map "Y" 'automatic-all)
1848 (define-key map "N" 'exit-current)
1849 map)
1850 "Keymap that defines additional bindings for multi-buffer replacements.
1851 It extends its parent map `query-replace-map' with new bindings to
1852 operate on a set of buffers/files. The difference with its parent map
1853 is the additional answers `automatic-all' to replace all remaining
1854 matches in all remaining buffers with no more questions, and
1855 `exit-current' to skip remaining matches in the current buffer
1856 and to continue with the next buffer in the sequence.")
1858 (defun replace-match-string-symbols (n)
1859 "Process a list (and any sub-lists), expanding certain symbols.
1860 Symbol Expands To
1861 N (match-string N) (where N is a string of digits)
1862 #N (string-to-number (match-string N))
1863 & (match-string 0)
1864 #& (string-to-number (match-string 0))
1865 # replace-count
1867 Note that these symbols must be preceded by a backslash in order to
1868 type them using Lisp syntax."
1869 (while (consp n)
1870 (cond
1871 ((consp (car n))
1872 (replace-match-string-symbols (car n))) ;Process sub-list
1873 ((symbolp (car n))
1874 (let ((name (symbol-name (car n))))
1875 (cond
1876 ((string-match "^[0-9]+$" name)
1877 (setcar n (list 'match-string (string-to-number name))))
1878 ((string-match "^#[0-9]+$" name)
1879 (setcar n (list 'string-to-number
1880 (list 'match-string
1881 (string-to-number (substring name 1))))))
1882 ((string= "&" name)
1883 (setcar n '(match-string 0)))
1884 ((string= "#&" name)
1885 (setcar n '(string-to-number (match-string 0))))
1886 ((string= "#" name)
1887 (setcar n 'replace-count))))))
1888 (setq n (cdr n))))
1890 (defun replace-eval-replacement (expression count)
1891 (let* ((replace-count count)
1893 (replacement
1894 (condition-case err
1895 (eval expression)
1896 (error
1897 (error "Error evaluating replacement expression: %S" err)))))
1898 (if (stringp replacement)
1899 replacement
1900 (prin1-to-string replacement t))))
1902 (defun replace-quote (replacement)
1903 "Quote a replacement string.
1904 This just doubles all backslashes in REPLACEMENT and
1905 returns the resulting string. If REPLACEMENT is not
1906 a string, it is first passed through `prin1-to-string'
1907 with the `noescape' argument set.
1909 `match-data' is preserved across the call."
1910 (save-match-data
1911 (replace-regexp-in-string "\\\\" "\\\\"
1912 (if (stringp replacement)
1913 replacement
1914 (prin1-to-string replacement t))
1915 t t)))
1917 (defun replace-loop-through-replacements (data count)
1918 ;; DATA is a vector containing the following values:
1919 ;; 0 next-rotate-count
1920 ;; 1 repeat-count
1921 ;; 2 next-replacement
1922 ;; 3 replacements
1923 (if (= (aref data 0) count)
1924 (progn
1925 (aset data 0 (+ count (aref data 1)))
1926 (let ((next (cdr (aref data 2))))
1927 (aset data 2 (if (consp next) next (aref data 3))))))
1928 (car (aref data 2)))
1930 (defun replace-match-data (integers reuse &optional new)
1931 "Like `match-data', but markers in REUSE get invalidated.
1932 If NEW is non-nil, it is set and returned instead of fresh data,
1933 but coerced to the correct value of INTEGERS."
1934 (or (and new
1935 (progn
1936 (set-match-data new)
1937 (and (eq new reuse)
1938 (eq (null integers) (markerp (car reuse)))
1939 new)))
1940 (match-data integers reuse t)))
1942 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data backward)
1943 "Make a replacement with `replace-match', editing `\\?'.
1944 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
1945 After possibly editing it (if `\\?' is present), NEWTEXT is also
1946 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
1947 is made (to save time). MATCH-DATA is used for the replacement.
1948 In case editing is done, it is changed to use markers.
1950 The return value is non-nil if there has been no `\\?' or NOEDIT was
1951 passed in. If LITERAL is set, no checking is done, anyway."
1952 (unless (or literal noedit)
1953 (setq noedit t)
1954 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1955 newtext)
1956 (setq newtext
1957 (read-string "Edit replacement string: "
1958 (prog1
1959 (cons
1960 (replace-match "" t t newtext 3)
1961 (1+ (match-beginning 3)))
1962 (setq match-data
1963 (replace-match-data
1964 nil match-data match-data))))
1965 noedit nil)))
1966 (set-match-data match-data)
1967 (replace-match newtext fixedcase literal)
1968 ;; `replace-match' leaves point at the end of the replacement text,
1969 ;; so move point to the beginning when replacing backward.
1970 (when backward (goto-char (nth 0 match-data)))
1971 noedit)
1973 (defvar replace-search-function nil
1974 "Function to use when searching for strings to replace.
1975 It is used by `query-replace' and `replace-string', and is called
1976 with three arguments, as if it were `search-forward'.")
1978 (defvar replace-re-search-function nil
1979 "Function to use when searching for regexps to replace.
1980 It is used by `query-replace-regexp', `replace-regexp',
1981 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1982 It is called with three arguments, as if it were
1983 `re-search-forward'.")
1985 (defun replace-search (search-string limit regexp-flag delimited-flag
1986 case-fold-search backward)
1987 "Search for the next occurrence of SEARCH-STRING to replace."
1988 ;; Let-bind global isearch-* variables to values used
1989 ;; to search the next replacement. These let-bindings
1990 ;; should be effective both at the time of calling
1991 ;; `isearch-search-fun-default' and also at the
1992 ;; time of funcalling `search-function'.
1993 ;; These isearch-* bindings can't be placed higher
1994 ;; outside of this function because then another I-search
1995 ;; used after `recursive-edit' might override them.
1996 (let* ((isearch-regexp regexp-flag)
1997 (isearch-word delimited-flag)
1998 (isearch-lax-whitespace
1999 replace-lax-whitespace)
2000 (isearch-regexp-lax-whitespace
2001 replace-regexp-lax-whitespace)
2002 (isearch-case-fold-search case-fold-search)
2003 (isearch-adjusted nil)
2004 (isearch-nonincremental t) ; don't use lax word mode
2005 (isearch-forward (not backward))
2006 (search-function
2007 (or (if regexp-flag
2008 replace-re-search-function
2009 replace-search-function)
2010 (isearch-search-fun-default))))
2011 (funcall search-function search-string limit t)))
2013 (defvar replace-overlay nil)
2015 (defun replace-highlight (match-beg match-end range-beg range-end
2016 search-string regexp-flag delimited-flag
2017 case-fold-search backward)
2018 (if query-replace-highlight
2019 (if replace-overlay
2020 (move-overlay replace-overlay match-beg match-end (current-buffer))
2021 (setq replace-overlay (make-overlay match-beg match-end))
2022 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2023 (overlay-put replace-overlay 'face 'query-replace)))
2024 (if query-replace-lazy-highlight
2025 (let ((isearch-string search-string)
2026 (isearch-regexp regexp-flag)
2027 (isearch-word delimited-flag)
2028 (isearch-lax-whitespace
2029 replace-lax-whitespace)
2030 (isearch-regexp-lax-whitespace
2031 replace-regexp-lax-whitespace)
2032 (isearch-case-fold-search case-fold-search)
2033 (isearch-forward (not backward))
2034 (isearch-other-end match-beg)
2035 (isearch-error nil))
2036 (isearch-lazy-highlight-new-loop range-beg range-end))))
2038 (defun replace-dehighlight ()
2039 (when replace-overlay
2040 (delete-overlay replace-overlay))
2041 (when query-replace-lazy-highlight
2042 (lazy-highlight-cleanup lazy-highlight-cleanup)
2043 (setq isearch-lazy-highlight-last-string nil))
2044 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2045 (isearch-clean-overlays))
2047 (defun perform-replace (from-string replacements
2048 query-flag regexp-flag delimited-flag
2049 &optional repeat-count map start end backward)
2050 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2051 Don't use this in your own program unless you want to query and set the mark
2052 just as `query-replace' does. Instead, write a simple loop like this:
2054 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2055 (replace-match \"foobar\" nil nil))
2057 which will run faster and probably do exactly what you want. Please
2058 see the documentation of `replace-match' to find out how to simulate
2059 `case-replace'.
2061 This function returns nil if and only if there were no matches to
2062 make, or the user didn't cancel the call."
2063 (or map (setq map query-replace-map))
2064 (and query-flag minibuffer-auto-raise
2065 (raise-frame (window-frame (minibuffer-window))))
2066 (let* ((case-fold-search
2067 (if (and case-fold-search search-upper-case)
2068 (isearch-no-upper-case-p from-string regexp-flag)
2069 case-fold-search))
2070 (nocasify (not (and case-replace case-fold-search)))
2071 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2072 (search-string from-string)
2073 (real-match-data nil) ; The match data for the current match.
2074 (next-replacement nil)
2075 ;; This is non-nil if we know there is nothing for the user
2076 ;; to edit in the replacement.
2077 (noedit nil)
2078 (keep-going t)
2079 (stack nil)
2080 (replace-count 0)
2081 (skip-read-only-count 0)
2082 (skip-filtered-count 0)
2083 (skip-invisible-count 0)
2084 (nonempty-match nil)
2085 (multi-buffer nil)
2086 (recenter-last-op nil) ; Start cycling order with initial position.
2088 ;; If non-nil, it is marker saying where in the buffer to stop.
2089 (limit nil)
2091 ;; Data for the next match. If a cons, it has the same format as
2092 ;; (match-data); otherwise it is t if a match is possible at point.
2093 (match-again t)
2095 (message
2096 (if query-flag
2097 (apply 'propertize
2098 (substitute-command-keys
2099 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2100 minibuffer-prompt-properties))))
2102 ;; If region is active, in Transient Mark mode, operate on region.
2103 (if backward
2104 (when end
2105 (setq limit (copy-marker (min start end)))
2106 (goto-char (max start end))
2107 (deactivate-mark))
2108 (when start
2109 (setq limit (copy-marker (max start end)))
2110 (goto-char (min start end))
2111 (deactivate-mark)))
2113 ;; If last typed key in previous call of multi-buffer perform-replace
2114 ;; was `automatic-all', don't ask more questions in next files
2115 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2116 (setq query-flag nil multi-buffer t))
2118 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
2119 ;; containing a function and its first argument. The function is
2120 ;; called to generate each replacement like this:
2121 ;; (funcall (car replacements) (cdr replacements) replace-count)
2122 ;; It must return a string.
2123 (cond
2124 ((stringp replacements)
2125 (setq next-replacement replacements
2126 replacements nil))
2127 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2128 (or repeat-count (setq repeat-count 1))
2129 (setq replacements (cons 'replace-loop-through-replacements
2130 (vector repeat-count repeat-count
2131 replacements replacements)))))
2133 (when query-replace-lazy-highlight
2134 (setq isearch-lazy-highlight-last-string nil))
2136 (push-mark)
2137 (undo-boundary)
2138 (unwind-protect
2139 ;; Loop finding occurrences that perhaps should be replaced.
2140 (while (and keep-going
2141 (if backward
2142 (not (or (bobp) (and limit (<= (point) limit))))
2143 (not (or (eobp) (and limit (>= (point) limit)))))
2144 ;; Use the next match if it is already known;
2145 ;; otherwise, search for a match after moving forward
2146 ;; one char if progress is required.
2147 (setq real-match-data
2148 (cond ((consp match-again)
2149 (goto-char (if backward
2150 (nth 0 match-again)
2151 (nth 1 match-again)))
2152 (replace-match-data
2153 t real-match-data match-again))
2154 ;; MATCH-AGAIN non-nil means accept an
2155 ;; adjacent match.
2156 (match-again
2157 (and
2158 (replace-search search-string limit
2159 regexp-flag delimited-flag
2160 case-fold-search backward)
2161 ;; For speed, use only integers and
2162 ;; reuse the list used last time.
2163 (replace-match-data t real-match-data)))
2164 ((and (if backward
2165 (> (1- (point)) (point-min))
2166 (< (1+ (point)) (point-max)))
2167 (or (null limit)
2168 (if backward
2169 (> (1- (point)) limit)
2170 (< (1+ (point)) limit))))
2171 ;; If not accepting adjacent matches,
2172 ;; move one char to the right before
2173 ;; searching again. Undo the motion
2174 ;; if the search fails.
2175 (let ((opoint (point)))
2176 (forward-char (if backward -1 1))
2177 (if (replace-search search-string limit
2178 regexp-flag delimited-flag
2179 case-fold-search backward)
2180 (replace-match-data
2181 t real-match-data)
2182 (goto-char opoint)
2183 nil))))))
2185 ;; Record whether the match is nonempty, to avoid an infinite loop
2186 ;; repeatedly matching the same empty string.
2187 (setq nonempty-match
2188 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2190 ;; If the match is empty, record that the next one can't be
2191 ;; adjacent.
2193 ;; Otherwise, if matching a regular expression, do the next
2194 ;; match now, since the replacement for this match may
2195 ;; affect whether the next match is adjacent to this one.
2196 ;; If that match is empty, don't use it.
2197 (setq match-again
2198 (and nonempty-match
2199 (or (not regexp-flag)
2200 (and (if backward
2201 (looking-back search-string)
2202 (looking-at search-string))
2203 (let ((match (match-data)))
2204 (and (/= (nth 0 match) (nth 1 match))
2205 match))))))
2207 (cond
2208 ;; Optionally ignore matches that have a read-only property.
2209 ((not (or (not query-replace-skip-read-only)
2210 (not (text-property-not-all
2211 (nth 0 real-match-data) (nth 1 real-match-data)
2212 'read-only nil))))
2213 (setq skip-read-only-count (1+ skip-read-only-count)))
2214 ;; Optionally filter out matches.
2215 ((not (funcall isearch-filter-predicate
2216 (nth 0 real-match-data) (nth 1 real-match-data)))
2217 (setq skip-filtered-count (1+ skip-filtered-count)))
2218 ;; Optionally ignore invisible matches.
2219 ((not (or (eq search-invisible t)
2220 ;; Don't open overlays for automatic replacements.
2221 (and (not query-flag) search-invisible)
2222 ;; Open hidden overlays for interactive replacements.
2223 (not (isearch-range-invisible
2224 (nth 0 real-match-data) (nth 1 real-match-data)))))
2225 (setq skip-invisible-count (1+ skip-invisible-count)))
2227 ;; Calculate the replacement string, if necessary.
2228 (when replacements
2229 (set-match-data real-match-data)
2230 (setq next-replacement
2231 (funcall (car replacements) (cdr replacements)
2232 replace-count)))
2233 (if (not query-flag)
2234 (progn
2235 (unless (or literal noedit)
2236 (replace-highlight
2237 (nth 0 real-match-data) (nth 1 real-match-data)
2238 start end search-string
2239 regexp-flag delimited-flag case-fold-search backward))
2240 (setq noedit
2241 (replace-match-maybe-edit
2242 next-replacement nocasify literal
2243 noedit real-match-data backward)
2244 replace-count (1+ replace-count)))
2245 (undo-boundary)
2246 (let (done replaced key def)
2247 ;; Loop reading commands until one of them sets done,
2248 ;; which means it has finished handling this
2249 ;; occurrence. Any command that sets `done' should
2250 ;; leave behind proper match data for the stack.
2251 ;; Commands not setting `done' need to adjust
2252 ;; `real-match-data'.
2253 (while (not done)
2254 (set-match-data real-match-data)
2255 (replace-highlight
2256 (match-beginning 0) (match-end 0)
2257 start end search-string
2258 regexp-flag delimited-flag case-fold-search backward)
2259 ;; Bind message-log-max so we don't fill up the message log
2260 ;; with a bunch of identical messages.
2261 (let ((message-log-max nil)
2262 (replacement-presentation
2263 (if query-replace-show-replacement
2264 (save-match-data
2265 (set-match-data real-match-data)
2266 (match-substitute-replacement next-replacement
2267 nocasify literal))
2268 next-replacement)))
2269 (message message
2270 (query-replace-descr from-string)
2271 (query-replace-descr replacement-presentation)))
2272 (setq key (read-event))
2273 ;; Necessary in case something happens during read-event
2274 ;; that clobbers the match data.
2275 (set-match-data real-match-data)
2276 (setq key (vector key))
2277 (setq def (lookup-key map key))
2278 ;; Restore the match data while we process the command.
2279 (cond ((eq def 'help)
2280 (with-output-to-temp-buffer "*Help*"
2281 (princ
2282 (concat "Query replacing "
2283 (if delimited-flag
2284 (or (and (symbolp delimited-flag)
2285 (get delimited-flag 'isearch-message-prefix))
2286 "word ") "")
2287 (if regexp-flag "regexp " "")
2288 (if backward "backward " "")
2289 from-string " with "
2290 next-replacement ".\n\n"
2291 (substitute-command-keys
2292 query-replace-help)))
2293 (with-current-buffer standard-output
2294 (help-mode))))
2295 ((eq def 'exit)
2296 (setq keep-going nil)
2297 (setq done t))
2298 ((eq def 'exit-current)
2299 (setq multi-buffer t keep-going nil done t))
2300 ((eq def 'backup)
2301 (if stack
2302 (let ((elt (pop stack)))
2303 (goto-char (nth 0 elt))
2304 (setq replaced (nth 1 elt)
2305 real-match-data
2306 (replace-match-data
2307 t real-match-data
2308 (nth 2 elt))))
2309 (message "No previous match")
2310 (ding 'no-terminate)
2311 (sit-for 1)))
2312 ((eq def 'act)
2313 (or replaced
2314 (setq noedit
2315 (replace-match-maybe-edit
2316 next-replacement nocasify literal
2317 noedit real-match-data backward)
2318 replace-count (1+ replace-count)))
2319 (setq done t replaced t))
2320 ((eq def 'act-and-exit)
2321 (or replaced
2322 (setq noedit
2323 (replace-match-maybe-edit
2324 next-replacement nocasify literal
2325 noedit real-match-data backward)
2326 replace-count (1+ replace-count)))
2327 (setq keep-going nil)
2328 (setq done t replaced t))
2329 ((eq def 'act-and-show)
2330 (if (not replaced)
2331 (setq noedit
2332 (replace-match-maybe-edit
2333 next-replacement nocasify literal
2334 noedit real-match-data backward)
2335 replace-count (1+ replace-count)
2336 real-match-data (replace-match-data
2337 t real-match-data)
2338 replaced t)))
2339 ((or (eq def 'automatic) (eq def 'automatic-all))
2340 (or replaced
2341 (setq noedit
2342 (replace-match-maybe-edit
2343 next-replacement nocasify literal
2344 noedit real-match-data backward)
2345 replace-count (1+ replace-count)))
2346 (setq done t query-flag nil replaced t)
2347 (if (eq def 'automatic-all) (setq multi-buffer t)))
2348 ((eq def 'skip)
2349 (setq done t))
2350 ((eq def 'recenter)
2351 ;; `this-command' has the value `query-replace',
2352 ;; so we need to bind it to `recenter-top-bottom'
2353 ;; to allow it to detect a sequence of `C-l'.
2354 (let ((this-command 'recenter-top-bottom)
2355 (last-command 'recenter-top-bottom))
2356 (recenter-top-bottom)))
2357 ((eq def 'edit)
2358 (let ((opos (point-marker)))
2359 (setq real-match-data (replace-match-data
2360 nil real-match-data
2361 real-match-data))
2362 (goto-char (match-beginning 0))
2363 (save-excursion
2364 (save-window-excursion
2365 (recursive-edit)))
2366 (goto-char opos)
2367 (set-marker opos nil))
2368 ;; Before we make the replacement,
2369 ;; decide whether the search string
2370 ;; can match again just after this match.
2371 (if (and regexp-flag nonempty-match)
2372 (setq match-again (and (looking-at search-string)
2373 (match-data)))))
2374 ;; Edit replacement.
2375 ((eq def 'edit-replacement)
2376 (setq real-match-data (replace-match-data
2377 nil real-match-data
2378 real-match-data)
2379 next-replacement
2380 (read-string "Edit replacement string: "
2381 next-replacement)
2382 noedit nil)
2383 (if replaced
2384 (set-match-data real-match-data)
2385 (setq noedit
2386 (replace-match-maybe-edit
2387 next-replacement nocasify literal noedit
2388 real-match-data backward)
2389 replaced t))
2390 (setq done t))
2392 ((eq def 'delete-and-edit)
2393 (replace-match "" t t)
2394 (setq real-match-data (replace-match-data
2395 nil real-match-data))
2396 (replace-dehighlight)
2397 (save-excursion (recursive-edit))
2398 (setq replaced t))
2399 ;; Note: we do not need to treat `exit-prefix'
2400 ;; specially here, since we reread
2401 ;; any unrecognized character.
2403 (setq this-command 'mode-exited)
2404 (setq keep-going nil)
2405 (setq unread-command-events
2406 (append (listify-key-sequence key)
2407 unread-command-events))
2408 (setq done t)))
2409 (when query-replace-lazy-highlight
2410 ;; Force lazy rehighlighting only after replacements.
2411 (if (not (memq def '(skip backup)))
2412 (setq isearch-lazy-highlight-last-string nil)))
2413 (unless (eq def 'recenter)
2414 ;; Reset recenter cycling order to initial position.
2415 (setq recenter-last-op nil)))
2416 ;; Record previous position for ^ when we move on.
2417 ;; Change markers to numbers in the match data
2418 ;; since lots of markers slow down editing.
2419 (push (list (point) replaced
2420 ;;; If the replacement has already happened, all we need is the
2421 ;;; current match start and end. We could get this with a trivial
2422 ;;; match like
2423 ;;; (save-excursion (goto-char (match-beginning 0))
2424 ;;; (search-forward (match-string 0))
2425 ;;; (match-data t))
2426 ;;; if we really wanted to avoid manually constructing match data.
2427 ;;; Adding current-buffer is necessary so that match-data calls can
2428 ;;; return markers which are appropriate for editing.
2429 (if replaced
2430 (list
2431 (match-beginning 0)
2432 (match-end 0)
2433 (current-buffer))
2434 (match-data t)))
2435 stack))))))
2437 (replace-dehighlight))
2438 (or unread-command-events
2439 (message "Replaced %d occurrence%s%s"
2440 replace-count
2441 (if (= replace-count 1) "" "s")
2442 (if (> (+ skip-read-only-count
2443 skip-filtered-count
2444 skip-invisible-count) 0)
2445 (format " (skipped %s)"
2446 (mapconcat
2447 'identity
2448 (delq nil (list
2449 (if (> skip-read-only-count 0)
2450 (format "%s read-only"
2451 skip-read-only-count))
2452 (if (> skip-invisible-count 0)
2453 (format "%s invisible"
2454 skip-invisible-count))
2455 (if (> skip-filtered-count 0)
2456 (format "%s filtered out"
2457 skip-filtered-count))))
2458 ", "))
2459 "")))
2460 (or (and keep-going stack) multi-buffer)))
2462 ;;; replace.el ends here