1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2016 Free
4 ;; Software Foundation, Inc.
6 ;; Maintainer: emacs-devel@gnu.org
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/>.
26 ;; This package supplies the string and regular-expression replace functions
27 ;; documented in the Emacs user's manual.
31 (defcustom case-replace t
32 "Non-nil means `query-replace' should preserve case in replacements."
36 (defcustom replace-character-fold nil
37 "Non-nil means replacement commands should do character folding in matches.
38 This means, for instance, that \\=' will match a large variety of
40 This variable affects `query-replace' and `replace-string', but not
46 (defcustom replace-lax-whitespace nil
47 "Non-nil means `query-replace' matches a sequence of whitespace chars.
48 When you enter a space or spaces in the strings to be replaced,
49 it will match any sequence matched by the regexp `search-whitespace-regexp'."
54 (defcustom replace-regexp-lax-whitespace nil
55 "Non-nil means `query-replace-regexp' matches a sequence of whitespace chars.
56 When you enter a space or spaces in the regexps to be replaced,
57 it will match any sequence matched by the regexp `search-whitespace-regexp'."
62 (defvar query-replace-history nil
63 "Default history list for query-replace commands.
64 See `query-replace-from-history-variable' and
65 `query-replace-to-history-variable'.")
67 (defvar query-replace-defaults nil
68 "Default values of FROM-STRING and TO-STRING for `query-replace'.
69 This is a list of cons cells (FROM-STRING . TO-STRING), or nil
70 if there are no default values.")
72 (defvar query-replace-interactive nil
73 "Non-nil means `query-replace' uses the last search string.
74 That becomes the \"string to replace\".")
75 (make-obsolete-variable 'query-replace-interactive
76 "use `M-n' to pull the last incremental search string
77 to the minibuffer that reads the string to replace, or invoke replacements
78 from Isearch by using a key sequence like `C-s C-s M-%'." "24.3")
80 (defcustom query-replace-from-to-separator
81 (propertize (if (char-displayable-p ?→) " → " " -> ")
82 'face 'minibuffer-prompt)
83 "String that separates FROM and TO in the history of replacement pairs."
84 ;; Avoids error when attempt to autoload char-displayable-p fails
85 ;; while preparing to dump, also stops customize-rogue listing this.
86 :initialize 'custom-initialize-delay
88 :type '(choice string (sexp :tag "Display specification"))
91 (defcustom query-replace-from-history-variable 'query-replace-history
92 "History list to use for the FROM argument of `query-replace' commands.
93 The value of this variable should be a symbol; that symbol
94 is used as a variable to hold a history list for the strings
95 or patterns to be replaced."
100 (defcustom query-replace-to-history-variable 'query-replace-history
101 "History list to use for the TO argument of `query-replace' commands.
102 The value of this variable should be a symbol; that symbol
103 is used as a variable to hold a history list for replacement
104 strings or patterns."
109 (defcustom query-replace-skip-read-only nil
110 "Non-nil means `query-replace' and friends ignore read-only matches."
115 (defcustom query-replace-show-replacement t
116 "Non-nil means show substituted replacement text in the minibuffer.
117 This variable affects only `query-replace-regexp'."
122 (defcustom query-replace-highlight t
123 "Non-nil means to highlight matches during query replacement."
127 (defcustom query-replace-lazy-highlight t
128 "Controls the lazy-highlighting during query replacements.
129 When non-nil, all text in the buffer matching the current match
130 is highlighted lazily using isearch lazy highlighting (see
131 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
133 :group 'lazy-highlight
137 (defface query-replace
138 '((t (:inherit isearch)))
139 "Face for highlighting query replacement matches."
143 (defvar replace-count 0
144 "Number of replacements done so far.
145 See `replace-regexp' and `query-replace-regexp-eval'.")
147 (defun query-replace-descr (string)
148 (mapconcat 'isearch-text-char-description string ""))
150 (defun query-replace--split-string (string)
151 "Split string STRING at a character with property `separator'"
152 (let* ((length (length string))
153 (split-pos (text-property-any 0 length 'separator t string)))
155 (substring-no-properties string)
156 (cl-assert (not (text-property-any (1+ split-pos) length 'separator t string)))
157 (cons (substring-no-properties string 0 split-pos)
158 (substring-no-properties string (1+ split-pos) length)))))
160 (defun query-replace-read-from (prompt regexp-flag)
161 "Query and return the `from' argument of a query-replace operation.
162 The return value can also be a pair (FROM . TO) indicating that the user
163 wants to replace FROM with TO."
164 (if query-replace-interactive
165 (car (if regexp-flag regexp-search-ring search-ring))
166 ;; Reevaluating will check char-displayable-p that is
167 ;; unavailable while preparing to dump.
168 (custom-reevaluate-setting 'query-replace-from-to-separator)
169 (let* ((history-add-new-input nil)
170 (text-property-default-nonsticky
171 (cons '(separator . t) text-property-default-nonsticky))
173 (when query-replace-from-to-separator
175 'display query-replace-from-to-separator
177 (query-replace-from-to-history
180 (mapcar (lambda (from-to)
181 (concat (query-replace-descr (car from-to))
183 (query-replace-descr (cdr from-to))))
184 query-replace-defaults))
185 (symbol-value query-replace-from-history-variable)))
186 (minibuffer-allow-text-properties t) ; separator uses text-properties
188 (if (and query-replace-defaults separator)
189 (format "%s (default %s): " prompt (car query-replace-from-to-history))
190 (format "%s: " prompt)))
192 ;; The save-excursion here is in case the user marks and copies
193 ;; a region in order to specify the minibuffer input.
194 ;; That should not clobber the region for the query-replace itself.
197 (read-regexp prompt nil 'query-replace-from-to-history)
198 (read-from-minibuffer
199 prompt nil nil nil 'query-replace-from-to-history
200 (car (if regexp-flag regexp-search-ring search-ring)) t))))
202 (if (and (zerop (length from)) query-replace-defaults)
203 (cons (caar query-replace-defaults)
204 (query-replace-compile-replacement
205 (cdar query-replace-defaults) regexp-flag))
206 (setq from (query-replace--split-string from))
207 (when (consp from) (setq to (cdr from) from (car from)))
208 (add-to-history query-replace-from-history-variable from nil t)
209 ;; Warn if user types \n or \t, but don't reject the input.
211 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
212 (let ((match (match-string 3 from)))
214 ((string= match "\\n")
215 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
216 ((string= match "\\t")
217 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
221 (add-to-history query-replace-to-history-variable to nil t)
222 (add-to-history 'query-replace-defaults (cons from to) nil t)
223 (cons from (query-replace-compile-replacement to regexp-flag)))))))
225 (defun query-replace-compile-replacement (to regexp-flag)
226 "Maybe convert a regexp replacement TO to Lisp.
227 Returns a list suitable for `perform-replace' if necessary,
228 the original string if not."
230 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
234 (setq pos (match-end 0))
235 (push (substring to 0 (- pos 2)) list)
236 (setq char (aref to (1- pos))
237 to (substring to pos))
239 (push '(number-to-string replace-count) list))
241 (setq pos (read-from-string to))
242 (push `(replace-quote ,(car pos)) list)
244 ;; Swallow a space after a symbol
245 ;; if there is a space.
246 (if (and (or (symbolp (car pos))
247 ;; Swallow a space after 'foo
248 ;; but not after (quote foo).
249 (and (eq (car-safe (car pos)) 'quote)
250 (not (= ?\( (aref to 0)))))
251 (eq (string-match " " to (cdr pos))
255 (setq to (substring to end)))))
256 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
257 (setq to (nreverse (delete "" (cons to list))))
258 (replace-match-string-symbols to)
259 (cons 'replace-eval-replacement
266 (defun query-replace-read-to (from prompt regexp-flag)
267 "Query and return the `to' argument of a query-replace operation."
268 (query-replace-compile-replacement
270 (let* ((history-add-new-input nil)
271 (to (read-from-minibuffer
272 (format "%s %s with: " prompt (query-replace-descr from))
274 query-replace-to-history-variable from t)))
275 (add-to-history query-replace-to-history-variable to nil t)
276 (add-to-history 'query-replace-defaults (cons from to) nil t)
280 (defun query-replace-read-args (prompt regexp-flag &optional noerror)
282 (barf-if-buffer-read-only))
283 (let* ((from (query-replace-read-from prompt regexp-flag))
284 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
285 (query-replace-read-to from prompt regexp-flag))))
287 (and current-prefix-arg (not (eq current-prefix-arg '-)))
288 (and current-prefix-arg (eq current-prefix-arg '-)))))
290 (defun query-replace (from-string to-string &optional delimited start end backward region-noncontiguous-p)
291 "Replace some occurrences of FROM-STRING with TO-STRING.
292 As each match is found, the user must type a character saying
293 what to do with it. For directions, type \\[help-command] at that time.
295 In Transient Mark mode, if the mark is active, operate on the contents
296 of the region. Otherwise, operate from point to the end of the buffer's
299 Use \\<minibuffer-local-map>\\[next-history-element] \
300 to pull the last incremental search string to the minibuffer
301 that reads FROM-STRING, or invoke replacements from
302 incremental search with a key sequence like `C-s C-s M-%'
303 to use its current search string as the string to replace.
305 Matching is independent of case if `case-fold-search' is non-nil and
306 FROM-STRING has no uppercase letters. Replacement transfers the case
307 pattern of the old text to the new text, if `case-replace' and
308 `case-fold-search' are non-nil and FROM-STRING has no uppercase
309 letters. (Transferring the case pattern means that if the old text
310 matched is all caps, or capitalized, then its replacement is upcased
313 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
314 ignore hidden matches if `search-invisible' is nil, and ignore more
315 matches using `isearch-filter-predicate'.
317 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
318 to be replaced will match a sequence of whitespace chars defined by the
319 regexp in `search-whitespace-regexp'.
321 If `replace-character-fold' is non-nil, matching uses character folding,
322 i.e. it ignores diacritics and other differences between equivalent
325 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
326 only matches surrounded by word boundaries. A negative prefix arg means
329 Fourth and fifth arg START and END specify the region to operate on.
331 To customize possible responses, change the bindings in `query-replace-map'."
334 (query-replace-read-args
335 (concat "Query replace"
336 (if current-prefix-arg
337 (if (eq current-prefix-arg '-) " backward" " word")
339 (if (use-region-p) " in region" ""))
341 (list (nth 0 common) (nth 1 common) (nth 2 common)
342 ;; These are done separately here
343 ;; so that command-history will record these expressions
344 ;; rather than the values they had this time.
345 (if (use-region-p) (region-beginning))
346 (if (use-region-p) (region-end))
348 (if (use-region-p) (region-noncontiguous-p)))))
349 (perform-replace from-string to-string t nil delimited nil nil start end backward region-noncontiguous-p))
351 (define-key esc-map "%" 'query-replace)
353 (defun query-replace-regexp (regexp to-string &optional delimited start end backward region-noncontiguous-p)
354 "Replace some things after point matching REGEXP with TO-STRING.
355 As each match is found, the user must type a character saying
356 what to do with it. For directions, type \\[help-command] at that time.
358 In Transient Mark mode, if the mark is active, operate on the contents
359 of the region. Otherwise, operate from point to the end of the buffer's
362 Use \\<minibuffer-local-map>\\[next-history-element] \
363 to pull the last incremental search regexp to the minibuffer
364 that reads REGEXP, or invoke replacements from
365 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
366 to use its current search regexp as the regexp to replace.
368 Matching is independent of case if `case-fold-search' is non-nil and
369 REGEXP has no uppercase letters. Replacement transfers the case
370 pattern of the old text to the new text, if `case-replace' and
371 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
372 \(Transferring the case pattern means that if the old text matched is
373 all caps, or capitalized, then its replacement is upcased or
376 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
377 ignore hidden matches if `search-invisible' is nil, and ignore more
378 matches using `isearch-filter-predicate'.
380 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
381 to be replaced will match a sequence of whitespace chars defined by the
382 regexp in `search-whitespace-regexp'.
384 This function is not affected by `replace-character-fold'.
386 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
387 only matches surrounded by word boundaries. A negative prefix arg means
390 Fourth and fifth arg START and END specify the region to operate on.
392 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
393 and `\\=\\N' (where N is a digit) stands for
394 whatever what matched the Nth `\\(...\\)' in REGEXP.
395 `\\?' lets you edit the replacement text in the minibuffer
396 at the given position for each replacement.
398 In interactive calls, the replacement text can contain `\\,'
399 followed by a Lisp expression. Each
400 replacement evaluates that expression to compute the replacement
401 string. Inside of that expression, `\\&' is a string denoting the
402 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
403 for the whole or a partial match converted to a number with
404 `string-to-number', and `\\#' itself for the number of replacements
405 done so far (starting with zero).
407 If the replacement expression is a symbol, write a space after it
408 to terminate it. One space there, if any, will be discarded.
410 When using those Lisp features interactively in the replacement
411 text, TO-STRING is actually made a list instead of a string.
412 Use \\[repeat-complex-command] after this command for details."
415 (query-replace-read-args
416 (concat "Query replace"
417 (if current-prefix-arg
418 (if (eq current-prefix-arg '-) " backward" " word")
421 (if (use-region-p) " in region" ""))
423 (list (nth 0 common) (nth 1 common) (nth 2 common)
424 ;; These are done separately here
425 ;; so that command-history will record these expressions
426 ;; rather than the values they had this time.
427 (if (use-region-p) (region-beginning))
428 (if (use-region-p) (region-end))
430 (if (use-region-p) (region-noncontiguous-p)))))
431 (perform-replace regexp to-string t t delimited nil nil start end backward region-noncontiguous-p))
433 (define-key esc-map [?\C-%] 'query-replace-regexp)
435 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
436 "Replace some things after point matching REGEXP with the result of TO-EXPR.
438 Interactive use of this function is deprecated in favor of the
439 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
440 using `search-forward-regexp' and `replace-match' is preferred.
442 As each match is found, the user must type a character saying
443 what to do with it. For directions, type \\[help-command] at that time.
445 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
446 reference `replace-count' to get the number of replacements already made.
447 If the result of TO-EXPR is not a string, it is converted to one using
448 `prin1-to-string' with the NOESCAPE argument (which see).
450 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
451 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
452 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
453 Use `\\#&' or `\\#N' if you want a number instead of a string.
454 In interactive use, `\\#' in itself stands for `replace-count'.
456 In Transient Mark mode, if the mark is active, operate on the contents
457 of the region. Otherwise, operate from point to the end of the buffer's
460 Use \\<minibuffer-local-map>\\[next-history-element] \
461 to pull the last incremental search regexp to the minibuffer
464 Preserves case in each replacement if `case-replace' and `case-fold-search'
465 are non-nil and REGEXP has no uppercase letters.
467 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
468 ignore hidden matches if `search-invisible' is nil, and ignore more
469 matches using `isearch-filter-predicate'.
471 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
472 to be replaced will match a sequence of whitespace chars defined by the
473 regexp in `search-whitespace-regexp'.
475 This function is not affected by `replace-character-fold'.
477 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
478 only matches that are surrounded by word boundaries.
479 Fourth and fifth arg START and END specify the region to operate on."
480 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
481 for interactive calls, and `search-forward-regexp'/`replace-match'
482 for Lisp calls." "22.1"))
485 (barf-if-buffer-read-only)
487 ;; Let-bind the history var to disable the "foo -> bar"
488 ;; default. Maybe we shouldn't disable this default, but
489 ;; for now I'll leave it off. --Stef
490 (let ((query-replace-defaults nil))
491 (query-replace-read-from "Query replace regexp" t)))
492 (to (list (read-from-minibuffer
493 (format "Query replace regexp %s with eval: "
494 (query-replace-descr from))
495 nil nil t query-replace-to-history-variable from t))))
496 ;; We make TO a list because replace-match-string-symbols requires one,
497 ;; and the user might enter a single token.
498 (replace-match-string-symbols to)
499 (list from (car to) current-prefix-arg
500 (if (use-region-p) (region-beginning))
501 (if (use-region-p) (region-end))))))
502 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
503 t 'literal delimited nil nil start end))
505 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
506 "Replace some matches for REGEXP with various strings, in rotation.
507 The second argument TO-STRINGS contains the replacement strings, separated
508 by spaces. This command works like `query-replace-regexp' except that
509 each successive replacement uses the next successive replacement string,
510 wrapping around from the last such string to the first.
512 In Transient Mark mode, if the mark is active, operate on the contents
513 of the region. Otherwise, operate from point to the end of the buffer's
516 Non-interactively, TO-STRINGS may be a list of replacement strings.
518 Interactively, reads the regexp using `read-regexp'.
519 Use \\<minibuffer-local-map>\\[next-history-element] \
520 to pull the last incremental search regexp to the minibuffer
523 A prefix argument N says to use each replacement string N times
524 before rotating to the next.
525 Fourth and fifth arg START and END specify the region to operate on."
527 (let* ((from (read-regexp "Map query replace (regexp): " nil
528 query-replace-from-history-variable))
529 (to (read-from-minibuffer
530 (format "Query replace %s with (space-separated strings): "
531 (query-replace-descr from))
533 query-replace-to-history-variable from t)))
535 (and current-prefix-arg
536 (prefix-numeric-value current-prefix-arg))
537 (if (use-region-p) (region-beginning))
538 (if (use-region-p) (region-end)))))
540 (if (listp to-strings)
541 (setq replacements to-strings)
542 (while (/= (length to-strings) 0)
543 (if (string-match " " to-strings)
546 (list (substring to-strings 0
547 (string-match " " to-strings))))
548 to-strings (substring to-strings
549 (1+ (string-match " " to-strings))))
550 (setq replacements (append replacements (list to-strings))
552 (perform-replace regexp replacements t t nil n nil start end)))
554 (defun replace-string (from-string to-string &optional delimited start end backward)
555 "Replace occurrences of FROM-STRING with TO-STRING.
556 Preserve case in each match if `case-replace' and `case-fold-search'
557 are non-nil and FROM-STRING has no uppercase letters.
558 \(Preserving case means that if the string matched is all caps, or capitalized,
559 then its replacement is upcased or capitalized.)
561 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
562 ignore hidden matches if `search-invisible' is nil, and ignore more
563 matches using `isearch-filter-predicate'.
565 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
566 to be replaced will match a sequence of whitespace chars defined by the
567 regexp in `search-whitespace-regexp'.
569 If `replace-character-fold' is non-nil, matching uses character folding,
570 i.e. it ignores diacritics and other differences between equivalent
573 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
574 only matches surrounded by word boundaries. A negative prefix arg means
577 Operates on the region between START and END (if both are nil, from point
578 to the end of the buffer). Interactively, if Transient Mark mode is
579 enabled and the mark is active, operates on the contents of the region;
580 otherwise from point to the end of the buffer's accessible portion.
582 Use \\<minibuffer-local-map>\\[next-history-element] \
583 to pull the last incremental search string to the minibuffer
584 that reads FROM-STRING.
586 This function is usually the wrong thing to use in a Lisp program.
587 What you probably want is a loop like this:
588 (while (search-forward FROM-STRING nil t)
589 (replace-match TO-STRING nil t))
590 which will run faster and will not set the mark or print anything.
591 \(You may need a more complex loop if FROM-STRING can match the null string
592 and TO-STRING is also null.)"
593 (declare (interactive-only
594 "use `search-forward' and `replace-match' instead."))
597 (query-replace-read-args
599 (if current-prefix-arg
600 (if (eq current-prefix-arg '-) " backward" " word")
603 (if (use-region-p) " in region" ""))
605 (list (nth 0 common) (nth 1 common) (nth 2 common)
606 (if (use-region-p) (region-beginning))
607 (if (use-region-p) (region-end))
609 (perform-replace from-string to-string nil nil delimited nil nil start end backward))
611 (defun replace-regexp (regexp to-string &optional delimited start end backward)
612 "Replace things after point matching REGEXP with TO-STRING.
613 Preserve case in each match if `case-replace' and `case-fold-search'
614 are non-nil and REGEXP has no uppercase letters.
616 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
617 ignore hidden matches if `search-invisible' is nil, and ignore more
618 matches using `isearch-filter-predicate'.
620 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
621 to be replaced will match a sequence of whitespace chars defined by the
622 regexp in `search-whitespace-regexp'.
624 This function is not affected by `replace-character-fold'
626 In Transient Mark mode, if the mark is active, operate on the contents
627 of the region. Otherwise, operate from point to the end of the buffer's
630 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
631 only matches surrounded by word boundaries. A negative prefix arg means
634 Fourth and fifth arg START and END specify the region to operate on.
636 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
637 and `\\=\\N' (where N is a digit) stands for
638 whatever what matched the Nth `\\(...\\)' in REGEXP.
639 `\\?' lets you edit the replacement text in the minibuffer
640 at the given position for each replacement.
642 In interactive calls, the replacement text may contain `\\,'
643 followed by a Lisp expression used as part of the replacement
644 text. Inside of that expression, `\\&' is a string denoting the
645 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
646 numeric values from `string-to-number', and `\\#' itself for
647 `replace-count', the number of replacements occurred so far.
649 If your Lisp expression is an identifier and the next letter in
650 the replacement string would be interpreted as part of it, you
651 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
652 for this particular case you may also enter `\\#' in the
653 replacement text directly.
655 When using those Lisp features interactively in the replacement
656 text, TO-STRING is actually made a list instead of a string.
657 Use \\[repeat-complex-command] after this command for details.
659 Use \\<minibuffer-local-map>\\[next-history-element] \
660 to pull the last incremental search regexp to the minibuffer
663 This function is usually the wrong thing to use in a Lisp program.
664 What you probably want is a loop like this:
665 (while (re-search-forward REGEXP nil t)
666 (replace-match TO-STRING nil nil))
667 which will run faster and will not set the mark or print anything."
668 (declare (interactive-only
669 "use `re-search-forward' and `replace-match' instead."))
672 (query-replace-read-args
674 (if current-prefix-arg
675 (if (eq current-prefix-arg '-) " backward" " word")
678 (if (use-region-p) " in region" ""))
680 (list (nth 0 common) (nth 1 common) (nth 2 common)
681 (if (use-region-p) (region-beginning))
682 (if (use-region-p) (region-end))
684 (perform-replace regexp to-string nil t delimited nil nil start end backward))
687 (defvar regexp-history nil
688 "History list for some commands that read regular expressions.
690 Maximum length of the history list is determined by the value
691 of `history-length', which see.")
693 (defvar occur-collect-regexp-history '("\\1")
694 "History of regexp for occur's collect operation")
696 (defcustom read-regexp-defaults-function nil
697 "Function that provides default regexp(s) for `read-regexp'.
698 This function should take no arguments and return one of: nil, a
699 regexp, or a list of regexps. Interactively, `read-regexp' uses
700 the return value of this function for its DEFAULT argument.
702 As an example, set this variable to `find-tag-default-as-regexp'
703 to default to the symbol at point.
705 To provide different default regexps for different commands,
706 the function that you set this to can check `this-command'."
708 (const :tag "No default regexp reading function" nil)
709 (const :tag "Latest regexp history" regexp-history-last)
710 (function-item :tag "Tag at point"
712 (function-item :tag "Tag at point as regexp"
713 find-tag-default-as-regexp)
714 (function-item :tag "Tag at point as symbol regexp"
715 find-tag-default-as-symbol-regexp)
716 (function :tag "Your choice of function"))
720 (defun read-regexp-suggestions ()
721 "Return a list of standard suggestions for `read-regexp'.
722 By default, the list includes the tag at point, the last isearch regexp,
723 the last isearch string, and the last replacement regexp. `read-regexp'
724 appends the list returned by this function to the end of values available
725 via \\<minibuffer-local-map>\\[next-history-element]."
727 (find-tag-default-as-regexp)
728 (find-tag-default-as-symbol-regexp)
729 (car regexp-search-ring)
730 (regexp-quote (or (car search-ring) ""))
731 (car (symbol-value query-replace-from-history-variable))))
733 (defun read-regexp (prompt &optional defaults history)
734 "Read and return a regular expression as a string.
735 Prompt with the string PROMPT. If PROMPT ends in \":\" (followed by
736 optional whitespace), use it as-is. Otherwise, add \": \" to the end,
737 possibly preceded by the default result (see below).
739 The optional argument DEFAULTS can be either: nil, a string, a list
740 of strings, or a symbol. We use DEFAULTS to construct the default
741 return value in case of empty input.
743 If DEFAULTS is a string, we use it as-is.
745 If DEFAULTS is a list of strings, the first element is the
746 default return value, but all the elements are accessible
747 using the history command \\<minibuffer-local-map>\\[next-history-element].
749 If DEFAULTS is a non-nil symbol, then if `read-regexp-defaults-function'
750 is non-nil, we use that in place of DEFAULTS in the following:
751 If DEFAULTS is the symbol `regexp-history-last', we use the first
752 element of HISTORY (if specified) or `regexp-history'.
753 If DEFAULTS is a function, we call it with no arguments and use
754 what it returns, which should be either nil, a string, or a list of strings.
756 We append the standard values from `read-regexp-suggestions' to DEFAULTS
759 If the first element of DEFAULTS is non-nil (and if PROMPT does not end
760 in \":\", followed by optional whitespace), we add it to the prompt.
762 The optional argument HISTORY is a symbol to use for the history list.
763 If nil, uses `regexp-history'."
765 (if (and defaults (symbolp defaults))
767 ((eq (or read-regexp-defaults-function defaults)
768 'regexp-history-last)
769 (car (symbol-value (or history 'regexp-history))))
770 ((functionp (or read-regexp-defaults-function defaults))
771 (funcall (or read-regexp-defaults-function defaults))))
773 (default (if (consp defaults) (car defaults) defaults))
774 (suggestions (if (listp defaults) defaults (list defaults)))
775 (suggestions (append suggestions (read-regexp-suggestions)))
776 (suggestions (delete-dups (delq nil (delete "" suggestions))))
777 ;; Do not automatically add default to the history for empty input.
778 (history-add-new-input nil)
779 (input (read-from-minibuffer
780 (cond ((string-match-p ":[ \t]*\\'" prompt)
782 ((and default (> (length default) 0))
783 (format "%s (default %s): " prompt
784 (query-replace-descr default)))
786 (format "%s: " prompt)))
787 nil nil nil (or history 'regexp-history) suggestions t)))
789 ;; Return the default value when the user enters empty input.
790 (prog1 (or default input)
792 (add-to-history (or history 'regexp-history) default)))
793 ;; Otherwise, add non-empty input to the history and return input.
795 (add-to-history (or history 'regexp-history) input)))))
798 (defalias 'delete-non-matching-lines 'keep-lines)
799 (defalias 'delete-matching-lines 'flush-lines)
800 (defalias 'count-matches 'how-many)
803 (defun keep-lines-read-args (prompt)
804 "Read arguments for `keep-lines' and friends.
805 Prompt for a regexp with PROMPT.
806 Value is a list, (REGEXP)."
807 (list (read-regexp prompt) nil nil t))
809 (defun keep-lines (regexp &optional rstart rend interactive)
810 "Delete all lines except those containing matches for REGEXP.
811 A match split across lines preserves all the lines it lies in.
812 When called from Lisp (and usually interactively as well, see below)
813 applies to all lines starting after point.
815 If REGEXP contains upper case characters (excluding those preceded by `\\')
816 and `search-upper-case' is non-nil, the matching is case-sensitive.
818 Second and third arg RSTART and REND specify the region to operate on.
819 This command operates on (the accessible part of) all lines whose
820 accessible part is entirely contained in the region determined by RSTART
821 and REND. (A newline ending a line counts as part of that line.)
823 Interactively, in Transient Mark mode when the mark is active, operate
824 on all lines whose accessible part is entirely contained in the region.
825 Otherwise, the command applies to all lines starting after point.
826 When calling this function from Lisp, you can pretend that it was
827 called interactively by passing a non-nil INTERACTIVE argument.
829 This function starts looking for the next match from the end of
830 the previous match. Hence, it ignores matches that overlap
831 a previously found match."
835 (barf-if-buffer-read-only)
836 (keep-lines-read-args "Keep lines containing match for regexp")))
839 (goto-char (min rstart rend))
843 (goto-char (max rstart rend))
844 (unless (or (bolp) (eobp))
847 (if (and interactive (use-region-p))
848 (setq rstart (region-beginning)
850 (goto-char (region-end))
851 (unless (or (bolp) (eobp))
855 rend (point-max-marker)))
858 (or (bolp) (forward-line 1))
859 (let ((start (point))
861 (if (and case-fold-search search-upper-case)
862 (isearch-no-upper-case-p regexp t)
864 (while (< (point) rend)
865 ;; Start is first char not preserved by previous match.
866 (if (not (re-search-forward regexp rend 'move))
867 (delete-region start rend)
868 (let ((end (save-excursion (goto-char (match-beginning 0))
871 ;; Now end is first char preserved by the new match.
873 (delete-region start end))))
875 (setq start (save-excursion (forward-line 1) (point)))
876 ;; If the match was empty, avoid matching again at same place.
877 (and (< (point) rend)
878 (= (match-beginning 0) (match-end 0))
880 (set-marker rend nil)
884 (defun flush-lines (regexp &optional rstart rend interactive)
885 "Delete lines containing matches for REGEXP.
886 When called from Lisp (and usually when called interactively as
887 well, see below), applies to the part of the buffer after point.
888 The line point is in is deleted if and only if it contains a
889 match for regexp starting after point.
891 If REGEXP contains upper case characters (excluding those preceded by `\\')
892 and `search-upper-case' is non-nil, the matching is case-sensitive.
894 Second and third arg RSTART and REND specify the region to operate on.
895 Lines partially contained in this region are deleted if and only if
896 they contain a match entirely contained in it.
898 Interactively, in Transient Mark mode when the mark is active, operate
899 on the contents of the region. Otherwise, operate from point to the
900 end of (the accessible portion of) the buffer. When calling this function
901 from Lisp, you can pretend that it was called interactively by passing
902 a non-nil INTERACTIVE argument.
904 If a match is split across lines, all the lines it lies in are deleted.
905 They are deleted _before_ looking for the next match. Hence, a match
906 starting on the same line at which another match ended is ignored."
910 (barf-if-buffer-read-only)
911 (keep-lines-read-args "Flush lines containing match for regexp")))
914 (goto-char (min rstart rend))
915 (setq rend (copy-marker (max rstart rend))))
916 (if (and interactive (use-region-p))
917 (setq rstart (region-beginning)
918 rend (copy-marker (region-end)))
920 rend (point-max-marker)))
922 (let ((case-fold-search
923 (if (and case-fold-search search-upper-case)
924 (isearch-no-upper-case-p regexp t)
927 (while (and (< (point) rend)
928 (re-search-forward regexp rend t))
929 (delete-region (save-excursion (goto-char (match-beginning 0))
932 (progn (forward-line 1) (point))))))
933 (set-marker rend nil)
937 (defun how-many (regexp &optional rstart rend interactive)
938 "Print and return number of matches for REGEXP following point.
939 When called from Lisp and INTERACTIVE is omitted or nil, just return
940 the number, do not print it; if INTERACTIVE is t, the function behaves
941 in all respects as if it had been called interactively.
943 If REGEXP contains upper case characters (excluding those preceded by `\\')
944 and `search-upper-case' is non-nil, the matching is case-sensitive.
946 Second and third arg RSTART and REND specify the region to operate on.
948 Interactively, in Transient Mark mode when the mark is active, operate
949 on the contents of the region. Otherwise, operate from point to the
950 end of (the accessible portion of) the buffer.
952 This function starts looking for the next match from the end of
953 the previous match. Hence, it ignores matches that overlap
954 a previously found match."
957 (keep-lines-read-args "How many matches for regexp"))
962 (goto-char (min rstart rend))
963 (setq rend (max rstart rend)))
965 (setq rend (point-max)))
966 (if (and interactive (use-region-p))
967 (setq rstart (region-beginning)
975 (if (and case-fold-search search-upper-case)
976 (isearch-no-upper-case-p regexp t)
978 (while (and (< (point) rend)
979 (progn (setq opoint (point))
980 (re-search-forward regexp rend t)))
981 (if (= opoint (point))
983 (setq count (1+ count))))
984 (when interactive (message "%d occurrence%s"
986 (if (= count 1) "" "s")))
990 (defvar occur-menu-map
991 (let ((map (make-sparse-keymap)))
992 (bindings--define-key map [next-error-follow-minor-mode]
993 '(menu-item "Auto Occurrence Display"
994 next-error-follow-minor-mode
995 :help "Display another occurrence when moving the cursor"
996 :button (:toggle . (and (boundp 'next-error-follow-minor-mode)
997 next-error-follow-minor-mode))))
998 (bindings--define-key map [separator-1] menu-bar-separator)
999 (bindings--define-key map [kill-this-buffer]
1000 '(menu-item "Kill Occur Buffer" kill-this-buffer
1001 :help "Kill the current *Occur* buffer"))
1002 (bindings--define-key map [quit-window]
1003 '(menu-item "Quit Occur Window" quit-window
1004 :help "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
1005 (bindings--define-key map [revert-buffer]
1006 '(menu-item "Revert Occur Buffer" revert-buffer
1007 :help "Replace the text in the *Occur* buffer with the results of rerunning occur"))
1008 (bindings--define-key map [clone-buffer]
1009 '(menu-item "Clone Occur Buffer" clone-buffer
1010 :help "Create and return a twin copy of the current *Occur* buffer"))
1011 (bindings--define-key map [occur-rename-buffer]
1012 '(menu-item "Rename Occur Buffer" occur-rename-buffer
1013 :help "Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
1014 (bindings--define-key map [occur-edit-buffer]
1015 '(menu-item "Edit Occur Buffer" occur-edit-mode
1016 :help "Edit the *Occur* buffer and apply changes to the original buffers."))
1017 (bindings--define-key map [separator-2] menu-bar-separator)
1018 (bindings--define-key map [occur-mode-goto-occurrence-other-window]
1019 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
1020 :help "Go to the occurrence the current line describes, in another window"))
1021 (bindings--define-key map [occur-mode-goto-occurrence]
1022 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
1023 :help "Go to the occurrence the current line describes"))
1024 (bindings--define-key map [occur-mode-display-occurrence]
1025 '(menu-item "Display Occurrence" occur-mode-display-occurrence
1026 :help "Display in another window the occurrence the current line describes"))
1027 (bindings--define-key map [occur-next]
1028 '(menu-item "Move to Next Match" occur-next
1029 :help "Move to the Nth (default 1) next match in an Occur mode buffer"))
1030 (bindings--define-key map [occur-prev]
1031 '(menu-item "Move to Previous Match" occur-prev
1032 :help "Move to the Nth (default 1) previous match in an Occur mode buffer"))
1034 "Menu keymap for `occur-mode'.")
1036 (defvar occur-mode-map
1037 (let ((map (make-sparse-keymap)))
1038 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
1039 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1040 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
1041 (define-key map "e" 'occur-edit-mode)
1042 (define-key map "\C-m" 'occur-mode-goto-occurrence)
1043 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
1044 (define-key map "\C-o" 'occur-mode-display-occurrence)
1045 (define-key map "\M-n" 'occur-next)
1046 (define-key map "\M-p" 'occur-prev)
1047 (define-key map "r" 'occur-rename-buffer)
1048 (define-key map "c" 'clone-buffer)
1049 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1050 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1052 "Keymap for `occur-mode'.")
1054 (defvar occur-revert-arguments nil
1055 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
1056 See `occur-revert-function'.")
1057 (make-variable-buffer-local 'occur-revert-arguments)
1058 (put 'occur-revert-arguments 'permanent-local t)
1060 (defcustom occur-mode-hook '(turn-on-font-lock)
1061 "Hook run when entering Occur mode."
1065 (defcustom occur-hook nil
1066 "Hook run by Occur when there are any matches."
1070 (defcustom occur-mode-find-occurrence-hook nil
1071 "Hook run by Occur after locating an occurrence.
1072 This will be called with the cursor position at the occurrence. An application
1073 for this is to reveal context in an outline-mode when the occurrence is hidden."
1077 (put 'occur-mode 'mode-class 'special)
1078 (define-derived-mode occur-mode special-mode "Occur"
1079 "Major mode for output from \\[occur].
1080 \\<occur-mode-map>Move point to one of the items in this buffer, then use
1081 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
1082 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
1085 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
1086 (setq next-error-function 'occur-next-error))
1091 (defvar occur-edit-mode-map
1092 (let ((map (make-sparse-keymap)))
1093 (set-keymap-parent map text-mode-map)
1094 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1095 (define-key map "\C-c\C-c" 'occur-cease-edit)
1096 (define-key map "\C-o" 'occur-mode-display-occurrence)
1097 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1098 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1100 "Keymap for `occur-edit-mode'.")
1102 (define-derived-mode occur-edit-mode occur-mode "Occur-Edit"
1103 "Major mode for editing *Occur* buffers.
1104 In this mode, changes to the *Occur* buffer are also applied to
1105 the originating buffer.
1107 To return to ordinary Occur mode, use \\[occur-cease-edit]."
1108 (setq buffer-read-only nil)
1109 (add-hook 'after-change-functions 'occur-after-change-function nil t)
1110 (message (substitute-command-keys
1111 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
1113 (defun occur-cease-edit ()
1114 "Switch from Occur Edit mode to Occur mode."
1116 (when (derived-mode-p 'occur-edit-mode)
1118 (message "Switching to Occur mode.")))
1120 (defun occur-after-change-function (beg end length)
1123 (let* ((line-beg (line-beginning-position))
1124 (m (get-text-property line-beg 'occur-target))
1125 (buf (marker-buffer m))
1127 (when (and (get-text-property line-beg 'occur-prefix)
1128 (not (get-text-property end 'occur-prefix)))
1130 ;; Apply occur-target property to inserted (e.g. yanked) text.
1131 (put-text-property beg end 'occur-target m)
1132 ;; Did we insert a newline? Occur Edit mode can't create new
1133 ;; Occur entries; just discard everything after the newline.
1135 (and (search-forward "\n" end t)
1136 (delete-region (1- (point)) end))))
1137 (let* ((line (- (line-number-at-pos)
1138 (line-number-at-pos (window-start))))
1139 (readonly (with-current-buffer buf buffer-read-only))
1140 (win (or (get-buffer-window buf)
1142 '(nil (inhibit-same-window . t)
1143 (inhibit-switch-frame . t)))))
1144 (line-end (line-end-position))
1145 (text (save-excursion
1146 (goto-char (next-single-property-change
1147 line-beg 'occur-prefix nil
1149 (setq col (- (point) line-beg))
1150 (buffer-substring-no-properties (point) line-end))))
1151 (with-selected-window win
1155 (message "Buffer `%s' is read only." buf)
1156 (delete-region (line-beginning-position) (line-end-position))
1158 (move-to-column col)))))))
1161 (defun occur-revert-function (_ignore1 _ignore2)
1162 "Handle `revert-buffer' for Occur mode buffers."
1163 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
1165 (defun occur-mode-find-occurrence ()
1166 (let ((pos (get-text-property (point) 'occur-target)))
1168 (error "No occurrence on this line"))
1169 (unless (buffer-live-p (marker-buffer pos))
1170 (error "Buffer for this occurrence was killed"))
1173 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
1174 (defun occur-mode-goto-occurrence (&optional event)
1175 "Go to the occurrence on the current line."
1176 (interactive (list last-nonmenu-event))
1179 ;; Actually `event-end' works correctly with a nil argument as
1180 ;; well, so we could dispense with this test, but let's not
1181 ;; rely on this undocumented behavior.
1182 (occur-mode-find-occurrence)
1183 (with-current-buffer (window-buffer (posn-window (event-end event)))
1185 (goto-char (posn-point (event-end event)))
1186 (occur-mode-find-occurrence))))))
1187 (pop-to-buffer (marker-buffer pos))
1189 (run-hooks 'occur-mode-find-occurrence-hook)))
1191 (defun occur-mode-goto-occurrence-other-window ()
1192 "Go to the occurrence the current line describes, in another window."
1194 (let ((pos (occur-mode-find-occurrence)))
1195 (switch-to-buffer-other-window (marker-buffer pos))
1197 (run-hooks 'occur-mode-find-occurrence-hook)))
1199 (defun occur-mode-display-occurrence ()
1200 "Display in another window the occurrence the current line describes."
1202 (let ((pos (occur-mode-find-occurrence))
1204 (setq window (display-buffer (marker-buffer pos) t))
1205 ;; This is the way to set point in the proper window.
1206 (save-selected-window
1207 (select-window window)
1209 (run-hooks 'occur-mode-find-occurrence-hook))))
1211 (defun occur-find-match (n search message)
1212 (if (not n) (setq n 1))
1215 (setq r (funcall search (point) 'occur-match))
1217 (get-text-property r 'occur-match)
1218 (setq r (funcall search r 'occur-match)))
1224 (defun occur-next (&optional n)
1225 "Move to the Nth (default 1) next match in an Occur mode buffer."
1227 (occur-find-match n #'next-single-property-change "No more matches"))
1229 (defun occur-prev (&optional n)
1230 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1232 (occur-find-match n #'previous-single-property-change "No earlier matches"))
1234 (defun occur-next-error (&optional argp reset)
1235 "Move to the Nth (default 1) next match in an Occur mode buffer.
1236 Compatibility function for \\[next-error] invocations."
1238 ;; we need to run occur-find-match from within the Occur buffer
1239 (with-current-buffer
1240 ;; Choose the buffer and make it current.
1241 (if (next-error-buffer-p (current-buffer))
1243 (next-error-find-buffer nil nil
1245 (eq major-mode 'occur-mode))))
1247 (goto-char (cond (reset (point-min))
1248 ((< argp 0) (line-beginning-position))
1249 ((> argp 0) (line-end-position))
1254 #'previous-single-property-change
1255 #'next-single-property-change)
1257 ;; In case the *Occur* buffer is visible in a nonselected window.
1258 (let ((win (get-buffer-window (current-buffer) t)))
1259 (if win (set-window-point win (point))))
1260 (occur-mode-goto-occurrence)))
1263 '((((class color) (min-colors 88) (background light))
1264 :background "yellow1")
1265 (((class color) (min-colors 88) (background dark))
1266 :background "RoyalBlue3")
1267 (((class color) (min-colors 8) (background light))
1268 :background "yellow" :foreground "black")
1269 (((class color) (min-colors 8) (background dark))
1270 :background "blue" :foreground "white")
1271 (((type tty) (class mono))
1273 (t :background "gray"))
1274 "Face used to highlight matches permanently."
1279 (defcustom list-matching-lines-default-context-lines 0
1280 "Default number of context lines included around `list-matching-lines' matches.
1281 A negative number means to include that many lines before the match.
1282 A positive number means to include that many lines both before and after."
1286 (defalias 'list-matching-lines 'occur)
1288 (defcustom list-matching-lines-face 'match
1289 "Face used by \\[list-matching-lines] to show the text that matches.
1290 If the value is nil, don't highlight the matching portions specially."
1294 (defcustom list-matching-lines-buffer-name-face 'underline
1295 "Face used by \\[list-matching-lines] to show the names of buffers.
1296 If the value is nil, don't highlight the buffer names specially."
1300 (defcustom list-matching-lines-prefix-face 'shadow
1301 "Face used by \\[list-matching-lines] to show the prefix column.
1302 If the face doesn't differ from the default face,
1303 don't highlight the prefix with line numbers specially."
1308 (defcustom occur-excluded-properties
1309 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1310 yank-handler follow-link)
1311 "Text properties to discard when copying lines to the *Occur* buffer.
1312 The value should be a list of text properties to discard or t,
1313 which means to discard all text properties."
1314 :type '(choice (const :tag "All" t) (repeat symbol))
1318 (defun occur-read-primary-args ()
1319 (let* ((perform-collect (consp current-prefix-arg))
1320 (regexp (read-regexp (if perform-collect
1321 "Collect strings matching regexp"
1322 "List lines matching regexp")
1323 'regexp-history-last)))
1326 ;; Perform collect operation
1327 (if (zerop (regexp-opt-depth regexp))
1328 ;; No subexpression so collect the entire match.
1330 ;; Get the regexp for collection pattern.
1331 (let ((default (car occur-collect-regexp-history)))
1333 (format "Regexp to collect (default %s): " default)
1334 default 'occur-collect-regexp-history)))
1335 ;; Otherwise normal occur takes numerical prefix argument.
1336 (when current-prefix-arg
1337 (prefix-numeric-value current-prefix-arg))))))
1339 (defun occur-rename-buffer (&optional unique-p interactive-p)
1340 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1341 Here `original-buffer-name' is the buffer name where Occur was originally run.
1342 When given the prefix argument, or called non-interactively, the renaming
1343 will not clobber the existing buffer(s) of that name, but use
1344 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1345 if you always want a separate *Occur* buffer for each buffer where you
1347 (interactive "P\np")
1348 (with-current-buffer
1349 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1350 (rename-buffer (concat "*Occur: "
1351 (mapconcat #'buffer-name
1352 (car (cddr occur-revert-arguments)) "/")
1354 (or unique-p (not interactive-p)))))
1356 (defun occur (regexp &optional nlines)
1357 "Show all lines in the current buffer containing a match for REGEXP.
1358 If a match spreads across multiple lines, all those lines are shown.
1360 Each line is displayed with NLINES lines before and after, or -NLINES
1361 before if NLINES is negative.
1362 NLINES defaults to `list-matching-lines-default-context-lines'.
1363 Interactively it is the prefix arg.
1365 The lines are shown in a buffer named `*Occur*'.
1366 It serves as a menu to find any of the occurrences in this buffer.
1367 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1369 If REGEXP contains upper case characters (excluding those preceded by `\\')
1370 and `search-upper-case' is non-nil, the matching is case-sensitive.
1372 When NLINES is a string or when the function is called
1373 interactively with prefix argument without a number (`C-u' alone
1374 as prefix) the matching strings are collected into the `*Occur*'
1375 buffer by using NLINES as a replacement regexp. NLINES may
1376 contain \\& and \\N which convention follows `replace-match'.
1377 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1378 \"\\1\" for NLINES collects all the function names in a lisp
1379 program. When there is no parenthesized subexpressions in REGEXP
1380 the entire match is collected. In any case the searched buffer
1382 (interactive (occur-read-primary-args))
1383 (occur-1 regexp nlines (list (current-buffer))))
1385 (defvar ido-ignore-item-temp-list)
1387 (defun multi-occur (bufs regexp &optional nlines)
1388 "Show all lines in buffers BUFS containing a match for REGEXP.
1389 This function acts on multiple buffers; otherwise, it is exactly like
1390 `occur'. When you invoke this command interactively, you must specify
1391 the buffer names that you want, one by one.
1392 See also `multi-occur-in-matching-buffers'."
1395 (let* ((bufs (list (read-buffer "First buffer to search: "
1396 (current-buffer) t)))
1398 (ido-ignore-item-temp-list bufs))
1399 (while (not (string-equal
1400 (setq buf (read-buffer
1401 (if (eq read-buffer-function #'ido-read-buffer)
1402 "Next buffer to search (C-j to end): "
1403 "Next buffer to search (RET to end): ")
1406 (add-to-list 'bufs buf)
1407 (setq ido-ignore-item-temp-list bufs))
1408 (nreverse (mapcar #'get-buffer bufs)))
1409 (occur-read-primary-args)))
1410 (occur-1 regexp nlines bufs))
1412 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1413 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1414 Normally BUFREGEXP matches against each buffer's visited file name,
1415 but if you specify a prefix argument, it matches against the buffer name.
1416 See also `multi-occur'."
1419 (let* ((default (car regexp-history))
1422 (if current-prefix-arg
1423 "List lines in buffers whose names match regexp: "
1424 "List lines in buffers whose filenames match regexp: "))))
1425 (if (equal input "")
1428 (occur-read-primary-args)))
1432 (mapcar (lambda (buf)
1434 (string-match bufregexp
1436 (and (buffer-file-name buf)
1437 (string-match bufregexp
1438 (buffer-file-name buf))))
1442 (defun occur-regexp-descr (regexp)
1443 (format " for %s\"%s\""
1444 (or (get-text-property 0 'isearch-regexp-function-descr regexp)
1446 (if (get-text-property 0 'isearch-string regexp)
1448 (query-replace-descr
1449 (get-text-property 0 'isearch-string regexp))
1451 (query-replace-descr regexp))))
1453 (defun occur-1 (regexp nlines bufs &optional buf-name)
1454 (unless (and regexp (not (equal regexp "")))
1455 (error "Occur doesn't work with the empty regexp"))
1457 (setq buf-name "*Occur*"))
1459 (active-bufs (delq nil (mapcar #'(lambda (buf)
1460 (when (buffer-live-p buf) buf))
1462 ;; Handle the case where one of the buffers we're searching is the
1463 ;; output buffer. Just rename it.
1464 (when (member buf-name (mapcar 'buffer-name active-bufs))
1465 (with-current-buffer (get-buffer buf-name)
1468 ;; Now find or create the output buffer.
1469 ;; If we just renamed that buffer, we will make a new one here.
1470 (setq occur-buf (get-buffer-create buf-name))
1472 (with-current-buffer occur-buf
1473 (if (stringp nlines)
1474 (fundamental-mode) ;; This is for collect operation.
1476 (let ((inhibit-read-only t)
1477 ;; Don't generate undo entries for creation of the initial contents.
1478 (buffer-undo-list t))
1481 (if (stringp nlines)
1482 ;; Treat nlines as a regexp to collect.
1483 (let ((bufs active-bufs)
1486 (with-current-buffer (car bufs)
1488 (goto-char (point-min))
1489 (while (re-search-forward regexp nil t)
1490 ;; Insert the replacement regexp.
1491 (let ((str (match-substitute-replacement nlines)))
1493 (with-current-buffer occur-buf
1495 (setq count (1+ count))
1496 (or (zerop (current-column))
1497 (insert "\n"))))))))
1498 (setq bufs (cdr bufs)))
1500 ;; Perform normal occur.
1502 regexp active-bufs occur-buf
1503 (or nlines list-matching-lines-default-context-lines)
1504 (if (and case-fold-search search-upper-case)
1505 (isearch-no-upper-case-p regexp t)
1507 list-matching-lines-buffer-name-face
1508 (if (face-differs-from-default-p list-matching-lines-prefix-face)
1509 list-matching-lines-prefix-face)
1510 list-matching-lines-face
1511 (not (eq occur-excluded-properties t))))))
1512 (let* ((bufcount (length active-bufs))
1513 (diff (- (length bufs) bufcount)))
1514 (message "Searched %d buffer%s%s; %s match%s%s"
1515 bufcount (if (= bufcount 1) "" "s")
1516 (if (zerop diff) "" (format " (%d killed)" diff))
1517 (if (zerop count) "no" (format "%d" count))
1518 (if (= count 1) "" "es")
1519 ;; Don't display regexp if with remaining text
1520 ;; it is longer than window-width.
1521 (if (> (+ (length (or (get-text-property 0 'isearch-string regexp)
1525 "" (occur-regexp-descr regexp))))
1526 (setq occur-revert-arguments (list regexp nlines bufs))
1528 (kill-buffer occur-buf)
1529 (display-buffer occur-buf)
1530 (setq next-error-last-buffer occur-buf)
1531 (setq buffer-read-only t)
1532 (set-buffer-modified-p nil)
1533 (run-hooks 'occur-hook)))))))
1535 (defun occur-engine (regexp buffers out-buf nlines case-fold
1536 title-face prefix-face match-face keep-props)
1537 (with-current-buffer out-buf
1538 (let ((global-lines 0) ;; total count of matching lines
1539 (global-matches 0) ;; total count of matches
1541 (case-fold-search case-fold))
1542 ;; Map over all the buffers
1543 (dolist (buf buffers)
1544 (when (buffer-live-p buf)
1545 (let ((lines 0) ;; count of matching lines
1546 (matches 0) ;; count of matches
1547 (curr-line 1) ;; line count
1548 (prev-line nil) ;; line number of prev match endpt
1549 (prev-after-lines nil) ;; context lines of prev match
1557 (inhibit-field-text-motion t)
1558 (headerpt (with-current-buffer out-buf (point))))
1559 (with-current-buffer buf
1561 ;; Set CODING only if the current buffer locally
1562 ;; binds buffer-file-coding-system.
1563 (not (local-variable-p 'buffer-file-coding-system))
1564 (setq coding buffer-file-coding-system))
1566 (goto-char (point-min)) ;; begin searching in the buffer
1568 (setq origpt (point))
1569 (when (setq endpt (re-search-forward regexp nil t))
1570 (setq lines (1+ lines)) ;; increment matching lines count
1571 (setq matchbeg (match-beginning 0))
1572 ;; Get beginning of first match line and end of the last.
1574 (goto-char matchbeg)
1575 (setq begpt (line-beginning-position))
1577 (setq endpt (line-end-position)))
1578 ;; Sum line numbers up to the first match line.
1579 (setq curr-line (+ curr-line (count-lines origpt begpt)))
1580 (setq marker (make-marker))
1581 (set-marker marker matchbeg)
1582 (setq curstring (occur-engine-line begpt endpt keep-props))
1583 ;; Highlight the matches
1584 (let ((len (length curstring))
1586 ;; Count empty lines that don't use next loop (Bug#22062).
1588 (setq matches (1+ matches)))
1589 (while (and (< start len)
1590 (string-match regexp curstring start))
1591 (setq matches (1+ matches))
1592 (add-text-properties
1593 (match-beginning 0) (match-end 0)
1594 '(occur-match t) curstring)
1596 ;; Add `match-face' to faces copied from the buffer.
1597 (add-face-text-property
1598 (match-beginning 0) (match-end 0)
1599 match-face nil curstring))
1600 ;; Avoid infloop (Bug#7593).
1601 (let ((end (match-end 0)))
1602 (setq start (if (= start end) (1+ start) end)))))
1603 ;; Generate the string to insert for this match
1604 (let* ((match-prefix
1605 ;; Using 7 digits aligns tabs properly.
1606 (apply #'propertize (format "%7d:" curr-line)
1609 `(font-lock-face ,prefix-face))
1610 `(occur-prefix t mouse-face (highlight)
1611 ;; Allow insertion of text at
1612 ;; the end of the prefix (for
1613 ;; Occur Edit mode).
1614 front-sticky t rear-nonsticky t
1615 occur-target ,marker follow-link t
1616 help-echo "mouse-2: go to this occurrence"))))
1618 ;; We don't put `mouse-face' on the newline,
1619 ;; because that loses. And don't put it
1620 ;; on context lines to reduce flicker.
1621 (propertize curstring 'mouse-face (list 'highlight)
1622 'occur-target marker
1625 "mouse-2: go to this occurrence"))
1629 ;; Add non-numeric prefix to all non-first lines
1630 ;; of multi-line matches.
1631 (replace-regexp-in-string
1634 (propertize "\n :" 'font-lock-face prefix-face)
1637 ;; Add marker at eol, but no mouse props.
1638 (propertize "\n" 'occur-target marker)))
1641 ;; The simple display style
1643 ;; The complex multi-line display style.
1644 (setq ret (occur-context-lines
1645 out-line nlines keep-props begpt endpt
1646 curr-line prev-line prev-after-lines
1648 ;; Set first elem of the returned list to `data',
1649 ;; and the second elem to `prev-after-lines'.
1650 (setq prev-after-lines (nth 1 ret))
1652 ;; Actually insert the match display data
1653 (with-current-buffer out-buf
1658 ;; Sum line numbers between first and last match lines.
1659 (setq curr-line (+ curr-line (count-lines begpt endpt)
1660 ;; Add 1 for empty last match line since
1661 ;; count-lines returns 1 line less.
1662 (if (and (bolp) (eolp)) 1 0)))
1663 ;; On to the next match...
1665 (goto-char (point-max)))
1666 (setq prev-line (1- curr-line)))
1667 ;; Flush remaining context after-lines.
1668 (when prev-after-lines
1669 (with-current-buffer out-buf
1670 (insert (apply #'concat (occur-engine-add-prefix
1671 prev-after-lines prefix-face)))))))
1672 (when (not (zerop lines)) ;; is the count zero?
1673 (setq global-lines (+ global-lines lines)
1674 global-matches (+ global-matches matches))
1675 (with-current-buffer out-buf
1676 (goto-char headerpt)
1680 (format "%d match%s%s%s in buffer: %s\n"
1681 matches (if (= matches 1) "" "es")
1682 ;; Don't display the same number of lines
1683 ;; and matches in case of 1 match per line.
1684 (if (= lines matches)
1685 "" (format " in %d line%s"
1686 lines (if (= lines 1) "" "s")))
1687 ;; Don't display regexp for multi-buffer.
1688 (if (> (length buffers) 1)
1689 "" (occur-regexp-descr regexp))
1693 (add-text-properties beg end `(occur-title ,buf))
1695 (add-face-text-property beg end title-face)))
1696 (goto-char (point-min)))))))
1697 ;; Display total match count and regexp for multi-buffer.
1698 (when (and (not (zerop global-lines)) (> (length buffers) 1))
1699 (goto-char (point-min))
1702 (insert (format "%d match%s%s total%s:\n"
1703 global-matches (if (= global-matches 1) "" "es")
1704 ;; Don't display the same number of lines
1705 ;; and matches in case of 1 match per line.
1706 (if (= global-lines global-matches)
1707 "" (format " in %d line%s"
1708 global-lines (if (= global-lines 1) "" "s")))
1709 (occur-regexp-descr regexp)))
1712 (add-face-text-property beg end title-face)))
1713 (goto-char (point-min)))
1715 ;; CODING is buffer-file-coding-system of the first buffer
1716 ;; that locally binds it. Let's use it also for the output
1718 (set-buffer-file-coding-system coding))
1719 ;; Return the number of matches
1722 (defun occur-engine-line (beg end &optional keep-props)
1723 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1724 (text-property-not-all beg end 'fontified t))
1725 (if (fboundp 'jit-lock-fontify-now)
1726 (jit-lock-fontify-now beg end)))
1727 (if (and keep-props (not (eq occur-excluded-properties t)))
1728 (let ((str (buffer-substring beg end)))
1729 (remove-list-of-text-properties
1730 0 (length str) occur-excluded-properties str)
1732 (buffer-substring-no-properties beg end)))
1734 (defun occur-engine-add-prefix (lines &optional prefix-face)
1737 (concat (if prefix-face
1738 (propertize " :" 'font-lock-face prefix-face)
1743 (defun occur-accumulate-lines (count &optional keep-props pt)
1747 (let ((forwardp (> count 0))
1748 result beg end moved)
1749 (while (not (or (zerop count)
1752 (and (bobp) (not moved)))))
1753 (setq count (+ count (if forwardp -1 1)))
1754 (setq beg (line-beginning-position)
1755 end (line-end-position))
1756 (push (occur-engine-line beg end keep-props) result)
1757 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1758 (nreverse result))))
1760 ;; Generate context display for occur.
1761 ;; OUT-LINE is the line where the match is.
1762 ;; NLINES and KEEP-PROPS are args to occur-engine.
1763 ;; CURR-LINE is line count of the current match,
1764 ;; PREV-LINE is line count of the previous match,
1765 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1766 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1767 ;; then concatenate them all together.
1768 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1769 curr-line prev-line prev-after-lines
1770 &optional prefix-face)
1771 ;; Find after- and before-context lines of the current match.
1773 (nreverse (cdr (occur-accumulate-lines
1774 (- (1+ (abs nlines))) keep-props begpt))))
1776 (cdr (occur-accumulate-lines
1777 (1+ nlines) keep-props endpt)))
1780 ;; Combine after-lines of the previous match
1781 ;; with before-lines of the current match.
1783 (when prev-after-lines
1784 ;; Don't overlap prev after-lines with current before-lines.
1785 (if (>= (+ prev-line (length prev-after-lines))
1786 (- curr-line (length before-lines)))
1787 (setq prev-after-lines
1788 (butlast prev-after-lines
1789 (- (length prev-after-lines)
1790 (- curr-line prev-line (length before-lines) 1))))
1791 ;; Separate non-overlapping context lines with a dashed line.
1792 (setq separator "-------\n")))
1795 ;; Don't overlap current before-lines with previous match line.
1796 (if (<= (- curr-line (length before-lines))
1799 (nthcdr (- (length before-lines)
1800 (- curr-line prev-line 1))
1802 ;; Separate non-overlapping before-context lines.
1803 (unless (> nlines 0)
1804 (setq separator "-------\n"))))
1807 ;; Return a list where the first element is the output line.
1810 (if prev-after-lines
1811 (occur-engine-add-prefix prev-after-lines prefix-face))
1813 (list (if prefix-face
1814 (propertize separator 'font-lock-face prefix-face)
1816 (occur-engine-add-prefix before-lines prefix-face)
1818 ;; And the second element is the list of context after-lines.
1819 (if (> nlines 0) after-lines))))
1822 ;; It would be nice to use \\[...], but there is no reasonable way
1823 ;; to make that display both SPC and Y.
1824 (defconst query-replace-help
1825 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1826 RET or `q' to exit, Period to replace one match and exit,
1827 Comma to replace but not move point immediately,
1828 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1829 C-w to delete match and recursive edit,
1830 C-l to clear the screen, redisplay, and offer same replacement again,
1831 ! to replace all remaining matches in this buffer with no more questions,
1832 ^ to move point back to previous match,
1833 E to edit the replacement string.
1834 In multi-buffer replacements type `Y' to replace all remaining
1835 matches in all remaining buffers with no more questions,
1836 `N' to skip to the next buffer without replacing remaining matches
1837 in the current buffer."
1838 "Help message while in `query-replace'.")
1840 (defvar query-replace-map
1841 (let ((map (make-sparse-keymap)))
1842 (define-key map " " 'act)
1843 (define-key map "\d" 'skip)
1844 (define-key map [delete] 'skip)
1845 (define-key map [backspace] 'skip)
1846 (define-key map "y" 'act)
1847 (define-key map "n" 'skip)
1848 (define-key map "Y" 'act)
1849 (define-key map "N" 'skip)
1850 (define-key map "e" 'edit-replacement)
1851 (define-key map "E" 'edit-replacement)
1852 (define-key map "," 'act-and-show)
1853 (define-key map "q" 'exit)
1854 (define-key map "\r" 'exit)
1855 (define-key map [return] 'exit)
1856 (define-key map "." 'act-and-exit)
1857 (define-key map "\C-r" 'edit)
1858 (define-key map "\C-w" 'delete-and-edit)
1859 (define-key map "\C-l" 'recenter)
1860 (define-key map "!" 'automatic)
1861 (define-key map "^" 'backup)
1862 (define-key map "\C-h" 'help)
1863 (define-key map [f1] 'help)
1864 (define-key map [help] 'help)
1865 (define-key map "?" 'help)
1866 (define-key map "\C-g" 'quit)
1867 (define-key map "\C-]" 'quit)
1868 (define-key map "\C-v" 'scroll-up)
1869 (define-key map "\M-v" 'scroll-down)
1870 (define-key map [next] 'scroll-up)
1871 (define-key map [prior] 'scroll-down)
1872 (define-key map [?\C-\M-v] 'scroll-other-window)
1873 (define-key map [M-next] 'scroll-other-window)
1874 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1875 (define-key map [M-prior] 'scroll-other-window-down)
1876 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1877 ;; should check for ESC specially.
1878 ;; (define-key map "\e" 'exit-prefix)
1879 (define-key map [escape] 'exit-prefix)
1881 "Keymap of responses to questions posed by commands like `query-replace'.
1882 The \"bindings\" in this map are not commands; they are answers.
1883 The valid answers include `act', `skip', `act-and-show',
1884 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1885 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1886 `edit', `edit-replacement', `delete-and-edit', `automatic',
1887 `backup', `quit', and `help'.
1889 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1891 (defvar multi-query-replace-map
1892 (let ((map (make-sparse-keymap)))
1893 (set-keymap-parent map query-replace-map)
1894 (define-key map "Y" 'automatic-all)
1895 (define-key map "N" 'exit-current)
1897 "Keymap that defines additional bindings for multi-buffer replacements.
1898 It extends its parent map `query-replace-map' with new bindings to
1899 operate on a set of buffers/files. The difference with its parent map
1900 is the additional answers `automatic-all' to replace all remaining
1901 matches in all remaining buffers with no more questions, and
1902 `exit-current' to skip remaining matches in the current buffer
1903 and to continue with the next buffer in the sequence.")
1905 (defun replace-match-string-symbols (n)
1906 "Process a list (and any sub-lists), expanding certain symbols.
1908 N (match-string N) (where N is a string of digits)
1909 #N (string-to-number (match-string N))
1911 #& (string-to-number (match-string 0))
1914 Note that these symbols must be preceded by a backslash in order to
1915 type them using Lisp syntax."
1919 (replace-match-string-symbols (car n))) ;Process sub-list
1921 (let ((name (symbol-name (car n))))
1923 ((string-match "^[0-9]+$" name)
1924 (setcar n (list 'match-string (string-to-number name))))
1925 ((string-match "^#[0-9]+$" name)
1926 (setcar n (list 'string-to-number
1928 (string-to-number (substring name 1))))))
1930 (setcar n '(match-string 0)))
1931 ((string= "#&" name)
1932 (setcar n '(string-to-number (match-string 0))))
1934 (setcar n 'replace-count))))))
1937 (defun replace-eval-replacement (expression count)
1938 (let* ((replace-count count)
1944 (error "Error evaluating replacement expression: %S" err)))))
1945 (if (stringp replacement)
1947 (prin1-to-string replacement t))))
1949 (defun replace-quote (replacement)
1950 "Quote a replacement string.
1951 This just doubles all backslashes in REPLACEMENT and
1952 returns the resulting string. If REPLACEMENT is not
1953 a string, it is first passed through `prin1-to-string'
1954 with the `noescape' argument set.
1956 `match-data' is preserved across the call."
1958 (replace-regexp-in-string "\\\\" "\\\\"
1959 (if (stringp replacement)
1961 (prin1-to-string replacement t))
1964 (defun replace-loop-through-replacements (data count)
1965 ;; DATA is a vector containing the following values:
1966 ;; 0 next-rotate-count
1968 ;; 2 next-replacement
1970 (if (= (aref data 0) count)
1972 (aset data 0 (+ count (aref data 1)))
1973 (let ((next (cdr (aref data 2))))
1974 (aset data 2 (if (consp next) next (aref data 3))))))
1975 (car (aref data 2)))
1977 (defun replace-match-data (integers reuse &optional new)
1978 "Like `match-data', but markers in REUSE get invalidated.
1979 If NEW is non-nil, it is set and returned instead of fresh data,
1980 but coerced to the correct value of INTEGERS."
1983 (set-match-data new)
1985 (eq (null integers) (markerp (car reuse)))
1987 (match-data integers reuse t)))
1989 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data
1991 "Make a replacement with `replace-match', editing `\\?'.
1992 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
1993 After possibly editing it (if `\\?' is present), NEWTEXT is also
1994 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
1995 is made (to save time). MATCH-DATA is used for the replacement.
1996 In case editing is done, it is changed to use markers. BACKWARD is
1997 used to reverse the replacement direction.
1999 The return value is non-nil if there has been no `\\?' or NOEDIT was
2000 passed in. If LITERAL is set, no checking is done, anyway."
2001 (unless (or literal noedit)
2003 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
2006 (read-string "Edit replacement string: "
2009 (replace-match "" t t newtext 3)
2010 (1+ (match-beginning 3)))
2013 nil match-data match-data))))
2015 (set-match-data match-data)
2016 (replace-match newtext fixedcase literal)
2017 ;; `replace-match' leaves point at the end of the replacement text,
2018 ;; so move point to the beginning when replacing backward.
2019 (when backward (goto-char (nth 0 match-data)))
2022 (defvar replace-update-post-hook nil
2023 "Function(s) to call after query-replace has found a match in the buffer.")
2025 (defvar replace-search-function nil
2026 "Function to use when searching for strings to replace.
2027 It is used by `query-replace' and `replace-string', and is called
2028 with three arguments, as if it were `search-forward'.")
2030 (defvar replace-re-search-function nil
2031 "Function to use when searching for regexps to replace.
2032 It is used by `query-replace-regexp', `replace-regexp',
2033 `query-replace-regexp-eval', and `map-query-replace-regexp'.
2034 It is called with three arguments, as if it were
2035 `re-search-forward'.")
2037 (defun replace-search (search-string limit regexp-flag delimited-flag
2038 case-fold-search &optional backward)
2039 "Search for the next occurrence of SEARCH-STRING to replace."
2040 ;; Let-bind global isearch-* variables to values used
2041 ;; to search the next replacement. These let-bindings
2042 ;; should be effective both at the time of calling
2043 ;; `isearch-search-fun-default' and also at the
2044 ;; time of funcalling `search-function'.
2045 ;; These isearch-* bindings can't be placed higher
2046 ;; outside of this function because then another I-search
2047 ;; used after `recursive-edit' might override them.
2048 (let* ((isearch-regexp regexp-flag)
2049 (isearch-regexp-function (or delimited-flag
2050 (and replace-character-fold
2052 #'character-fold-to-regexp)))
2053 (isearch-lax-whitespace
2054 replace-lax-whitespace)
2055 (isearch-regexp-lax-whitespace
2056 replace-regexp-lax-whitespace)
2057 (isearch-case-fold-search case-fold-search)
2058 (isearch-adjusted nil)
2059 (isearch-nonincremental t) ; don't use lax word mode
2060 (isearch-forward (not backward))
2063 replace-re-search-function
2064 replace-search-function)
2065 (isearch-search-fun-default))))
2066 (funcall search-function search-string limit t)))
2068 (defvar replace-overlay nil)
2070 (defun replace-highlight (match-beg match-end range-beg range-end
2071 search-string regexp-flag delimited-flag
2072 case-fold-search &optional backward)
2073 (if query-replace-highlight
2075 (move-overlay replace-overlay match-beg match-end (current-buffer))
2076 (setq replace-overlay (make-overlay match-beg match-end))
2077 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2078 (overlay-put replace-overlay 'face 'query-replace)))
2079 (if query-replace-lazy-highlight
2080 (let ((isearch-string search-string)
2081 (isearch-regexp regexp-flag)
2082 (isearch-regexp-function delimited-flag)
2083 (isearch-lax-whitespace
2084 replace-lax-whitespace)
2085 (isearch-regexp-lax-whitespace
2086 replace-regexp-lax-whitespace)
2087 (isearch-case-fold-search case-fold-search)
2088 (isearch-forward (not backward))
2089 (isearch-other-end match-beg)
2090 (isearch-error nil))
2091 (isearch-lazy-highlight-new-loop range-beg range-end))))
2093 (defun replace-dehighlight ()
2094 (when replace-overlay
2095 (delete-overlay replace-overlay))
2096 (when query-replace-lazy-highlight
2097 (lazy-highlight-cleanup lazy-highlight-cleanup)
2098 (setq isearch-lazy-highlight-last-string nil))
2099 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2100 (isearch-clean-overlays))
2102 (defun perform-replace (from-string replacements
2103 query-flag regexp-flag delimited-flag
2104 &optional repeat-count map start end backward region-noncontiguous-p)
2105 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2106 Don't use this in your own program unless you want to query and set the mark
2107 just as `query-replace' does. Instead, write a simple loop like this:
2109 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2110 (replace-match \"foobar\" nil nil))
2112 which will run faster and probably do exactly what you want. Please
2113 see the documentation of `replace-match' to find out how to simulate
2116 This function returns nil if and only if there were no matches to
2117 make, or the user didn't cancel the call.
2119 REPLACEMENTS is either a string, a list of strings, or a cons cell
2120 containing a function and its first argument. The function is
2121 called to generate each replacement like this:
2122 (funcall (car replacements) (cdr replacements) replace-count)
2123 It must return a string."
2124 (or map (setq map query-replace-map))
2125 (and query-flag minibuffer-auto-raise
2126 (raise-frame (window-frame (minibuffer-window))))
2127 (let* ((case-fold-search
2128 (if (and case-fold-search search-upper-case)
2129 (isearch-no-upper-case-p from-string regexp-flag)
2131 (nocasify (not (and case-replace case-fold-search)))
2132 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2133 (search-string from-string)
2134 (real-match-data nil) ; The match data for the current match.
2135 (next-replacement nil)
2136 ;; This is non-nil if we know there is nothing for the user
2137 ;; to edit in the replacement.
2142 (skip-read-only-count 0)
2143 (skip-filtered-count 0)
2144 (skip-invisible-count 0)
2145 (nonempty-match nil)
2147 (recenter-last-op nil) ; Start cycling order with initial position.
2149 ;; If non-nil, it is marker saying where in the buffer to stop.
2151 ;; Use local binding in add-function below.
2152 (isearch-filter-predicate isearch-filter-predicate)
2155 ;; Data for the next match. If a cons, it has the same format as
2156 ;; (match-data); otherwise it is t if a match is possible at point.
2162 (substitute-command-keys
2163 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2164 minibuffer-prompt-properties))))
2166 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
2167 (when region-noncontiguous-p
2169 (mapcar (lambda (position)
2170 (cons (copy-marker (car position))
2171 (copy-marker (cdr position))))
2172 (funcall region-extract-function 'bounds)))
2173 (add-function :after-while isearch-filter-predicate
2178 (>= start (car bounds))
2179 (<= start (cdr bounds))
2180 (>= end (car bounds))
2181 (<= end (cdr bounds))))
2184 ;; If region is active, in Transient Mark mode, operate on region.
2187 (setq limit (copy-marker (min start end)))
2188 (goto-char (max start end))
2191 (setq limit (copy-marker (max start end)))
2192 (goto-char (min start end))
2195 ;; If last typed key in previous call of multi-buffer perform-replace
2196 ;; was `automatic-all', don't ask more questions in next files
2197 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2198 (setq query-flag nil multi-buffer t))
2201 ((stringp replacements)
2202 (setq next-replacement replacements
2204 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2205 (or repeat-count (setq repeat-count 1))
2206 (setq replacements (cons 'replace-loop-through-replacements
2207 (vector repeat-count repeat-count
2208 replacements replacements)))))
2210 (when query-replace-lazy-highlight
2211 (setq isearch-lazy-highlight-last-string nil))
2216 ;; Loop finding occurrences that perhaps should be replaced.
2217 (while (and keep-going
2219 (not (or (bobp) (and limit (<= (point) limit))))
2220 (not (or (eobp) (and limit (>= (point) limit)))))
2221 ;; Use the next match if it is already known;
2222 ;; otherwise, search for a match after moving forward
2223 ;; one char if progress is required.
2224 (setq real-match-data
2225 (cond ((consp match-again)
2226 (goto-char (if backward
2228 (nth 1 match-again)))
2230 t real-match-data match-again))
2231 ;; MATCH-AGAIN non-nil means accept an
2235 (replace-search search-string limit
2236 regexp-flag delimited-flag
2237 case-fold-search backward)
2238 ;; For speed, use only integers and
2239 ;; reuse the list used last time.
2240 (replace-match-data t real-match-data)))
2242 (> (1- (point)) (point-min))
2243 (< (1+ (point)) (point-max)))
2246 (> (1- (point)) limit)
2247 (< (1+ (point)) limit))))
2248 ;; If not accepting adjacent matches,
2249 ;; move one char to the right before
2250 ;; searching again. Undo the motion
2251 ;; if the search fails.
2252 (let ((opoint (point)))
2253 (forward-char (if backward -1 1))
2254 (if (replace-search search-string limit
2255 regexp-flag delimited-flag
2256 case-fold-search backward)
2262 ;; Record whether the match is nonempty, to avoid an infinite loop
2263 ;; repeatedly matching the same empty string.
2264 (setq nonempty-match
2265 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2267 ;; If the match is empty, record that the next one can't be
2270 ;; Otherwise, if matching a regular expression, do the next
2271 ;; match now, since the replacement for this match may
2272 ;; affect whether the next match is adjacent to this one.
2273 ;; If that match is empty, don't use it.
2276 (or (not regexp-flag)
2278 (looking-back search-string nil)
2279 (looking-at search-string))
2280 (let ((match (match-data)))
2281 (and (/= (nth 0 match) (nth 1 match))
2285 ;; Optionally ignore matches that have a read-only property.
2286 ((not (or (not query-replace-skip-read-only)
2287 (not (text-property-not-all
2288 (nth 0 real-match-data) (nth 1 real-match-data)
2290 (setq skip-read-only-count (1+ skip-read-only-count)))
2291 ;; Optionally filter out matches.
2292 ((not (funcall isearch-filter-predicate
2293 (nth 0 real-match-data) (nth 1 real-match-data)))
2294 (setq skip-filtered-count (1+ skip-filtered-count)))
2295 ;; Optionally ignore invisible matches.
2296 ((not (or (eq search-invisible t)
2297 ;; Don't open overlays for automatic replacements.
2298 (and (not query-flag) search-invisible)
2299 ;; Open hidden overlays for interactive replacements.
2300 (not (isearch-range-invisible
2301 (nth 0 real-match-data) (nth 1 real-match-data)))))
2302 (setq skip-invisible-count (1+ skip-invisible-count)))
2304 ;; Calculate the replacement string, if necessary.
2306 (set-match-data real-match-data)
2307 (setq next-replacement
2308 (funcall (car replacements) (cdr replacements)
2310 (if (not query-flag)
2312 (unless (or literal noedit)
2314 (nth 0 real-match-data) (nth 1 real-match-data)
2315 start end search-string
2316 regexp-flag delimited-flag case-fold-search backward))
2318 (replace-match-maybe-edit
2319 next-replacement nocasify literal
2320 noedit real-match-data backward)
2321 replace-count (1+ replace-count)))
2323 (let (done replaced key def)
2324 ;; Loop reading commands until one of them sets done,
2325 ;; which means it has finished handling this
2326 ;; occurrence. Any command that sets `done' should
2327 ;; leave behind proper match data for the stack.
2328 ;; Commands not setting `done' need to adjust
2329 ;; `real-match-data'.
2331 (set-match-data real-match-data)
2332 (run-hooks 'replace-update-post-hook) ; Before `replace-highlight'.
2334 (match-beginning 0) (match-end 0)
2335 start end search-string
2336 regexp-flag delimited-flag case-fold-search backward)
2337 ;; Bind message-log-max so we don't fill up the message log
2338 ;; with a bunch of identical messages.
2339 (let ((message-log-max nil)
2340 (replacement-presentation
2341 (if query-replace-show-replacement
2343 (set-match-data real-match-data)
2344 (match-substitute-replacement next-replacement
2348 (query-replace-descr from-string)
2349 (query-replace-descr replacement-presentation)))
2350 (setq key (read-event))
2351 ;; Necessary in case something happens during read-event
2352 ;; that clobbers the match data.
2353 (set-match-data real-match-data)
2354 (setq key (vector key))
2355 (setq def (lookup-key map key))
2356 ;; Restore the match data while we process the command.
2357 (cond ((eq def 'help)
2358 (with-output-to-temp-buffer "*Help*"
2360 (concat "Query replacing "
2362 (or (and (symbolp delimited-flag)
2363 (get delimited-flag 'isearch-message-prefix))
2365 (if regexp-flag "regexp " "")
2366 (if backward "backward " "")
2367 from-string " with "
2368 next-replacement ".\n\n"
2369 (substitute-command-keys
2370 query-replace-help)))
2371 (with-current-buffer standard-output
2374 (setq keep-going nil)
2376 ((eq def 'exit-current)
2377 (setq multi-buffer t keep-going nil done t))
2380 (let ((elt (pop stack)))
2381 (goto-char (nth 0 elt))
2382 (setq replaced (nth 1 elt)
2387 (message "No previous match")
2388 (ding 'no-terminate)
2393 (replace-match-maybe-edit
2394 next-replacement nocasify literal
2395 noedit real-match-data backward)
2396 replace-count (1+ replace-count)))
2397 (setq done t replaced t))
2398 ((eq def 'act-and-exit)
2401 (replace-match-maybe-edit
2402 next-replacement nocasify literal
2403 noedit real-match-data backward)
2404 replace-count (1+ replace-count)))
2405 (setq keep-going nil)
2406 (setq done t replaced t))
2407 ((eq def 'act-and-show)
2410 (replace-match-maybe-edit
2411 next-replacement nocasify literal
2412 noedit real-match-data backward)
2413 replace-count (1+ replace-count)
2414 real-match-data (replace-match-data
2417 ((or (eq def 'automatic) (eq def 'automatic-all))
2420 (replace-match-maybe-edit
2421 next-replacement nocasify literal
2422 noedit real-match-data backward)
2423 replace-count (1+ replace-count)))
2424 (setq done t query-flag nil replaced t)
2425 (if (eq def 'automatic-all) (setq multi-buffer t)))
2429 ;; `this-command' has the value `query-replace',
2430 ;; so we need to bind it to `recenter-top-bottom'
2431 ;; to allow it to detect a sequence of `C-l'.
2432 (let ((this-command 'recenter-top-bottom)
2433 (last-command 'recenter-top-bottom))
2434 (recenter-top-bottom)))
2436 (let ((opos (point-marker)))
2437 (setq real-match-data (replace-match-data
2440 (goto-char (match-beginning 0))
2442 (save-window-excursion
2445 (set-marker opos nil))
2446 ;; Before we make the replacement,
2447 ;; decide whether the search string
2448 ;; can match again just after this match.
2449 (if (and regexp-flag nonempty-match)
2450 (setq match-again (and (looking-at search-string)
2452 ;; Edit replacement.
2453 ((eq def 'edit-replacement)
2454 (setq real-match-data (replace-match-data
2458 (read-string "Edit replacement string: "
2462 (set-match-data real-match-data)
2464 (replace-match-maybe-edit
2465 next-replacement nocasify literal noedit
2466 real-match-data backward)
2470 ((eq def 'delete-and-edit)
2471 (replace-match "" t t)
2472 (setq real-match-data (replace-match-data
2473 nil real-match-data))
2474 (replace-dehighlight)
2475 (save-excursion (recursive-edit))
2477 ;; Note: we do not need to treat `exit-prefix'
2478 ;; specially here, since we reread
2479 ;; any unrecognized character.
2481 (setq this-command 'mode-exited)
2482 (setq keep-going nil)
2483 (setq unread-command-events
2484 (append (listify-key-sequence key)
2485 unread-command-events))
2487 (when query-replace-lazy-highlight
2488 ;; Force lazy rehighlighting only after replacements.
2489 (if (not (memq def '(skip backup)))
2490 (setq isearch-lazy-highlight-last-string nil)))
2491 (unless (eq def 'recenter)
2492 ;; Reset recenter cycling order to initial position.
2493 (setq recenter-last-op nil)))
2494 ;; Record previous position for ^ when we move on.
2495 ;; Change markers to numbers in the match data
2496 ;; since lots of markers slow down editing.
2497 (push (list (point) replaced
2498 ;;; If the replacement has already happened, all we need is the
2499 ;;; current match start and end. We could get this with a trivial
2501 ;;; (save-excursion (goto-char (match-beginning 0))
2502 ;;; (search-forward (match-string 0))
2504 ;;; if we really wanted to avoid manually constructing match data.
2505 ;;; Adding current-buffer is necessary so that match-data calls can
2506 ;;; return markers which are appropriate for editing.
2515 (replace-dehighlight))
2516 (or unread-command-events
2517 (message "Replaced %d occurrence%s%s"
2519 (if (= replace-count 1) "" "s")
2520 (if (> (+ skip-read-only-count
2522 skip-invisible-count) 0)
2523 (format " (skipped %s)"
2527 (if (> skip-read-only-count 0)
2528 (format "%s read-only"
2529 skip-read-only-count))
2530 (if (> skip-invisible-count 0)
2531 (format "%s invisible"
2532 skip-invisible-count))
2533 (if (> skip-filtered-count 0)
2534 (format "%s filtered out"
2535 skip-filtered-count))))
2538 (or (and keep-going stack) multi-buffer)))
2540 ;;; replace.el ends here