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