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