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