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
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
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.
298 Use \\<minibuffer-local-map>\\[next-history-element] \
299 to pull the last incremental search string to the minibuffer
300 that reads FROM-STRING, or invoke replacements from
301 incremental search with a key sequence like `C-s C-s M-%'
302 to use its current search string as the string to replace.
304 Matching is independent of case if `case-fold-search' is non-nil and
305 FROM-STRING has no uppercase letters. Replacement transfers the case
306 pattern of the old text to the new text, if `case-replace' and
307 `case-fold-search' are non-nil and FROM-STRING has no uppercase
308 letters. (Transferring the case pattern means that if the old text
309 matched is all caps, or capitalized, then its replacement is upcased
312 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
313 ignore hidden matches if `search-invisible' is nil, and ignore more
314 matches using `isearch-filter-predicate'.
316 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
317 to be replaced will match a sequence of whitespace chars defined by the
318 regexp in `search-whitespace-regexp'.
320 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
321 only matches surrounded by word boundaries. A negative prefix arg means
324 Fourth and fifth arg START and END specify the region to operate on.
326 To customize possible responses, change the bindings in `query-replace-map'."
329 (query-replace-read-args
330 (concat "Query replace"
331 (if current-prefix-arg
332 (if (eq current-prefix-arg '-) " backward" " word")
334 (if (use-region-p) " in region" ""))
336 (list (nth 0 common) (nth 1 common) (nth 2 common)
337 ;; These are done separately here
338 ;; so that command-history will record these expressions
339 ;; rather than the values they had this time.
340 (if (use-region-p) (region-beginning))
341 (if (use-region-p) (region-end))
343 (if (use-region-p) (region-noncontiguous-p)))))
344 (perform-replace from-string to-string t nil delimited nil nil start end backward region-noncontiguous-p))
346 (define-key esc-map "%" 'query-replace)
348 (defun query-replace-regexp (regexp to-string &optional delimited start end backward region-noncontiguous-p)
349 "Replace some things after point matching REGEXP with TO-STRING.
350 As each match is found, the user must type a character saying
351 what to do with it. For directions, type \\[help-command] at that time.
353 In Transient Mark mode, if the mark is active, operate on the contents
354 of the region. Otherwise, operate from point to the end of the buffer.
356 Use \\<minibuffer-local-map>\\[next-history-element] \
357 to pull the last incremental search regexp to the minibuffer
358 that reads REGEXP, or invoke replacements from
359 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
360 to use its current search regexp as the regexp to replace.
362 Matching is independent of case if `case-fold-search' is non-nil and
363 REGEXP has no uppercase letters. Replacement transfers the case
364 pattern of the old text to the new text, if `case-replace' and
365 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
366 \(Transferring the case pattern means that if the old text matched is
367 all caps, or capitalized, then its replacement is upcased or
370 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
371 ignore hidden matches if `search-invisible' is nil, and ignore more
372 matches using `isearch-filter-predicate'.
374 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
375 to be replaced will match a sequence of whitespace chars defined by the
376 regexp in `search-whitespace-regexp'.
378 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
379 only matches surrounded by word boundaries. A negative prefix arg means
382 Fourth and fifth arg START and END specify the region to operate on.
384 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
385 and `\\=\\N' (where N is a digit) stands for
386 whatever what matched the Nth `\\(...\\)' in REGEXP.
387 `\\?' lets you edit the replacement text in the minibuffer
388 at the given position for each replacement.
390 In interactive calls, the replacement text can contain `\\,'
391 followed by a Lisp expression. Each
392 replacement evaluates that expression to compute the replacement
393 string. Inside of that expression, `\\&' is a string denoting the
394 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
395 for the whole or a partial match converted to a number with
396 `string-to-number', and `\\#' itself for the number of replacements
397 done so far (starting with zero).
399 If the replacement expression is a symbol, write a space after it
400 to terminate it. One space there, if any, will be discarded.
402 When using those Lisp features interactively in the replacement
403 text, TO-STRING is actually made a list instead of a string.
404 Use \\[repeat-complex-command] after this command for details."
407 (query-replace-read-args
408 (concat "Query replace"
409 (if current-prefix-arg
410 (if (eq current-prefix-arg '-) " backward" " word")
413 (if (use-region-p) " in region" ""))
415 (list (nth 0 common) (nth 1 common) (nth 2 common)
416 ;; These are done separately here
417 ;; so that command-history will record these expressions
418 ;; rather than the values they had this time.
419 (if (use-region-p) (region-beginning))
420 (if (use-region-p) (region-end))
422 (if (use-region-p) (region-noncontiguous-p)))))
423 (perform-replace regexp to-string t t delimited nil nil start end backward region-noncontiguous-p))
425 (define-key esc-map [?\C-%] 'query-replace-regexp)
427 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
428 "Replace some things after point matching REGEXP with the result of TO-EXPR.
430 Interactive use of this function is deprecated in favor of the
431 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
432 using `search-forward-regexp' and `replace-match' is preferred.
434 As each match is found, the user must type a character saying
435 what to do with it. For directions, type \\[help-command] at that time.
437 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
438 reference `replace-count' to get the number of replacements already made.
439 If the result of TO-EXPR is not a string, it is converted to one using
440 `prin1-to-string' with the NOESCAPE argument (which see).
442 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
443 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
444 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
445 Use `\\#&' or `\\#N' if you want a number instead of a string.
446 In interactive use, `\\#' in itself stands for `replace-count'.
448 In Transient Mark mode, if the mark is active, operate on the contents
449 of the region. Otherwise, operate from point to the end of the buffer.
451 Use \\<minibuffer-local-map>\\[next-history-element] \
452 to pull the last incremental search regexp to the minibuffer
455 Preserves case in each replacement if `case-replace' and `case-fold-search'
456 are non-nil and REGEXP has no uppercase letters.
458 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
459 ignore hidden matches if `search-invisible' is nil, and ignore more
460 matches using `isearch-filter-predicate'.
462 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
463 to be replaced will match a sequence of whitespace chars defined by the
464 regexp in `search-whitespace-regexp'.
466 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
467 only matches that are surrounded by word boundaries.
468 Fourth and fifth arg START and END specify the region to operate on."
469 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
470 for interactive calls, and `search-forward-regexp'/`replace-match'
471 for Lisp calls." "22.1"))
474 (barf-if-buffer-read-only)
476 ;; Let-bind the history var to disable the "foo -> bar"
477 ;; default. Maybe we shouldn't disable this default, but
478 ;; for now I'll leave it off. --Stef
479 (let ((query-replace-defaults nil))
480 (query-replace-read-from "Query replace regexp" t)))
481 (to (list (read-from-minibuffer
482 (format "Query replace regexp %s with eval: "
483 (query-replace-descr from))
484 nil nil t query-replace-to-history-variable from t))))
485 ;; We make TO a list because replace-match-string-symbols requires one,
486 ;; and the user might enter a single token.
487 (replace-match-string-symbols to)
488 (list from (car to) current-prefix-arg
489 (if (use-region-p) (region-beginning))
490 (if (use-region-p) (region-end))))))
491 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
492 t 'literal delimited nil nil start end))
494 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
495 "Replace some matches for REGEXP with various strings, in rotation.
496 The second argument TO-STRINGS contains the replacement strings, separated
497 by spaces. This command works like `query-replace-regexp' except that
498 each successive replacement uses the next successive replacement string,
499 wrapping around from the last such string to the first.
501 In Transient Mark mode, if the mark is active, operate on the contents
502 of the region. Otherwise, operate from point to the end of the buffer.
504 Non-interactively, TO-STRINGS may be a list of replacement strings.
506 Interactively, reads the regexp using `read-regexp'.
507 Use \\<minibuffer-local-map>\\[next-history-element] \
508 to pull the last incremental search regexp to the minibuffer
511 A prefix argument N says to use each replacement string N times
512 before rotating to the next.
513 Fourth and fifth arg START and END specify the region to operate on."
515 (let* ((from (read-regexp "Map query replace (regexp): " nil
516 query-replace-from-history-variable))
517 (to (read-from-minibuffer
518 (format "Query replace %s with (space-separated strings): "
519 (query-replace-descr from))
521 query-replace-to-history-variable from t)))
523 (and current-prefix-arg
524 (prefix-numeric-value current-prefix-arg))
525 (if (use-region-p) (region-beginning))
526 (if (use-region-p) (region-end)))))
528 (if (listp to-strings)
529 (setq replacements to-strings)
530 (while (/= (length to-strings) 0)
531 (if (string-match " " to-strings)
534 (list (substring to-strings 0
535 (string-match " " to-strings))))
536 to-strings (substring to-strings
537 (1+ (string-match " " to-strings))))
538 (setq replacements (append replacements (list to-strings))
540 (perform-replace regexp replacements t t nil n nil start end)))
542 (defun replace-string (from-string to-string &optional delimited start end backward)
543 "Replace occurrences of FROM-STRING with TO-STRING.
544 Preserve case in each match if `case-replace' and `case-fold-search'
545 are non-nil and FROM-STRING has no uppercase letters.
546 \(Preserving case means that if the string matched is all caps, or capitalized,
547 then its replacement is upcased or capitalized.)
549 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
550 ignore hidden matches if `search-invisible' is nil, and ignore more
551 matches using `isearch-filter-predicate'.
553 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
554 to be replaced will match a sequence of whitespace chars defined by the
555 regexp in `search-whitespace-regexp'.
557 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
558 only matches surrounded by word boundaries. A negative prefix arg means
561 Operates on the region between START and END (if both are nil, from point
562 to the end of the buffer). Interactively, if Transient Mark mode is
563 enabled and the mark is active, operates on the contents of the region;
564 otherwise from point to the end of the buffer.
566 Use \\<minibuffer-local-map>\\[next-history-element] \
567 to pull the last incremental search string to the minibuffer
568 that reads FROM-STRING.
570 This function is usually the wrong thing to use in a Lisp program.
571 What you probably want is a loop like this:
572 (while (search-forward FROM-STRING nil t)
573 (replace-match TO-STRING nil t))
574 which will run faster and will not set the mark or print anything.
575 \(You may need a more complex loop if FROM-STRING can match the null string
576 and TO-STRING is also null.)"
577 (declare (interactive-only
578 "use `search-forward' and `replace-match' instead."))
581 (query-replace-read-args
583 (if current-prefix-arg
584 (if (eq current-prefix-arg '-) " backward" " word")
587 (if (use-region-p) " in region" ""))
589 (list (nth 0 common) (nth 1 common) (nth 2 common)
590 (if (use-region-p) (region-beginning))
591 (if (use-region-p) (region-end))
593 (perform-replace from-string to-string nil nil delimited nil nil start end backward))
595 (defun replace-regexp (regexp to-string &optional delimited start end backward)
596 "Replace things after point matching REGEXP with TO-STRING.
597 Preserve case in each match if `case-replace' and `case-fold-search'
598 are non-nil and REGEXP has no uppercase letters.
600 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
601 ignore hidden matches if `search-invisible' is nil, and ignore more
602 matches using `isearch-filter-predicate'.
604 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
605 to be replaced will match a sequence of whitespace chars defined by the
606 regexp in `search-whitespace-regexp'.
608 In Transient Mark mode, if the mark is active, operate on the contents
609 of the region. Otherwise, operate from point to the end of the buffer.
611 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
612 only matches surrounded by word boundaries. A negative prefix arg means
615 Fourth and fifth arg START and END specify the region to operate on.
617 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
618 and `\\=\\N' (where N is a digit) stands for
619 whatever what matched the Nth `\\(...\\)' in REGEXP.
620 `\\?' lets you edit the replacement text in the minibuffer
621 at the given position for each replacement.
623 In interactive calls, the replacement text may contain `\\,'
624 followed by a Lisp expression used as part of the replacement
625 text. Inside of that expression, `\\&' is a string denoting the
626 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
627 numeric values from `string-to-number', and `\\#' itself for
628 `replace-count', the number of replacements occurred so far.
630 If your Lisp expression is an identifier and the next letter in
631 the replacement string would be interpreted as part of it, you
632 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
633 for this particular case you may also enter `\\#' in the
634 replacement text directly.
636 When using those Lisp features interactively in the replacement
637 text, TO-STRING is actually made a list instead of a string.
638 Use \\[repeat-complex-command] after this command for details.
640 Use \\<minibuffer-local-map>\\[next-history-element] \
641 to pull the last incremental search regexp to the minibuffer
644 This function is usually the wrong thing to use in a Lisp program.
645 What you probably want is a loop like this:
646 (while (re-search-forward REGEXP nil t)
647 (replace-match TO-STRING nil nil))
648 which will run faster and will not set the mark or print anything."
649 (declare (interactive-only
650 "use `re-search-forward' and `replace-match' instead."))
653 (query-replace-read-args
655 (if current-prefix-arg
656 (if (eq current-prefix-arg '-) " backward" " word")
659 (if (use-region-p) " in region" ""))
661 (list (nth 0 common) (nth 1 common) (nth 2 common)
662 (if (use-region-p) (region-beginning))
663 (if (use-region-p) (region-end))
665 (perform-replace regexp to-string nil t delimited nil nil start end backward))
668 (defvar regexp-history nil
669 "History list for some commands that read regular expressions.
671 Maximum length of the history list is determined by the value
672 of `history-length', which see.")
674 (defvar occur-collect-regexp-history '("\\1")
675 "History of regexp for occur's collect operation")
677 (defcustom read-regexp-defaults-function nil
678 "Function that provides default regexp(s) for `read-regexp'.
679 This function should take no arguments and return one of: nil, a
680 regexp, or a list of regexps. Interactively, `read-regexp' uses
681 the return value of this function for its DEFAULT argument.
683 As an example, set this variable to `find-tag-default-as-regexp'
684 to default to the symbol at point.
686 To provide different default regexps for different commands,
687 the function that you set this to can check `this-command'."
689 (const :tag "No default regexp reading function" nil)
690 (const :tag "Latest regexp history" regexp-history-last)
691 (function-item :tag "Tag at point"
693 (function-item :tag "Tag at point as regexp"
694 find-tag-default-as-regexp)
695 (function-item :tag "Tag at point as symbol regexp"
696 find-tag-default-as-symbol-regexp)
697 (function :tag "Your choice of function"))
701 (defun read-regexp-suggestions ()
702 "Return a list of standard suggestions for `read-regexp'.
703 By default, the list includes the tag at point, the last isearch regexp,
704 the last isearch string, and the last replacement regexp. `read-regexp'
705 appends the list returned by this function to the end of values available
706 via \\<minibuffer-local-map>\\[next-history-element]."
708 (find-tag-default-as-regexp)
709 (find-tag-default-as-symbol-regexp)
710 (car regexp-search-ring)
711 (regexp-quote (or (car search-ring) ""))
712 (car (symbol-value query-replace-from-history-variable))))
714 (defun read-regexp (prompt &optional defaults history)
715 "Read and return a regular expression as a string.
716 Prompt with the string PROMPT. If PROMPT ends in \":\" (followed by
717 optional whitespace), use it as-is. Otherwise, add \": \" to the end,
718 possibly preceded by the default result (see below).
720 The optional argument DEFAULTS can be either: nil, a string, a list
721 of strings, or a symbol. We use DEFAULTS to construct the default
722 return value in case of empty input.
724 If DEFAULTS is a string, we use it as-is.
726 If DEFAULTS is a list of strings, the first element is the
727 default return value, but all the elements are accessible
728 using the history command \\<minibuffer-local-map>\\[next-history-element].
730 If DEFAULTS is a non-nil symbol, then if `read-regexp-defaults-function'
731 is non-nil, we use that in place of DEFAULTS in the following:
732 If DEFAULTS is the symbol `regexp-history-last', we use the first
733 element of HISTORY (if specified) or `regexp-history'.
734 If DEFAULTS is a function, we call it with no arguments and use
735 what it returns, which should be either nil, a string, or a list of strings.
737 We append the standard values from `read-regexp-suggestions' to DEFAULTS
740 If the first element of DEFAULTS is non-nil (and if PROMPT does not end
741 in \":\", followed by optional whitespace), we add it to the prompt.
743 The optional argument HISTORY is a symbol to use for the history list.
744 If nil, uses `regexp-history'."
746 (if (and defaults (symbolp defaults))
748 ((eq (or read-regexp-defaults-function defaults)
749 'regexp-history-last)
750 (car (symbol-value (or history 'regexp-history))))
751 ((functionp (or read-regexp-defaults-function defaults))
752 (funcall (or read-regexp-defaults-function defaults))))
754 (default (if (consp defaults) (car defaults) defaults))
755 (suggestions (if (listp defaults) defaults (list defaults)))
756 (suggestions (append suggestions (read-regexp-suggestions)))
757 (suggestions (delete-dups (delq nil (delete "" suggestions))))
758 ;; Do not automatically add default to the history for empty input.
759 (history-add-new-input nil)
760 (input (read-from-minibuffer
761 (cond ((string-match-p ":[ \t]*\\'" prompt)
763 ((and default (> (length default) 0))
764 (format "%s (default %s): " prompt
765 (query-replace-descr default)))
767 (format "%s: " prompt)))
768 nil nil nil (or history 'regexp-history) suggestions t)))
770 ;; Return the default value when the user enters empty input.
771 (prog1 (or default input)
773 (add-to-history (or history 'regexp-history) default)))
774 ;; Otherwise, add non-empty input to the history and return input.
776 (add-to-history (or history 'regexp-history) input)))))
779 (defalias 'delete-non-matching-lines 'keep-lines)
780 (defalias 'delete-matching-lines 'flush-lines)
781 (defalias 'count-matches 'how-many)
784 (defun keep-lines-read-args (prompt)
785 "Read arguments for `keep-lines' and friends.
786 Prompt for a regexp with PROMPT.
787 Value is a list, (REGEXP)."
788 (list (read-regexp prompt) nil nil t))
790 (defun keep-lines (regexp &optional rstart rend interactive)
791 "Delete all lines except those containing matches for REGEXP.
792 A match split across lines preserves all the lines it lies in.
793 When called from Lisp (and usually interactively as well, see below)
794 applies to all lines starting after point.
796 If REGEXP contains upper case characters (excluding those preceded by `\\')
797 and `search-upper-case' is non-nil, the matching is case-sensitive.
799 Second and third arg RSTART and REND specify the region to operate on.
800 This command operates on (the accessible part of) all lines whose
801 accessible part is entirely contained in the region determined by RSTART
802 and REND. (A newline ending a line counts as part of that line.)
804 Interactively, in Transient Mark mode when the mark is active, operate
805 on all lines whose accessible part is entirely contained in the region.
806 Otherwise, the command applies to all lines starting after point.
807 When calling this function from Lisp, you can pretend that it was
808 called interactively by passing a non-nil INTERACTIVE argument.
810 This function starts looking for the next match from the end of
811 the previous match. Hence, it ignores matches that overlap
812 a previously found match."
816 (barf-if-buffer-read-only)
817 (keep-lines-read-args "Keep lines containing match for regexp")))
820 (goto-char (min rstart rend))
824 (goto-char (max rstart rend))
825 (unless (or (bolp) (eobp))
828 (if (and interactive (use-region-p))
829 (setq rstart (region-beginning)
831 (goto-char (region-end))
832 (unless (or (bolp) (eobp))
836 rend (point-max-marker)))
839 (or (bolp) (forward-line 1))
840 (let ((start (point))
842 (if (and case-fold-search search-upper-case)
843 (isearch-no-upper-case-p regexp t)
845 (while (< (point) rend)
846 ;; Start is first char not preserved by previous match.
847 (if (not (re-search-forward regexp rend 'move))
848 (delete-region start rend)
849 (let ((end (save-excursion (goto-char (match-beginning 0))
852 ;; Now end is first char preserved by the new match.
854 (delete-region start end))))
856 (setq start (save-excursion (forward-line 1) (point)))
857 ;; If the match was empty, avoid matching again at same place.
858 (and (< (point) rend)
859 (= (match-beginning 0) (match-end 0))
861 (set-marker rend nil)
865 (defun flush-lines (regexp &optional rstart rend interactive)
866 "Delete lines containing matches for REGEXP.
867 When called from Lisp (and usually when called interactively as
868 well, see below), applies to the part of the buffer after point.
869 The line point is in is deleted if and only if it contains a
870 match for regexp starting after point.
872 If REGEXP contains upper case characters (excluding those preceded by `\\')
873 and `search-upper-case' is non-nil, the matching is case-sensitive.
875 Second and third arg RSTART and REND specify the region to operate on.
876 Lines partially contained in this region are deleted if and only if
877 they contain a match entirely contained in it.
879 Interactively, in Transient Mark mode when the mark is active, operate
880 on the contents of the region. Otherwise, operate from point to the
881 end of (the accessible portion of) the buffer. When calling this function
882 from Lisp, you can pretend that it was called interactively by passing
883 a non-nil INTERACTIVE argument.
885 If a match is split across lines, all the lines it lies in are deleted.
886 They are deleted _before_ looking for the next match. Hence, a match
887 starting on the same line at which another match ended is ignored."
891 (barf-if-buffer-read-only)
892 (keep-lines-read-args "Flush lines containing match for regexp")))
895 (goto-char (min rstart rend))
896 (setq rend (copy-marker (max rstart rend))))
897 (if (and interactive (use-region-p))
898 (setq rstart (region-beginning)
899 rend (copy-marker (region-end)))
901 rend (point-max-marker)))
903 (let ((case-fold-search
904 (if (and case-fold-search search-upper-case)
905 (isearch-no-upper-case-p regexp t)
908 (while (and (< (point) rend)
909 (re-search-forward regexp rend t))
910 (delete-region (save-excursion (goto-char (match-beginning 0))
913 (progn (forward-line 1) (point))))))
914 (set-marker rend nil)
918 (defun how-many (regexp &optional rstart rend interactive)
919 "Print and return number of matches for REGEXP following point.
920 When called from Lisp and INTERACTIVE is omitted or nil, just return
921 the number, do not print it; if INTERACTIVE is t, the function behaves
922 in all respects as if it had been called interactively.
924 If REGEXP contains upper case characters (excluding those preceded by `\\')
925 and `search-upper-case' is non-nil, the matching is case-sensitive.
927 Second and third arg RSTART and REND specify the region to operate on.
929 Interactively, in Transient Mark mode when the mark is active, operate
930 on the contents of the region. Otherwise, operate from point to the
931 end of (the accessible portion of) the buffer.
933 This function starts looking for the next match from the end of
934 the previous match. Hence, it ignores matches that overlap
935 a previously found match."
938 (keep-lines-read-args "How many matches for regexp"))
943 (goto-char (min rstart rend))
944 (setq rend (max rstart rend)))
946 (setq rend (point-max)))
947 (if (and interactive (use-region-p))
948 (setq rstart (region-beginning)
956 (if (and case-fold-search search-upper-case)
957 (isearch-no-upper-case-p regexp t)
959 (while (and (< (point) rend)
960 (progn (setq opoint (point))
961 (re-search-forward regexp rend t)))
962 (if (= opoint (point))
964 (setq count (1+ count))))
965 (when interactive (message "%d occurrence%s"
967 (if (= count 1) "" "s")))
971 (defvar occur-menu-map
972 (let ((map (make-sparse-keymap)))
973 (bindings--define-key map [next-error-follow-minor-mode]
974 '(menu-item "Auto Occurrence Display"
975 next-error-follow-minor-mode
976 :help "Display another occurrence when moving the cursor"
977 :button (:toggle . (and (boundp 'next-error-follow-minor-mode)
978 next-error-follow-minor-mode))))
979 (bindings--define-key map [separator-1] menu-bar-separator)
980 (bindings--define-key map [kill-this-buffer]
981 '(menu-item "Kill Occur Buffer" kill-this-buffer
982 :help "Kill the current *Occur* buffer"))
983 (bindings--define-key map [quit-window]
984 '(menu-item "Quit Occur Window" quit-window
985 :help "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
986 (bindings--define-key map [revert-buffer]
987 '(menu-item "Revert Occur Buffer" revert-buffer
988 :help "Replace the text in the *Occur* buffer with the results of rerunning occur"))
989 (bindings--define-key map [clone-buffer]
990 '(menu-item "Clone Occur Buffer" clone-buffer
991 :help "Create and return a twin copy of the current *Occur* buffer"))
992 (bindings--define-key map [occur-rename-buffer]
993 '(menu-item "Rename Occur Buffer" occur-rename-buffer
994 :help "Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
995 (bindings--define-key map [occur-edit-buffer]
996 '(menu-item "Edit Occur Buffer" occur-edit-mode
997 :help "Edit the *Occur* buffer and apply changes to the original buffers."))
998 (bindings--define-key map [separator-2] menu-bar-separator)
999 (bindings--define-key map [occur-mode-goto-occurrence-other-window]
1000 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
1001 :help "Go to the occurrence the current line describes, in another window"))
1002 (bindings--define-key map [occur-mode-goto-occurrence]
1003 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
1004 :help "Go to the occurrence the current line describes"))
1005 (bindings--define-key map [occur-mode-display-occurrence]
1006 '(menu-item "Display Occurrence" occur-mode-display-occurrence
1007 :help "Display in another window the occurrence the current line describes"))
1008 (bindings--define-key map [occur-next]
1009 '(menu-item "Move to Next Match" occur-next
1010 :help "Move to the Nth (default 1) next match in an Occur mode buffer"))
1011 (bindings--define-key map [occur-prev]
1012 '(menu-item "Move to Previous Match" occur-prev
1013 :help "Move to the Nth (default 1) previous match in an Occur mode buffer"))
1015 "Menu keymap for `occur-mode'.")
1017 (defvar occur-mode-map
1018 (let ((map (make-sparse-keymap)))
1019 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
1020 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1021 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
1022 (define-key map "e" 'occur-edit-mode)
1023 (define-key map "\C-m" 'occur-mode-goto-occurrence)
1024 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
1025 (define-key map "\C-o" 'occur-mode-display-occurrence)
1026 (define-key map "\M-n" 'occur-next)
1027 (define-key map "\M-p" 'occur-prev)
1028 (define-key map "r" 'occur-rename-buffer)
1029 (define-key map "c" 'clone-buffer)
1030 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1031 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1033 "Keymap for `occur-mode'.")
1035 (defvar occur-revert-arguments nil
1036 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
1037 See `occur-revert-function'.")
1038 (make-variable-buffer-local 'occur-revert-arguments)
1039 (put 'occur-revert-arguments 'permanent-local t)
1041 (defcustom occur-mode-hook '(turn-on-font-lock)
1042 "Hook run when entering Occur mode."
1046 (defcustom occur-hook nil
1047 "Hook run by Occur when there are any matches."
1051 (defcustom occur-mode-find-occurrence-hook nil
1052 "Hook run by Occur after locating an occurrence.
1053 This will be called with the cursor position at the occurrence. An application
1054 for this is to reveal context in an outline-mode when the occurrence is hidden."
1058 (put 'occur-mode 'mode-class 'special)
1059 (define-derived-mode occur-mode special-mode "Occur"
1060 "Major mode for output from \\[occur].
1061 \\<occur-mode-map>Move point to one of the items in this buffer, then use
1062 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
1063 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
1066 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
1067 (setq next-error-function 'occur-next-error))
1072 (defvar occur-edit-mode-map
1073 (let ((map (make-sparse-keymap)))
1074 (set-keymap-parent map text-mode-map)
1075 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1076 (define-key map "\C-c\C-c" 'occur-cease-edit)
1077 (define-key map "\C-o" 'occur-mode-display-occurrence)
1078 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1079 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1081 "Keymap for `occur-edit-mode'.")
1083 (define-derived-mode occur-edit-mode occur-mode "Occur-Edit"
1084 "Major mode for editing *Occur* buffers.
1085 In this mode, changes to the *Occur* buffer are also applied to
1086 the originating buffer.
1088 To return to ordinary Occur mode, use \\[occur-cease-edit]."
1089 (setq buffer-read-only nil)
1090 (add-hook 'after-change-functions 'occur-after-change-function nil t)
1091 (message (substitute-command-keys
1092 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
1094 (defun occur-cease-edit ()
1095 "Switch from Occur Edit mode to Occur mode."
1097 (when (derived-mode-p 'occur-edit-mode)
1099 (message "Switching to Occur mode.")))
1101 (defun occur-after-change-function (beg end length)
1104 (let* ((line-beg (line-beginning-position))
1105 (m (get-text-property line-beg 'occur-target))
1106 (buf (marker-buffer m))
1108 (when (and (get-text-property line-beg 'occur-prefix)
1109 (not (get-text-property end 'occur-prefix)))
1111 ;; Apply occur-target property to inserted (e.g. yanked) text.
1112 (put-text-property beg end 'occur-target m)
1113 ;; Did we insert a newline? Occur Edit mode can't create new
1114 ;; Occur entries; just discard everything after the newline.
1116 (and (search-forward "\n" end t)
1117 (delete-region (1- (point)) end))))
1118 (let* ((line (- (line-number-at-pos)
1119 (line-number-at-pos (window-start))))
1120 (readonly (with-current-buffer buf buffer-read-only))
1121 (win (or (get-buffer-window buf)
1123 '(nil (inhibit-same-window . t)
1124 (inhibit-switch-frame . t)))))
1125 (line-end (line-end-position))
1126 (text (save-excursion
1127 (goto-char (next-single-property-change
1128 line-beg 'occur-prefix nil
1130 (setq col (- (point) line-beg))
1131 (buffer-substring-no-properties (point) line-end))))
1132 (with-selected-window win
1136 (message "Buffer `%s' is read only." buf)
1137 (delete-region (line-beginning-position) (line-end-position))
1139 (move-to-column col)))))))
1142 (defun occur-revert-function (_ignore1 _ignore2)
1143 "Handle `revert-buffer' for Occur mode buffers."
1144 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
1146 (defun occur-mode-find-occurrence ()
1147 (let ((pos (get-text-property (point) 'occur-target)))
1149 (error "No occurrence on this line"))
1150 (unless (buffer-live-p (marker-buffer pos))
1151 (error "Buffer for this occurrence was killed"))
1154 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
1155 (defun occur-mode-goto-occurrence (&optional event)
1156 "Go to the occurrence on the current line."
1157 (interactive (list last-nonmenu-event))
1160 ;; Actually `event-end' works correctly with a nil argument as
1161 ;; well, so we could dispense with this test, but let's not
1162 ;; rely on this undocumented behavior.
1163 (occur-mode-find-occurrence)
1164 (with-current-buffer (window-buffer (posn-window (event-end event)))
1166 (goto-char (posn-point (event-end event)))
1167 (occur-mode-find-occurrence))))))
1168 (pop-to-buffer (marker-buffer pos))
1170 (run-hooks 'occur-mode-find-occurrence-hook)))
1172 (defun occur-mode-goto-occurrence-other-window ()
1173 "Go to the occurrence the current line describes, in another window."
1175 (let ((pos (occur-mode-find-occurrence)))
1176 (switch-to-buffer-other-window (marker-buffer pos))
1178 (run-hooks 'occur-mode-find-occurrence-hook)))
1180 (defun occur-mode-display-occurrence ()
1181 "Display in another window the occurrence the current line describes."
1183 (let ((pos (occur-mode-find-occurrence))
1185 (setq window (display-buffer (marker-buffer pos) t))
1186 ;; This is the way to set point in the proper window.
1187 (save-selected-window
1188 (select-window window)
1190 (run-hooks 'occur-mode-find-occurrence-hook))))
1192 (defun occur-find-match (n search message)
1193 (if (not n) (setq n 1))
1196 (setq r (funcall search (point) 'occur-match))
1198 (get-text-property r 'occur-match)
1199 (setq r (funcall search r 'occur-match)))
1205 (defun occur-next (&optional n)
1206 "Move to the Nth (default 1) next match in an Occur mode buffer."
1208 (occur-find-match n #'next-single-property-change "No more matches"))
1210 (defun occur-prev (&optional n)
1211 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1213 (occur-find-match n #'previous-single-property-change "No earlier matches"))
1215 (defun occur-next-error (&optional argp reset)
1216 "Move to the Nth (default 1) next match in an Occur mode buffer.
1217 Compatibility function for \\[next-error] invocations."
1219 ;; we need to run occur-find-match from within the Occur buffer
1220 (with-current-buffer
1221 ;; Choose the buffer and make it current.
1222 (if (next-error-buffer-p (current-buffer))
1224 (next-error-find-buffer nil nil
1226 (eq major-mode 'occur-mode))))
1228 (goto-char (cond (reset (point-min))
1229 ((< argp 0) (line-beginning-position))
1230 ((> argp 0) (line-end-position))
1235 #'previous-single-property-change
1236 #'next-single-property-change)
1238 ;; In case the *Occur* buffer is visible in a nonselected window.
1239 (let ((win (get-buffer-window (current-buffer) t)))
1240 (if win (set-window-point win (point))))
1241 (occur-mode-goto-occurrence)))
1244 '((((class color) (min-colors 88) (background light))
1245 :background "yellow1")
1246 (((class color) (min-colors 88) (background dark))
1247 :background "RoyalBlue3")
1248 (((class color) (min-colors 8) (background light))
1249 :background "yellow" :foreground "black")
1250 (((class color) (min-colors 8) (background dark))
1251 :background "blue" :foreground "white")
1252 (((type tty) (class mono))
1254 (t :background "gray"))
1255 "Face used to highlight matches permanently."
1259 (defcustom list-matching-lines-default-context-lines 0
1260 "Default number of context lines included around `list-matching-lines' matches.
1261 A negative number means to include that many lines before the match.
1262 A positive number means to include that many lines both before and after."
1266 (defalias 'list-matching-lines 'occur)
1268 (defcustom list-matching-lines-face 'match
1269 "Face used by \\[list-matching-lines] to show the text that matches.
1270 If the value is nil, don't highlight the matching portions specially."
1274 (defcustom list-matching-lines-buffer-name-face 'underline
1275 "Face used by \\[list-matching-lines] to show the names of buffers.
1276 If the value is nil, don't highlight the buffer names specially."
1280 (defcustom list-matching-lines-prefix-face 'shadow
1281 "Face used by \\[list-matching-lines] to show the prefix column.
1282 If the face doesn't differ from the default face,
1283 don't highlight the prefix with line numbers specially."
1288 (defcustom occur-excluded-properties
1289 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1290 yank-handler follow-link)
1291 "Text properties to discard when copying lines to the *Occur* buffer.
1292 The value should be a list of text properties to discard or t,
1293 which means to discard all text properties."
1294 :type '(choice (const :tag "All" t) (repeat symbol))
1298 (defun occur-read-primary-args ()
1299 (let* ((perform-collect (consp current-prefix-arg))
1300 (regexp (read-regexp (if perform-collect
1301 "Collect strings matching regexp"
1302 "List lines matching regexp")
1303 'regexp-history-last)))
1306 ;; Perform collect operation
1307 (if (zerop (regexp-opt-depth regexp))
1308 ;; No subexpression so collect the entire match.
1310 ;; Get the regexp for collection pattern.
1311 (let ((default (car occur-collect-regexp-history)))
1313 (format "Regexp to collect (default %s): " default)
1314 default 'occur-collect-regexp-history)))
1315 ;; Otherwise normal occur takes numerical prefix argument.
1316 (when current-prefix-arg
1317 (prefix-numeric-value current-prefix-arg))))))
1319 (defun occur-rename-buffer (&optional unique-p interactive-p)
1320 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1321 Here `original-buffer-name' is the buffer name where Occur was originally run.
1322 When given the prefix argument, or called non-interactively, the renaming
1323 will not clobber the existing buffer(s) of that name, but use
1324 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1325 if you always want a separate *Occur* buffer for each buffer where you
1327 (interactive "P\np")
1328 (with-current-buffer
1329 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1330 (rename-buffer (concat "*Occur: "
1331 (mapconcat #'buffer-name
1332 (car (cddr occur-revert-arguments)) "/")
1334 (or unique-p (not interactive-p)))))
1336 (defun occur (regexp &optional nlines)
1337 "Show all lines in the current buffer containing a match for REGEXP.
1338 If a match spreads across multiple lines, all those lines are shown.
1340 Each line is displayed with NLINES lines before and after, or -NLINES
1341 before if NLINES is negative.
1342 NLINES defaults to `list-matching-lines-default-context-lines'.
1343 Interactively it is the prefix arg.
1345 The lines are shown in a buffer named `*Occur*'.
1346 It serves as a menu to find any of the occurrences in this buffer.
1347 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1349 If REGEXP contains upper case characters (excluding those preceded by `\\')
1350 and `search-upper-case' is non-nil, the matching is case-sensitive.
1352 When NLINES is a string or when the function is called
1353 interactively with prefix argument without a number (`C-u' alone
1354 as prefix) the matching strings are collected into the `*Occur*'
1355 buffer by using NLINES as a replacement regexp. NLINES may
1356 contain \\& and \\N which convention follows `replace-match'.
1357 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1358 \"\\1\" for NLINES collects all the function names in a lisp
1359 program. When there is no parenthesized subexpressions in REGEXP
1360 the entire match is collected. In any case the searched buffer
1362 (interactive (occur-read-primary-args))
1363 (occur-1 regexp nlines (list (current-buffer))))
1365 (defvar ido-ignore-item-temp-list)
1367 (defun multi-occur (bufs regexp &optional nlines)
1368 "Show all lines in buffers BUFS containing a match for REGEXP.
1369 This function acts on multiple buffers; otherwise, it is exactly like
1370 `occur'. When you invoke this command interactively, you must specify
1371 the buffer names that you want, one by one.
1372 See also `multi-occur-in-matching-buffers'."
1375 (let* ((bufs (list (read-buffer "First buffer to search: "
1376 (current-buffer) t)))
1378 (ido-ignore-item-temp-list bufs))
1379 (while (not (string-equal
1380 (setq buf (read-buffer
1381 (if (eq read-buffer-function #'ido-read-buffer)
1382 "Next buffer to search (C-j to end): "
1383 "Next buffer to search (RET to end): ")
1386 (add-to-list 'bufs buf)
1387 (setq ido-ignore-item-temp-list bufs))
1388 (nreverse (mapcar #'get-buffer bufs)))
1389 (occur-read-primary-args)))
1390 (occur-1 regexp nlines bufs))
1392 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1393 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1394 Normally BUFREGEXP matches against each buffer's visited file name,
1395 but if you specify a prefix argument, it matches against the buffer name.
1396 See also `multi-occur'."
1399 (let* ((default (car regexp-history))
1402 (if current-prefix-arg
1403 "List lines in buffers whose names match regexp: "
1404 "List lines in buffers whose filenames match regexp: "))))
1405 (if (equal input "")
1408 (occur-read-primary-args)))
1412 (mapcar (lambda (buf)
1414 (string-match bufregexp
1416 (and (buffer-file-name buf)
1417 (string-match bufregexp
1418 (buffer-file-name buf))))
1422 (defun occur-regexp-descr (regexp)
1423 (format " for %s\"%s\""
1424 (or (get-text-property 0 'isearch-regexp-function-descr regexp)
1426 (if (get-text-property 0 'isearch-string regexp)
1428 (query-replace-descr
1429 (get-text-property 0 'isearch-string regexp))
1431 (query-replace-descr regexp))))
1433 (defun occur-1 (regexp nlines bufs &optional buf-name)
1434 (unless (and regexp (not (equal regexp "")))
1435 (error "Occur doesn't work with the empty regexp"))
1437 (setq buf-name "*Occur*"))
1439 (active-bufs (delq nil (mapcar #'(lambda (buf)
1440 (when (buffer-live-p buf) buf))
1442 ;; Handle the case where one of the buffers we're searching is the
1443 ;; output buffer. Just rename it.
1444 (when (member buf-name (mapcar 'buffer-name active-bufs))
1445 (with-current-buffer (get-buffer buf-name)
1448 ;; Now find or create the output buffer.
1449 ;; If we just renamed that buffer, we will make a new one here.
1450 (setq occur-buf (get-buffer-create buf-name))
1452 (with-current-buffer occur-buf
1453 (if (stringp nlines)
1454 (fundamental-mode) ;; This is for collect operation.
1456 (let ((inhibit-read-only t)
1457 ;; Don't generate undo entries for creation of the initial contents.
1458 (buffer-undo-list t))
1461 (if (stringp nlines)
1462 ;; Treat nlines as a regexp to collect.
1463 (let ((bufs active-bufs)
1466 (with-current-buffer (car bufs)
1468 (goto-char (point-min))
1469 (while (re-search-forward regexp nil t)
1470 ;; Insert the replacement regexp.
1471 (let ((str (match-substitute-replacement nlines)))
1473 (with-current-buffer occur-buf
1475 (setq count (1+ count))
1476 (or (zerop (current-column))
1477 (insert "\n"))))))))
1478 (setq bufs (cdr bufs)))
1480 ;; Perform normal occur.
1482 regexp active-bufs occur-buf
1483 (or nlines list-matching-lines-default-context-lines)
1484 (if (and case-fold-search search-upper-case)
1485 (isearch-no-upper-case-p regexp t)
1487 list-matching-lines-buffer-name-face
1488 (if (face-differs-from-default-p list-matching-lines-prefix-face)
1489 list-matching-lines-prefix-face)
1490 list-matching-lines-face
1491 (not (eq occur-excluded-properties t))))))
1492 (let* ((bufcount (length active-bufs))
1493 (diff (- (length bufs) bufcount)))
1494 (message "Searched %d buffer%s%s; %s match%s%s"
1495 bufcount (if (= bufcount 1) "" "s")
1496 (if (zerop diff) "" (format " (%d killed)" diff))
1497 (if (zerop count) "no" (format "%d" count))
1498 (if (= count 1) "" "es")
1499 ;; Don't display regexp if with remaining text
1500 ;; it is longer than window-width.
1501 (if (> (+ (length (or (get-text-property 0 'isearch-string regexp)
1505 "" (occur-regexp-descr regexp))))
1506 (setq occur-revert-arguments (list regexp nlines bufs))
1508 (kill-buffer occur-buf)
1509 (display-buffer occur-buf)
1510 (setq next-error-last-buffer occur-buf)
1511 (setq buffer-read-only t)
1512 (set-buffer-modified-p nil)
1513 (run-hooks 'occur-hook)))))))
1515 (defun occur-engine (regexp buffers out-buf nlines case-fold
1516 title-face prefix-face match-face keep-props)
1517 (with-current-buffer out-buf
1518 (let ((global-lines 0) ;; total count of matching lines
1519 (global-matches 0) ;; total count of matches
1521 (case-fold-search case-fold))
1522 ;; Map over all the buffers
1523 (dolist (buf buffers)
1524 (when (buffer-live-p buf)
1525 (let ((lines 0) ;; count of matching lines
1526 (matches 0) ;; count of matches
1527 (curr-line 1) ;; line count
1528 (prev-line nil) ;; line number of prev match endpt
1529 (prev-after-lines nil) ;; context lines of prev match
1537 (inhibit-field-text-motion t)
1538 (headerpt (with-current-buffer out-buf (point))))
1539 (with-current-buffer buf
1541 ;; Set CODING only if the current buffer locally
1542 ;; binds buffer-file-coding-system.
1543 (not (local-variable-p 'buffer-file-coding-system))
1544 (setq coding buffer-file-coding-system))
1546 (goto-char (point-min)) ;; begin searching in the buffer
1548 (setq origpt (point))
1549 (when (setq endpt (re-search-forward regexp nil t))
1550 (setq lines (1+ lines)) ;; increment matching lines count
1551 (setq matchbeg (match-beginning 0))
1552 ;; Get beginning of first match line and end of the last.
1554 (goto-char matchbeg)
1555 (setq begpt (line-beginning-position))
1557 (setq endpt (line-end-position)))
1558 ;; Sum line numbers up to the first match line.
1559 (setq curr-line (+ curr-line (count-lines origpt begpt)))
1560 (setq marker (make-marker))
1561 (set-marker marker matchbeg)
1562 (setq curstring (occur-engine-line begpt endpt keep-props))
1563 ;; Highlight the matches
1564 (let ((len (length curstring))
1566 (while (and (< start len)
1567 (string-match regexp curstring start))
1568 (setq matches (1+ matches))
1569 (add-text-properties
1570 (match-beginning 0) (match-end 0)
1571 '(occur-match t) curstring)
1573 ;; Add `match-face' to faces copied from the buffer.
1574 (add-face-text-property
1575 (match-beginning 0) (match-end 0)
1576 match-face nil curstring))
1577 ;; Avoid infloop (Bug#7593).
1578 (let ((end (match-end 0)))
1579 (setq start (if (= start end) (1+ start) end)))))
1580 ;; Generate the string to insert for this match
1581 (let* ((match-prefix
1582 ;; Using 7 digits aligns tabs properly.
1583 (apply #'propertize (format "%7d:" curr-line)
1586 `(font-lock-face ,prefix-face))
1587 `(occur-prefix t mouse-face (highlight)
1588 ;; Allow insertion of text at
1589 ;; the end of the prefix (for
1590 ;; Occur Edit mode).
1591 front-sticky t rear-nonsticky t
1592 occur-target ,marker follow-link t
1593 help-echo "mouse-2: go to this occurrence"))))
1595 ;; We don't put `mouse-face' on the newline,
1596 ;; because that loses. And don't put it
1597 ;; on context lines to reduce flicker.
1598 (propertize curstring 'mouse-face (list 'highlight)
1599 'occur-target marker
1602 "mouse-2: go to this occurrence"))
1606 ;; Add non-numeric prefix to all non-first lines
1607 ;; of multi-line matches.
1608 (replace-regexp-in-string
1611 (propertize "\n :" 'font-lock-face prefix-face)
1614 ;; Add marker at eol, but no mouse props.
1615 (propertize "\n" 'occur-target marker)))
1618 ;; The simple display style
1620 ;; The complex multi-line display style.
1621 (setq ret (occur-context-lines
1622 out-line nlines keep-props begpt endpt
1623 curr-line prev-line prev-after-lines
1625 ;; Set first elem of the returned list to `data',
1626 ;; and the second elem to `prev-after-lines'.
1627 (setq prev-after-lines (nth 1 ret))
1629 ;; Actually insert the match display data
1630 (with-current-buffer out-buf
1635 ;; Sum line numbers between first and last match lines.
1636 (setq curr-line (+ curr-line (count-lines begpt endpt)
1637 ;; Add 1 for empty last match line since
1638 ;; count-lines returns 1 line less.
1639 (if (and (bolp) (eolp)) 1 0)))
1640 ;; On to the next match...
1642 (goto-char (point-max)))
1643 (setq prev-line (1- curr-line)))
1644 ;; Flush remaining context after-lines.
1645 (when prev-after-lines
1646 (with-current-buffer out-buf
1647 (insert (apply #'concat (occur-engine-add-prefix
1648 prev-after-lines prefix-face)))))))
1649 (when (not (zerop lines)) ;; is the count zero?
1650 (setq global-lines (+ global-lines lines)
1651 global-matches (+ global-matches matches))
1652 (with-current-buffer out-buf
1653 (goto-char headerpt)
1657 (format "%d match%s%s%s in buffer: %s\n"
1658 matches (if (= matches 1) "" "es")
1659 ;; Don't display the same number of lines
1660 ;; and matches in case of 1 match per line.
1661 (if (= lines matches)
1662 "" (format " in %d line%s"
1663 lines (if (= lines 1) "" "s")))
1664 ;; Don't display regexp for multi-buffer.
1665 (if (> (length buffers) 1)
1666 "" (occur-regexp-descr regexp))
1670 (add-text-properties beg end `(occur-title ,buf))
1672 (add-face-text-property beg end title-face)))
1673 (goto-char (point-min)))))))
1674 ;; Display total match count and regexp for multi-buffer.
1675 (when (and (not (zerop global-lines)) (> (length buffers) 1))
1676 (goto-char (point-min))
1679 (insert (format "%d match%s%s total%s:\n"
1680 global-matches (if (= global-matches 1) "" "es")
1681 ;; Don't display the same number of lines
1682 ;; and matches in case of 1 match per line.
1683 (if (= global-lines global-matches)
1684 "" (format " in %d line%s"
1685 global-lines (if (= global-lines 1) "" "s")))
1686 (occur-regexp-descr regexp)))
1689 (add-face-text-property beg end title-face)))
1690 (goto-char (point-min)))
1692 ;; CODING is buffer-file-coding-system of the first buffer
1693 ;; that locally binds it. Let's use it also for the output
1695 (set-buffer-file-coding-system coding))
1696 ;; Return the number of matches
1699 (defun occur-engine-line (beg end &optional keep-props)
1700 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1701 (text-property-not-all beg end 'fontified t))
1702 (if (fboundp 'jit-lock-fontify-now)
1703 (jit-lock-fontify-now beg end)))
1704 (if (and keep-props (not (eq occur-excluded-properties t)))
1705 (let ((str (buffer-substring beg end)))
1706 (remove-list-of-text-properties
1707 0 (length str) occur-excluded-properties str)
1709 (buffer-substring-no-properties beg end)))
1711 (defun occur-engine-add-prefix (lines &optional prefix-face)
1714 (concat (if prefix-face
1715 (propertize " :" 'font-lock-face prefix-face)
1720 (defun occur-accumulate-lines (count &optional keep-props pt)
1724 (let ((forwardp (> count 0))
1725 result beg end moved)
1726 (while (not (or (zerop count)
1729 (and (bobp) (not moved)))))
1730 (setq count (+ count (if forwardp -1 1)))
1731 (setq beg (line-beginning-position)
1732 end (line-end-position))
1733 (push (occur-engine-line beg end keep-props) result)
1734 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1735 (nreverse result))))
1737 ;; Generate context display for occur.
1738 ;; OUT-LINE is the line where the match is.
1739 ;; NLINES and KEEP-PROPS are args to occur-engine.
1740 ;; CURR-LINE is line count of the current match,
1741 ;; PREV-LINE is line count of the previous match,
1742 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1743 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1744 ;; then concatenate them all together.
1745 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1746 curr-line prev-line prev-after-lines
1747 &optional prefix-face)
1748 ;; Find after- and before-context lines of the current match.
1750 (nreverse (cdr (occur-accumulate-lines
1751 (- (1+ (abs nlines))) keep-props begpt))))
1753 (cdr (occur-accumulate-lines
1754 (1+ nlines) keep-props endpt)))
1757 ;; Combine after-lines of the previous match
1758 ;; with before-lines of the current match.
1760 (when prev-after-lines
1761 ;; Don't overlap prev after-lines with current before-lines.
1762 (if (>= (+ prev-line (length prev-after-lines))
1763 (- curr-line (length before-lines)))
1764 (setq prev-after-lines
1765 (butlast prev-after-lines
1766 (- (length prev-after-lines)
1767 (- curr-line prev-line (length before-lines) 1))))
1768 ;; Separate non-overlapping context lines with a dashed line.
1769 (setq separator "-------\n")))
1772 ;; Don't overlap current before-lines with previous match line.
1773 (if (<= (- curr-line (length before-lines))
1776 (nthcdr (- (length before-lines)
1777 (- curr-line prev-line 1))
1779 ;; Separate non-overlapping before-context lines.
1780 (unless (> nlines 0)
1781 (setq separator "-------\n"))))
1784 ;; Return a list where the first element is the output line.
1787 (if prev-after-lines
1788 (occur-engine-add-prefix prev-after-lines prefix-face))
1790 (list (if prefix-face
1791 (propertize separator 'font-lock-face prefix-face)
1793 (occur-engine-add-prefix before-lines prefix-face)
1795 ;; And the second element is the list of context after-lines.
1796 (if (> nlines 0) after-lines))))
1799 ;; It would be nice to use \\[...], but there is no reasonable way
1800 ;; to make that display both SPC and Y.
1801 (defconst query-replace-help
1802 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1803 RET or `q' to exit, Period to replace one match and exit,
1804 Comma to replace but not move point immediately,
1805 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1806 C-w to delete match and recursive edit,
1807 C-l to clear the screen, redisplay, and offer same replacement again,
1808 ! to replace all remaining matches in this buffer with no more questions,
1809 ^ to move point back to previous match,
1810 E to edit the replacement string.
1811 In multi-buffer replacements type `Y' to replace all remaining
1812 matches in all remaining buffers with no more questions,
1813 `N' to skip to the next buffer without replacing remaining matches
1814 in the current buffer."
1815 "Help message while in `query-replace'.")
1817 (defvar query-replace-map
1818 (let ((map (make-sparse-keymap)))
1819 (define-key map " " 'act)
1820 (define-key map "\d" 'skip)
1821 (define-key map [delete] 'skip)
1822 (define-key map [backspace] 'skip)
1823 (define-key map "y" 'act)
1824 (define-key map "n" 'skip)
1825 (define-key map "Y" 'act)
1826 (define-key map "N" 'skip)
1827 (define-key map "e" 'edit-replacement)
1828 (define-key map "E" 'edit-replacement)
1829 (define-key map "," 'act-and-show)
1830 (define-key map "q" 'exit)
1831 (define-key map "\r" 'exit)
1832 (define-key map [return] 'exit)
1833 (define-key map "." 'act-and-exit)
1834 (define-key map "\C-r" 'edit)
1835 (define-key map "\C-w" 'delete-and-edit)
1836 (define-key map "\C-l" 'recenter)
1837 (define-key map "!" 'automatic)
1838 (define-key map "^" 'backup)
1839 (define-key map "\C-h" 'help)
1840 (define-key map [f1] 'help)
1841 (define-key map [help] 'help)
1842 (define-key map "?" 'help)
1843 (define-key map "\C-g" 'quit)
1844 (define-key map "\C-]" 'quit)
1845 (define-key map "\C-v" 'scroll-up)
1846 (define-key map "\M-v" 'scroll-down)
1847 (define-key map [next] 'scroll-up)
1848 (define-key map [prior] 'scroll-down)
1849 (define-key map [?\C-\M-v] 'scroll-other-window)
1850 (define-key map [M-next] 'scroll-other-window)
1851 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1852 (define-key map [M-prior] 'scroll-other-window-down)
1853 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1854 ;; should check for ESC specially.
1855 ;; (define-key map "\e" 'exit-prefix)
1856 (define-key map [escape] 'exit-prefix)
1858 "Keymap of responses to questions posed by commands like `query-replace'.
1859 The \"bindings\" in this map are not commands; they are answers.
1860 The valid answers include `act', `skip', `act-and-show',
1861 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1862 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1863 `edit', `edit-replacement', `delete-and-edit', `automatic',
1864 `backup', `quit', and `help'.
1866 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1868 (defvar multi-query-replace-map
1869 (let ((map (make-sparse-keymap)))
1870 (set-keymap-parent map query-replace-map)
1871 (define-key map "Y" 'automatic-all)
1872 (define-key map "N" 'exit-current)
1874 "Keymap that defines additional bindings for multi-buffer replacements.
1875 It extends its parent map `query-replace-map' with new bindings to
1876 operate on a set of buffers/files. The difference with its parent map
1877 is the additional answers `automatic-all' to replace all remaining
1878 matches in all remaining buffers with no more questions, and
1879 `exit-current' to skip remaining matches in the current buffer
1880 and to continue with the next buffer in the sequence.")
1882 (defun replace-match-string-symbols (n)
1883 "Process a list (and any sub-lists), expanding certain symbols.
1885 N (match-string N) (where N is a string of digits)
1886 #N (string-to-number (match-string N))
1888 #& (string-to-number (match-string 0))
1891 Note that these symbols must be preceded by a backslash in order to
1892 type them using Lisp syntax."
1896 (replace-match-string-symbols (car n))) ;Process sub-list
1898 (let ((name (symbol-name (car n))))
1900 ((string-match "^[0-9]+$" name)
1901 (setcar n (list 'match-string (string-to-number name))))
1902 ((string-match "^#[0-9]+$" name)
1903 (setcar n (list 'string-to-number
1905 (string-to-number (substring name 1))))))
1907 (setcar n '(match-string 0)))
1908 ((string= "#&" name)
1909 (setcar n '(string-to-number (match-string 0))))
1911 (setcar n 'replace-count))))))
1914 (defun replace-eval-replacement (expression count)
1915 (let* ((replace-count count)
1921 (error "Error evaluating replacement expression: %S" err)))))
1922 (if (stringp replacement)
1924 (prin1-to-string replacement t))))
1926 (defun replace-quote (replacement)
1927 "Quote a replacement string.
1928 This just doubles all backslashes in REPLACEMENT and
1929 returns the resulting string. If REPLACEMENT is not
1930 a string, it is first passed through `prin1-to-string'
1931 with the `noescape' argument set.
1933 `match-data' is preserved across the call."
1935 (replace-regexp-in-string "\\\\" "\\\\"
1936 (if (stringp replacement)
1938 (prin1-to-string replacement t))
1941 (defun replace-loop-through-replacements (data count)
1942 ;; DATA is a vector containing the following values:
1943 ;; 0 next-rotate-count
1945 ;; 2 next-replacement
1947 (if (= (aref data 0) count)
1949 (aset data 0 (+ count (aref data 1)))
1950 (let ((next (cdr (aref data 2))))
1951 (aset data 2 (if (consp next) next (aref data 3))))))
1952 (car (aref data 2)))
1954 (defun replace-match-data (integers reuse &optional new)
1955 "Like `match-data', but markers in REUSE get invalidated.
1956 If NEW is non-nil, it is set and returned instead of fresh data,
1957 but coerced to the correct value of INTEGERS."
1960 (set-match-data new)
1962 (eq (null integers) (markerp (car reuse)))
1964 (match-data integers reuse t)))
1966 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data backward)
1967 "Make a replacement with `replace-match', editing `\\?'.
1968 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
1969 After possibly editing it (if `\\?' is present), NEWTEXT is also
1970 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
1971 is made (to save time). MATCH-DATA is used for the replacement.
1972 In case editing is done, it is changed to use markers.
1974 The return value is non-nil if there has been no `\\?' or NOEDIT was
1975 passed in. If LITERAL is set, no checking is done, anyway."
1976 (unless (or literal noedit)
1978 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1981 (read-string "Edit replacement string: "
1984 (replace-match "" t t newtext 3)
1985 (1+ (match-beginning 3)))
1988 nil match-data match-data))))
1990 (set-match-data match-data)
1991 (replace-match newtext fixedcase literal)
1992 ;; `replace-match' leaves point at the end of the replacement text,
1993 ;; so move point to the beginning when replacing backward.
1994 (when backward (goto-char (nth 0 match-data)))
1997 (defvar replace-search-function nil
1998 "Function to use when searching for strings to replace.
1999 It is used by `query-replace' and `replace-string', and is called
2000 with three arguments, as if it were `search-forward'.")
2002 (defvar replace-re-search-function nil
2003 "Function to use when searching for regexps to replace.
2004 It is used by `query-replace-regexp', `replace-regexp',
2005 `query-replace-regexp-eval', and `map-query-replace-regexp'.
2006 It is called with three arguments, as if it were
2007 `re-search-forward'.")
2009 (defun replace-search (search-string limit regexp-flag delimited-flag
2010 case-fold-search backward)
2011 "Search for the next occurrence of SEARCH-STRING to replace."
2012 ;; Let-bind global isearch-* variables to values used
2013 ;; to search the next replacement. These let-bindings
2014 ;; should be effective both at the time of calling
2015 ;; `isearch-search-fun-default' and also at the
2016 ;; time of funcalling `search-function'.
2017 ;; These isearch-* bindings can't be placed higher
2018 ;; outside of this function because then another I-search
2019 ;; used after `recursive-edit' might override them.
2020 (let* ((isearch-regexp regexp-flag)
2021 (isearch-regexp-function (or delimited-flag
2022 (and replace-character-fold
2024 #'character-fold-to-regexp)))
2025 (isearch-lax-whitespace
2026 replace-lax-whitespace)
2027 (isearch-regexp-lax-whitespace
2028 replace-regexp-lax-whitespace)
2029 (isearch-case-fold-search case-fold-search)
2030 (isearch-adjusted nil)
2031 (isearch-nonincremental t) ; don't use lax word mode
2032 (isearch-forward (not backward))
2035 replace-re-search-function
2036 replace-search-function)
2037 (isearch-search-fun-default))))
2038 (funcall search-function search-string limit t)))
2040 (defvar replace-overlay nil)
2042 (defun replace-highlight (match-beg match-end range-beg range-end
2043 search-string regexp-flag delimited-flag
2044 case-fold-search backward)
2045 (if query-replace-highlight
2047 (move-overlay replace-overlay match-beg match-end (current-buffer))
2048 (setq replace-overlay (make-overlay match-beg match-end))
2049 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2050 (overlay-put replace-overlay 'face 'query-replace)))
2051 (if query-replace-lazy-highlight
2052 (let ((isearch-string search-string)
2053 (isearch-regexp regexp-flag)
2054 (isearch-regexp-function delimited-flag)
2055 (isearch-lax-whitespace
2056 replace-lax-whitespace)
2057 (isearch-regexp-lax-whitespace
2058 replace-regexp-lax-whitespace)
2059 (isearch-case-fold-search case-fold-search)
2060 (isearch-forward (not backward))
2061 (isearch-other-end match-beg)
2062 (isearch-error nil))
2063 (isearch-lazy-highlight-new-loop range-beg range-end))))
2065 (defun replace-dehighlight ()
2066 (when replace-overlay
2067 (delete-overlay replace-overlay))
2068 (when query-replace-lazy-highlight
2069 (lazy-highlight-cleanup lazy-highlight-cleanup)
2070 (setq isearch-lazy-highlight-last-string nil))
2071 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2072 (isearch-clean-overlays))
2074 (defun perform-replace (from-string replacements
2075 query-flag regexp-flag delimited-flag
2076 &optional repeat-count map start end backward region-noncontiguous-p)
2077 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2078 Don't use this in your own program unless you want to query and set the mark
2079 just as `query-replace' does. Instead, write a simple loop like this:
2081 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2082 (replace-match \"foobar\" nil nil))
2084 which will run faster and probably do exactly what you want. Please
2085 see the documentation of `replace-match' to find out how to simulate
2088 This function returns nil if and only if there were no matches to
2089 make, or the user didn't cancel the call.
2091 REPLACEMENTS is either a string, a list of strings, or a cons cell
2092 containing a function and its first argument. The function is
2093 called to generate each replacement like this:
2094 (funcall (car replacements) (cdr replacements) replace-count)
2095 It must return a string."
2096 (or map (setq map query-replace-map))
2097 (and query-flag minibuffer-auto-raise
2098 (raise-frame (window-frame (minibuffer-window))))
2099 (let* ((case-fold-search
2100 (if (and case-fold-search search-upper-case)
2101 (isearch-no-upper-case-p from-string regexp-flag)
2103 (nocasify (not (and case-replace case-fold-search)))
2104 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2105 (search-string from-string)
2106 (real-match-data nil) ; The match data for the current match.
2107 (next-replacement nil)
2108 ;; This is non-nil if we know there is nothing for the user
2109 ;; to edit in the replacement.
2114 (skip-read-only-count 0)
2115 (skip-filtered-count 0)
2116 (skip-invisible-count 0)
2117 (nonempty-match nil)
2119 (recenter-last-op nil) ; Start cycling order with initial position.
2121 ;; If non-nil, it is marker saying where in the buffer to stop.
2123 ;; Use local binding in add-function below.
2124 (isearch-filter-predicate isearch-filter-predicate)
2127 ;; Data for the next match. If a cons, it has the same format as
2128 ;; (match-data); otherwise it is t if a match is possible at point.
2134 (substitute-command-keys
2135 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2136 minibuffer-prompt-properties))))
2138 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
2139 (when region-noncontiguous-p
2141 (mapcar (lambda (position)
2142 (cons (copy-marker (car position))
2143 (copy-marker (cdr position))))
2144 (funcall region-extract-function 'bounds)))
2145 (add-function :after-while isearch-filter-predicate
2150 (>= start (car bounds))
2151 (<= start (cdr bounds))
2152 (>= end (car bounds))
2153 (<= end (cdr bounds))))
2156 ;; If region is active, in Transient Mark mode, operate on region.
2159 (setq limit (copy-marker (min start end)))
2160 (goto-char (max start end))
2163 (setq limit (copy-marker (max start end)))
2164 (goto-char (min start end))
2167 ;; If last typed key in previous call of multi-buffer perform-replace
2168 ;; was `automatic-all', don't ask more questions in next files
2169 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2170 (setq query-flag nil multi-buffer t))
2173 ((stringp replacements)
2174 (setq next-replacement replacements
2176 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2177 (or repeat-count (setq repeat-count 1))
2178 (setq replacements (cons 'replace-loop-through-replacements
2179 (vector repeat-count repeat-count
2180 replacements replacements)))))
2182 (when query-replace-lazy-highlight
2183 (setq isearch-lazy-highlight-last-string nil))
2188 ;; Loop finding occurrences that perhaps should be replaced.
2189 (while (and keep-going
2191 (not (or (bobp) (and limit (<= (point) limit))))
2192 (not (or (eobp) (and limit (>= (point) limit)))))
2193 ;; Use the next match if it is already known;
2194 ;; otherwise, search for a match after moving forward
2195 ;; one char if progress is required.
2196 (setq real-match-data
2197 (cond ((consp match-again)
2198 (goto-char (if backward
2200 (nth 1 match-again)))
2202 t real-match-data match-again))
2203 ;; MATCH-AGAIN non-nil means accept an
2207 (replace-search search-string limit
2208 regexp-flag delimited-flag
2209 case-fold-search backward)
2210 ;; For speed, use only integers and
2211 ;; reuse the list used last time.
2212 (replace-match-data t real-match-data)))
2214 (> (1- (point)) (point-min))
2215 (< (1+ (point)) (point-max)))
2218 (> (1- (point)) limit)
2219 (< (1+ (point)) limit))))
2220 ;; If not accepting adjacent matches,
2221 ;; move one char to the right before
2222 ;; searching again. Undo the motion
2223 ;; if the search fails.
2224 (let ((opoint (point)))
2225 (forward-char (if backward -1 1))
2226 (if (replace-search search-string limit
2227 regexp-flag delimited-flag
2228 case-fold-search backward)
2234 ;; Record whether the match is nonempty, to avoid an infinite loop
2235 ;; repeatedly matching the same empty string.
2236 (setq nonempty-match
2237 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2239 ;; If the match is empty, record that the next one can't be
2242 ;; Otherwise, if matching a regular expression, do the next
2243 ;; match now, since the replacement for this match may
2244 ;; affect whether the next match is adjacent to this one.
2245 ;; If that match is empty, don't use it.
2248 (or (not regexp-flag)
2250 (looking-back search-string)
2251 (looking-at search-string))
2252 (let ((match (match-data)))
2253 (and (/= (nth 0 match) (nth 1 match))
2257 ;; Optionally ignore matches that have a read-only property.
2258 ((not (or (not query-replace-skip-read-only)
2259 (not (text-property-not-all
2260 (nth 0 real-match-data) (nth 1 real-match-data)
2262 (setq skip-read-only-count (1+ skip-read-only-count)))
2263 ;; Optionally filter out matches.
2264 ((not (funcall isearch-filter-predicate
2265 (nth 0 real-match-data) (nth 1 real-match-data)))
2266 (setq skip-filtered-count (1+ skip-filtered-count)))
2267 ;; Optionally ignore invisible matches.
2268 ((not (or (eq search-invisible t)
2269 ;; Don't open overlays for automatic replacements.
2270 (and (not query-flag) search-invisible)
2271 ;; Open hidden overlays for interactive replacements.
2272 (not (isearch-range-invisible
2273 (nth 0 real-match-data) (nth 1 real-match-data)))))
2274 (setq skip-invisible-count (1+ skip-invisible-count)))
2276 ;; Calculate the replacement string, if necessary.
2278 (set-match-data real-match-data)
2279 (setq next-replacement
2280 (funcall (car replacements) (cdr replacements)
2282 (if (not query-flag)
2284 (unless (or literal noedit)
2286 (nth 0 real-match-data) (nth 1 real-match-data)
2287 start end search-string
2288 regexp-flag delimited-flag case-fold-search backward))
2290 (replace-match-maybe-edit
2291 next-replacement nocasify literal
2292 noedit real-match-data backward)
2293 replace-count (1+ replace-count)))
2295 (let (done replaced key def)
2296 ;; Loop reading commands until one of them sets done,
2297 ;; which means it has finished handling this
2298 ;; occurrence. Any command that sets `done' should
2299 ;; leave behind proper match data for the stack.
2300 ;; Commands not setting `done' need to adjust
2301 ;; `real-match-data'.
2303 (set-match-data real-match-data)
2305 (match-beginning 0) (match-end 0)
2306 start end search-string
2307 regexp-flag delimited-flag case-fold-search backward)
2308 ;; Bind message-log-max so we don't fill up the message log
2309 ;; with a bunch of identical messages.
2310 (let ((message-log-max nil)
2311 (replacement-presentation
2312 (if query-replace-show-replacement
2314 (set-match-data real-match-data)
2315 (match-substitute-replacement next-replacement
2319 (query-replace-descr from-string)
2320 (query-replace-descr replacement-presentation)))
2321 (setq key (read-event))
2322 ;; Necessary in case something happens during read-event
2323 ;; that clobbers the match data.
2324 (set-match-data real-match-data)
2325 (setq key (vector key))
2326 (setq def (lookup-key map key))
2327 ;; Restore the match data while we process the command.
2328 (cond ((eq def 'help)
2329 (with-output-to-temp-buffer "*Help*"
2331 (concat "Query replacing "
2333 (or (and (symbolp delimited-flag)
2334 (get delimited-flag 'isearch-message-prefix))
2336 (if regexp-flag "regexp " "")
2337 (if backward "backward " "")
2338 from-string " with "
2339 next-replacement ".\n\n"
2340 (substitute-command-keys
2341 query-replace-help)))
2342 (with-current-buffer standard-output
2345 (setq keep-going nil)
2347 ((eq def 'exit-current)
2348 (setq multi-buffer t keep-going nil done t))
2351 (let ((elt (pop stack)))
2352 (goto-char (nth 0 elt))
2353 (setq replaced (nth 1 elt)
2358 (message "No previous match")
2359 (ding 'no-terminate)
2364 (replace-match-maybe-edit
2365 next-replacement nocasify literal
2366 noedit real-match-data backward)
2367 replace-count (1+ replace-count)))
2368 (setq done t replaced t))
2369 ((eq def 'act-and-exit)
2372 (replace-match-maybe-edit
2373 next-replacement nocasify literal
2374 noedit real-match-data backward)
2375 replace-count (1+ replace-count)))
2376 (setq keep-going nil)
2377 (setq done t replaced t))
2378 ((eq def 'act-and-show)
2381 (replace-match-maybe-edit
2382 next-replacement nocasify literal
2383 noedit real-match-data backward)
2384 replace-count (1+ replace-count)
2385 real-match-data (replace-match-data
2388 ((or (eq def 'automatic) (eq def 'automatic-all))
2391 (replace-match-maybe-edit
2392 next-replacement nocasify literal
2393 noedit real-match-data backward)
2394 replace-count (1+ replace-count)))
2395 (setq done t query-flag nil replaced t)
2396 (if (eq def 'automatic-all) (setq multi-buffer t)))
2400 ;; `this-command' has the value `query-replace',
2401 ;; so we need to bind it to `recenter-top-bottom'
2402 ;; to allow it to detect a sequence of `C-l'.
2403 (let ((this-command 'recenter-top-bottom)
2404 (last-command 'recenter-top-bottom))
2405 (recenter-top-bottom)))
2407 (let ((opos (point-marker)))
2408 (setq real-match-data (replace-match-data
2411 (goto-char (match-beginning 0))
2413 (save-window-excursion
2416 (set-marker opos nil))
2417 ;; Before we make the replacement,
2418 ;; decide whether the search string
2419 ;; can match again just after this match.
2420 (if (and regexp-flag nonempty-match)
2421 (setq match-again (and (looking-at search-string)
2423 ;; Edit replacement.
2424 ((eq def 'edit-replacement)
2425 (setq real-match-data (replace-match-data
2429 (read-string "Edit replacement string: "
2433 (set-match-data real-match-data)
2435 (replace-match-maybe-edit
2436 next-replacement nocasify literal noedit
2437 real-match-data backward)
2441 ((eq def 'delete-and-edit)
2442 (replace-match "" t t)
2443 (setq real-match-data (replace-match-data
2444 nil real-match-data))
2445 (replace-dehighlight)
2446 (save-excursion (recursive-edit))
2448 ;; Note: we do not need to treat `exit-prefix'
2449 ;; specially here, since we reread
2450 ;; any unrecognized character.
2452 (setq this-command 'mode-exited)
2453 (setq keep-going nil)
2454 (setq unread-command-events
2455 (append (listify-key-sequence key)
2456 unread-command-events))
2458 (when query-replace-lazy-highlight
2459 ;; Force lazy rehighlighting only after replacements.
2460 (if (not (memq def '(skip backup)))
2461 (setq isearch-lazy-highlight-last-string nil)))
2462 (unless (eq def 'recenter)
2463 ;; Reset recenter cycling order to initial position.
2464 (setq recenter-last-op nil)))
2465 ;; Record previous position for ^ when we move on.
2466 ;; Change markers to numbers in the match data
2467 ;; since lots of markers slow down editing.
2468 (push (list (point) replaced
2469 ;;; If the replacement has already happened, all we need is the
2470 ;;; current match start and end. We could get this with a trivial
2472 ;;; (save-excursion (goto-char (match-beginning 0))
2473 ;;; (search-forward (match-string 0))
2475 ;;; if we really wanted to avoid manually constructing match data.
2476 ;;; Adding current-buffer is necessary so that match-data calls can
2477 ;;; return markers which are appropriate for editing.
2486 (replace-dehighlight))
2487 (or unread-command-events
2488 (message "Replaced %d occurrence%s%s"
2490 (if (= replace-count 1) "" "s")
2491 (if (> (+ skip-read-only-count
2493 skip-invisible-count) 0)
2494 (format " (skipped %s)"
2498 (if (> skip-read-only-count 0)
2499 (format "%s read-only"
2500 skip-read-only-count))
2501 (if (> skip-invisible-count 0)
2502 (format "%s invisible"
2503 skip-invisible-count))
2504 (if (> skip-filtered-count 0)
2505 (format "%s filtered out"
2506 skip-filtered-count))))
2509 (or (and keep-going stack) multi-buffer)))
2511 ;;; replace.el ends here