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 `query-replace' should do character folding in matches.
38 This means, for instance, that \\=' will match a large variety of
44 (defcustom replace-lax-whitespace nil
45 "Non-nil means `query-replace' matches a sequence of whitespace chars.
46 When you enter a space or spaces in the strings to be replaced,
47 it will match any sequence matched by the regexp `search-whitespace-regexp'."
52 (defcustom replace-regexp-lax-whitespace nil
53 "Non-nil means `query-replace-regexp' matches a sequence of whitespace chars.
54 When you enter a space or spaces in the regexps to be replaced,
55 it will match any sequence matched by the regexp `search-whitespace-regexp'."
60 (defvar query-replace-history nil
61 "Default history list for query-replace commands.
62 See `query-replace-from-history-variable' and
63 `query-replace-to-history-variable'.")
65 (defvar query-replace-defaults nil
66 "Default values of FROM-STRING and TO-STRING for `query-replace'.
67 This is a list of cons cells (FROM-STRING . TO-STRING), or nil
68 if there are no default values.")
70 (defvar query-replace-interactive nil
71 "Non-nil means `query-replace' uses the last search string.
72 That becomes the \"string to replace\".")
73 (make-obsolete-variable 'query-replace-interactive
74 "use `M-n' to pull the last incremental search string
75 to the minibuffer that reads the string to replace, or invoke replacements
76 from Isearch by using a key sequence like `C-s C-s M-%'." "24.3")
78 (defcustom query-replace-from-to-separator
79 (propertize (if (char-displayable-p ?→) " → " " -> ")
80 'face 'minibuffer-prompt)
81 "String that separates FROM and TO in the history of replacement pairs."
82 ;; Avoids error when attempt to autoload char-displayable-p fails
83 ;; while preparing to dump, also stops customize-rogue listing this.
84 :initialize 'custom-initialize-delay
89 (defcustom query-replace-from-history-variable 'query-replace-history
90 "History list to use for the FROM argument of `query-replace' commands.
91 The value of this variable should be a symbol; that symbol
92 is used as a variable to hold a history list for the strings
93 or patterns to be replaced."
98 (defcustom query-replace-to-history-variable 'query-replace-history
99 "History list to use for the TO argument of `query-replace' commands.
100 The value of this variable should be a symbol; that symbol
101 is used as a variable to hold a history list for replacement
102 strings or patterns."
107 (defcustom query-replace-skip-read-only nil
108 "Non-nil means `query-replace' and friends ignore read-only matches."
113 (defcustom query-replace-show-replacement t
114 "Non-nil means to show what actual replacement text will be."
119 (defcustom query-replace-highlight t
120 "Non-nil means to highlight matches during query replacement."
124 (defcustom query-replace-lazy-highlight t
125 "Controls the lazy-highlighting during query replacements.
126 When non-nil, all text in the buffer matching the current match
127 is highlighted lazily using isearch lazy highlighting (see
128 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
130 :group 'lazy-highlight
134 (defface query-replace
135 '((t (:inherit isearch)))
136 "Face for highlighting query replacement matches."
140 (defvar replace-count 0
141 "Number of replacements done so far.
142 See `replace-regexp' and `query-replace-regexp-eval'.")
144 (defun query-replace-descr (string)
145 (mapconcat 'isearch-text-char-description string ""))
147 (defun query-replace--split-string (string)
148 "Split string STRING at a character with property `separator'"
149 (let* ((length (length string))
150 (split-pos (text-property-any 0 length 'separator t string)))
152 (substring-no-properties string)
153 (cl-assert (not (text-property-any (1+ split-pos) length 'separator t string)))
154 (cons (substring-no-properties string 0 split-pos)
155 (substring-no-properties string (1+ split-pos) length)))))
157 (defun query-replace-read-from (prompt regexp-flag)
158 "Query and return the `from' argument of a query-replace operation.
159 The return value can also be a pair (FROM . TO) indicating that the user
160 wants to replace FROM with TO."
161 (if query-replace-interactive
162 (car (if regexp-flag regexp-search-ring search-ring))
163 ;; Reevaluating will check char-displayable-p that is
164 ;; unavailable while preparing to dump.
165 (custom-reevaluate-setting 'query-replace-from-to-separator)
166 (let* ((history-add-new-input nil)
167 (text-property-default-nonsticky
168 (cons '(separator . t) text-property-default-nonsticky))
170 (when query-replace-from-to-separator
172 'display query-replace-from-to-separator
174 (query-replace-from-to-history
177 (mapcar (lambda (from-to)
178 (concat (query-replace-descr (car from-to))
180 (query-replace-descr (cdr from-to))))
181 query-replace-defaults))
182 (symbol-value query-replace-from-history-variable)))
183 (minibuffer-allow-text-properties t) ; separator uses text-properties
185 (if (and query-replace-defaults separator)
186 (format "%s (default %s): " prompt (car query-replace-from-to-history))
187 (format "%s: " prompt)))
189 ;; The save-excursion here is in case the user marks and copies
190 ;; a region in order to specify the minibuffer input.
191 ;; That should not clobber the region for the query-replace itself.
194 (read-regexp prompt nil 'query-replace-from-to-history)
195 (read-from-minibuffer
196 prompt nil nil nil 'query-replace-from-to-history
197 (car (if regexp-flag regexp-search-ring search-ring)) t))))
199 (if (and (zerop (length from)) query-replace-defaults)
200 (cons (caar query-replace-defaults)
201 (query-replace-compile-replacement
202 (cdar query-replace-defaults) regexp-flag))
203 (setq from (query-replace--split-string from))
204 (when (consp from) (setq to (cdr from) from (car from)))
205 (add-to-history query-replace-from-history-variable from nil t)
206 ;; Warn if user types \n or \t, but don't reject the input.
208 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
209 (let ((match (match-string 3 from)))
211 ((string= match "\\n")
212 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
213 ((string= match "\\t")
214 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
218 (add-to-history query-replace-to-history-variable to nil t)
219 (add-to-history 'query-replace-defaults (cons from to) nil t)
220 (cons from (query-replace-compile-replacement to regexp-flag)))))))
222 (defun query-replace-compile-replacement (to regexp-flag)
223 "Maybe convert a regexp replacement TO to Lisp.
224 Returns a list suitable for `perform-replace' if necessary,
225 the original string if not."
227 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
231 (setq pos (match-end 0))
232 (push (substring to 0 (- pos 2)) list)
233 (setq char (aref to (1- pos))
234 to (substring to pos))
236 (push '(number-to-string replace-count) list))
238 (setq pos (read-from-string to))
239 (push `(replace-quote ,(car pos)) list)
241 ;; Swallow a space after a symbol
242 ;; if there is a space.
243 (if (and (or (symbolp (car pos))
244 ;; Swallow a space after 'foo
245 ;; but not after (quote foo).
246 (and (eq (car-safe (car pos)) 'quote)
247 (not (= ?\( (aref to 0)))))
248 (eq (string-match " " to (cdr pos))
252 (setq to (substring to end)))))
253 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
254 (setq to (nreverse (delete "" (cons to list))))
255 (replace-match-string-symbols to)
256 (cons 'replace-eval-replacement
263 (defun query-replace-read-to (from prompt regexp-flag)
264 "Query and return the `to' argument of a query-replace operation."
265 (query-replace-compile-replacement
267 (let* ((history-add-new-input nil)
268 (to (read-from-minibuffer
269 (format "%s %s with: " prompt (query-replace-descr from))
271 query-replace-to-history-variable from t)))
272 (add-to-history query-replace-to-history-variable to nil t)
273 (add-to-history 'query-replace-defaults (cons from to) nil t)
277 (defun query-replace-read-args (prompt regexp-flag &optional noerror)
279 (barf-if-buffer-read-only))
280 (let* ((from (query-replace-read-from prompt regexp-flag))
281 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
282 (query-replace-read-to from prompt regexp-flag))))
284 (and current-prefix-arg (not (eq current-prefix-arg '-)))
285 (and current-prefix-arg (eq current-prefix-arg '-)))))
287 (defun query-replace (from-string to-string &optional delimited start end backward region-noncontiguous-p)
288 "Replace some occurrences of FROM-STRING with TO-STRING.
289 As each match is found, the user must type a character saying
290 what to do with it. For directions, type \\[help-command] at that time.
292 In Transient Mark mode, if the mark is active, operate on the contents
293 of the region. Otherwise, operate from point to the end of the buffer.
295 Use \\<minibuffer-local-map>\\[next-history-element] \
296 to pull the last incremental search string to the minibuffer
297 that reads FROM-STRING, or invoke replacements from
298 incremental search with a key sequence like `C-s C-s M-%'
299 to use its current search string as the string to replace.
301 Matching is independent of case if `case-fold-search' is non-nil and
302 FROM-STRING has no uppercase letters. Replacement transfers the case
303 pattern of the old text to the new text, if `case-replace' and
304 `case-fold-search' are non-nil and FROM-STRING has no uppercase
305 letters. (Transferring the case pattern means that if the old text
306 matched is all caps, or capitalized, then its replacement is upcased
309 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
310 ignore hidden matches if `search-invisible' is nil, and ignore more
311 matches using `isearch-filter-predicate'.
313 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
314 to be replaced will match a sequence of whitespace chars defined by the
315 regexp in `search-whitespace-regexp'.
317 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
318 only matches surrounded by word boundaries. A negative prefix arg means
321 Fourth and fifth arg START and END specify the region to operate on.
323 To customize possible responses, change the bindings in `query-replace-map'."
326 (query-replace-read-args
327 (concat "Query replace"
328 (if current-prefix-arg
329 (if (eq current-prefix-arg '-) " backward" " word")
331 (if (use-region-p) " in region" ""))
333 (list (nth 0 common) (nth 1 common) (nth 2 common)
334 ;; These are done separately here
335 ;; so that command-history will record these expressions
336 ;; rather than the values they had this time.
337 (if (use-region-p) (region-beginning))
338 (if (use-region-p) (region-end))
340 (if (use-region-p) (region-noncontiguous-p)))))
341 (perform-replace from-string to-string t nil delimited nil nil start end backward region-noncontiguous-p))
343 (define-key esc-map "%" 'query-replace)
345 (defun query-replace-regexp (regexp to-string &optional delimited start end backward region-noncontiguous-p)
346 "Replace some things after point matching REGEXP with TO-STRING.
347 As each match is found, the user must type a character saying
348 what to do with it. For directions, type \\[help-command] at that time.
350 In Transient Mark mode, if the mark is active, operate on the contents
351 of the region. Otherwise, operate from point to the end of the buffer.
353 Use \\<minibuffer-local-map>\\[next-history-element] \
354 to pull the last incremental search regexp to the minibuffer
355 that reads REGEXP, or invoke replacements from
356 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
357 to use its current search regexp as the regexp to replace.
359 Matching is independent of case if `case-fold-search' is non-nil and
360 REGEXP has no uppercase letters. Replacement transfers the case
361 pattern of the old text to the new text, if `case-replace' and
362 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
363 \(Transferring the case pattern means that if the old text matched is
364 all caps, or capitalized, then its replacement is upcased or
367 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
368 ignore hidden matches if `search-invisible' is nil, and ignore more
369 matches using `isearch-filter-predicate'.
371 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
372 to be replaced will match a sequence of whitespace chars defined by the
373 regexp in `search-whitespace-regexp'.
375 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
376 only matches surrounded by word boundaries. A negative prefix arg means
379 Fourth and fifth arg START and END specify the region to operate on.
381 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
382 and `\\=\\N' (where N is a digit) stands for
383 whatever what matched the Nth `\\(...\\)' in REGEXP.
384 `\\?' lets you edit the replacement text in the minibuffer
385 at the given position for each replacement.
387 In interactive calls, the replacement text can contain `\\,'
388 followed by a Lisp expression. Each
389 replacement evaluates that expression to compute the replacement
390 string. Inside of that expression, `\\&' is a string denoting the
391 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
392 for the whole or a partial match converted to a number with
393 `string-to-number', and `\\#' itself for the number of replacements
394 done so far (starting with zero).
396 If the replacement expression is a symbol, write a space after it
397 to terminate it. One space there, if any, will be discarded.
399 When using those Lisp features interactively in the replacement
400 text, TO-STRING is actually made a list instead of a string.
401 Use \\[repeat-complex-command] after this command for details."
404 (query-replace-read-args
405 (concat "Query replace"
406 (if current-prefix-arg
407 (if (eq current-prefix-arg '-) " backward" " word")
410 (if (use-region-p) " in region" ""))
412 (list (nth 0 common) (nth 1 common) (nth 2 common)
413 ;; These are done separately here
414 ;; so that command-history will record these expressions
415 ;; rather than the values they had this time.
416 (if (use-region-p) (region-beginning))
417 (if (use-region-p) (region-end))
419 (if (use-region-p) (region-noncontiguous-p)))))
420 (perform-replace regexp to-string t t delimited nil nil start end backward region-noncontiguous-p))
422 (define-key esc-map [?\C-%] 'query-replace-regexp)
424 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
425 "Replace some things after point matching REGEXP with the result of TO-EXPR.
427 Interactive use of this function is deprecated in favor of the
428 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
429 using `search-forward-regexp' and `replace-match' is preferred.
431 As each match is found, the user must type a character saying
432 what to do with it. For directions, type \\[help-command] at that time.
434 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
435 reference `replace-count' to get the number of replacements already made.
436 If the result of TO-EXPR is not a string, it is converted to one using
437 `prin1-to-string' with the NOESCAPE argument (which see).
439 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
440 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
441 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
442 Use `\\#&' or `\\#N' if you want a number instead of a string.
443 In interactive use, `\\#' in itself stands for `replace-count'.
445 In Transient Mark mode, if the mark is active, operate on the contents
446 of the region. Otherwise, operate from point to the end of the buffer.
448 Use \\<minibuffer-local-map>\\[next-history-element] \
449 to pull the last incremental search regexp to the minibuffer
452 Preserves case in each replacement if `case-replace' and `case-fold-search'
453 are non-nil and REGEXP has no uppercase letters.
455 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
456 ignore hidden matches if `search-invisible' is nil, and ignore more
457 matches using `isearch-filter-predicate'.
459 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
460 to be replaced will match a sequence of whitespace chars defined by the
461 regexp in `search-whitespace-regexp'.
463 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
464 only matches that are surrounded by word boundaries.
465 Fourth and fifth arg START and END specify the region to operate on."
466 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
467 for interactive calls, and `search-forward-regexp'/`replace-match'
468 for Lisp calls." "22.1"))
471 (barf-if-buffer-read-only)
473 ;; Let-bind the history var to disable the "foo -> bar"
474 ;; default. Maybe we shouldn't disable this default, but
475 ;; for now I'll leave it off. --Stef
476 (let ((query-replace-defaults nil))
477 (query-replace-read-from "Query replace regexp" t)))
478 (to (list (read-from-minibuffer
479 (format "Query replace regexp %s with eval: "
480 (query-replace-descr from))
481 nil nil t query-replace-to-history-variable from t))))
482 ;; We make TO a list because replace-match-string-symbols requires one,
483 ;; and the user might enter a single token.
484 (replace-match-string-symbols to)
485 (list from (car to) current-prefix-arg
486 (if (use-region-p) (region-beginning))
487 (if (use-region-p) (region-end))))))
488 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
489 t 'literal delimited nil nil start end))
491 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
492 "Replace some matches for REGEXP with various strings, in rotation.
493 The second argument TO-STRINGS contains the replacement strings, separated
494 by spaces. This command works like `query-replace-regexp' except that
495 each successive replacement uses the next successive replacement string,
496 wrapping around from the last such string to the first.
498 In Transient Mark mode, if the mark is active, operate on the contents
499 of the region. Otherwise, operate from point to the end of the buffer.
501 Non-interactively, TO-STRINGS may be a list of replacement strings.
503 Interactively, reads the regexp using `read-regexp'.
504 Use \\<minibuffer-local-map>\\[next-history-element] \
505 to pull the last incremental search regexp to the minibuffer
508 A prefix argument N says to use each replacement string N times
509 before rotating to the next.
510 Fourth and fifth arg START and END specify the region to operate on."
512 (let* ((from (read-regexp "Map query replace (regexp): " nil
513 query-replace-from-history-variable))
514 (to (read-from-minibuffer
515 (format "Query replace %s with (space-separated strings): "
516 (query-replace-descr from))
518 query-replace-to-history-variable from t)))
520 (and current-prefix-arg
521 (prefix-numeric-value current-prefix-arg))
522 (if (use-region-p) (region-beginning))
523 (if (use-region-p) (region-end)))))
525 (if (listp to-strings)
526 (setq replacements to-strings)
527 (while (/= (length to-strings) 0)
528 (if (string-match " " to-strings)
531 (list (substring to-strings 0
532 (string-match " " to-strings))))
533 to-strings (substring to-strings
534 (1+ (string-match " " to-strings))))
535 (setq replacements (append replacements (list to-strings))
537 (perform-replace regexp replacements t t nil n nil start end)))
539 (defun replace-string (from-string to-string &optional delimited start end backward)
540 "Replace occurrences of FROM-STRING with TO-STRING.
541 Preserve case in each match if `case-replace' and `case-fold-search'
542 are non-nil and FROM-STRING has no uppercase letters.
543 \(Preserving case means that if the string matched is all caps, or capitalized,
544 then its replacement is upcased or capitalized.)
546 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
547 ignore hidden matches if `search-invisible' is nil, and ignore more
548 matches using `isearch-filter-predicate'.
550 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
551 to be replaced will match a sequence of whitespace chars defined by the
552 regexp in `search-whitespace-regexp'.
554 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
555 only matches surrounded by word boundaries. A negative prefix arg means
558 Operates on the region between START and END (if both are nil, from point
559 to the end of the buffer). Interactively, if Transient Mark mode is
560 enabled and the mark is active, operates on the contents of the region;
561 otherwise from point to the end of the buffer.
563 Use \\<minibuffer-local-map>\\[next-history-element] \
564 to pull the last incremental search string to the minibuffer
565 that reads FROM-STRING.
567 This function is usually the wrong thing to use in a Lisp program.
568 What you probably want is a loop like this:
569 (while (search-forward FROM-STRING nil t)
570 (replace-match TO-STRING nil t))
571 which will run faster and will not set the mark or print anything.
572 \(You may need a more complex loop if FROM-STRING can match the null string
573 and TO-STRING is also null.)"
574 (declare (interactive-only
575 "use `search-forward' and `replace-match' instead."))
578 (query-replace-read-args
580 (if current-prefix-arg
581 (if (eq current-prefix-arg '-) " backward" " word")
584 (if (use-region-p) " in region" ""))
586 (list (nth 0 common) (nth 1 common) (nth 2 common)
587 (if (use-region-p) (region-beginning))
588 (if (use-region-p) (region-end))
590 (perform-replace from-string to-string nil nil delimited nil nil start end backward))
592 (defun replace-regexp (regexp to-string &optional delimited start end backward)
593 "Replace things after point matching REGEXP with TO-STRING.
594 Preserve case in each match if `case-replace' and `case-fold-search'
595 are non-nil and REGEXP has no uppercase letters.
597 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
598 ignore hidden matches if `search-invisible' is nil, and ignore more
599 matches using `isearch-filter-predicate'.
601 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
602 to be replaced will match a sequence of whitespace chars defined by the
603 regexp in `search-whitespace-regexp'.
605 In Transient Mark mode, if the mark is active, operate on the contents
606 of the region. Otherwise, operate from point to the end of the buffer.
608 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
609 only matches surrounded by word boundaries. A negative prefix arg means
612 Fourth and fifth arg START and END specify the region to operate on.
614 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
615 and `\\=\\N' (where N is a digit) stands for
616 whatever what matched the Nth `\\(...\\)' in REGEXP.
617 `\\?' lets you edit the replacement text in the minibuffer
618 at the given position for each replacement.
620 In interactive calls, the replacement text may contain `\\,'
621 followed by a Lisp expression used as part of the replacement
622 text. Inside of that expression, `\\&' is a string denoting the
623 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
624 numeric values from `string-to-number', and `\\#' itself for
625 `replace-count', the number of replacements occurred so far.
627 If your Lisp expression is an identifier and the next letter in
628 the replacement string would be interpreted as part of it, you
629 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
630 for this particular case you may also enter `\\#' in the
631 replacement text directly.
633 When using those Lisp features interactively in the replacement
634 text, TO-STRING is actually made a list instead of a string.
635 Use \\[repeat-complex-command] after this command for details.
637 Use \\<minibuffer-local-map>\\[next-history-element] \
638 to pull the last incremental search regexp to the minibuffer
641 This function is usually the wrong thing to use in a Lisp program.
642 What you probably want is a loop like this:
643 (while (re-search-forward REGEXP nil t)
644 (replace-match TO-STRING nil nil))
645 which will run faster and will not set the mark or print anything."
646 (declare (interactive-only
647 "use `re-search-forward' and `replace-match' instead."))
650 (query-replace-read-args
652 (if current-prefix-arg
653 (if (eq current-prefix-arg '-) " backward" " word")
656 (if (use-region-p) " in region" ""))
658 (list (nth 0 common) (nth 1 common) (nth 2 common)
659 (if (use-region-p) (region-beginning))
660 (if (use-region-p) (region-end))
662 (perform-replace regexp to-string nil t delimited nil nil start end backward))
665 (defvar regexp-history nil
666 "History list for some commands that read regular expressions.
668 Maximum length of the history list is determined by the value
669 of `history-length', which see.")
671 (defvar occur-collect-regexp-history '("\\1")
672 "History of regexp for occur's collect operation")
674 (defcustom read-regexp-defaults-function nil
675 "Function that provides default regexp(s) for `read-regexp'.
676 This function should take no arguments and return one of: nil, a
677 regexp, or a list of regexps. Interactively, `read-regexp' uses
678 the return value of this function for its DEFAULT argument.
680 As an example, set this variable to `find-tag-default-as-regexp'
681 to default to the symbol at point.
683 To provide different default regexps for different commands,
684 the function that you set this to can check `this-command'."
686 (const :tag "No default regexp reading function" nil)
687 (const :tag "Latest regexp history" regexp-history-last)
688 (function-item :tag "Tag at point"
690 (function-item :tag "Tag at point as regexp"
691 find-tag-default-as-regexp)
692 (function-item :tag "Tag at point as symbol regexp"
693 find-tag-default-as-symbol-regexp)
694 (function :tag "Your choice of function"))
698 (defun read-regexp-suggestions ()
699 "Return a list of standard suggestions for `read-regexp'.
700 By default, the list includes the tag at point, the last isearch regexp,
701 the last isearch string, and the last replacement regexp. `read-regexp'
702 appends the list returned by this function to the end of values available
703 via \\<minibuffer-local-map>\\[next-history-element]."
705 (find-tag-default-as-regexp)
706 (find-tag-default-as-symbol-regexp)
707 (car regexp-search-ring)
708 (regexp-quote (or (car search-ring) ""))
709 (car (symbol-value query-replace-from-history-variable))))
711 (defun read-regexp (prompt &optional defaults history)
712 "Read and return a regular expression as a string.
713 Prompt with the string PROMPT. If PROMPT ends in \":\" (followed by
714 optional whitespace), use it as-is. Otherwise, add \": \" to the end,
715 possibly preceded by the default result (see below).
717 The optional argument DEFAULTS can be either: nil, a string, a list
718 of strings, or a symbol. We use DEFAULTS to construct the default
719 return value in case of empty input.
721 If DEFAULTS is a string, we use it as-is.
723 If DEFAULTS is a list of strings, the first element is the
724 default return value, but all the elements are accessible
725 using the history command \\<minibuffer-local-map>\\[next-history-element].
727 If DEFAULTS is a non-nil symbol, then if `read-regexp-defaults-function'
728 is non-nil, we use that in place of DEFAULTS in the following:
729 If DEFAULTS is the symbol `regexp-history-last', we use the first
730 element of HISTORY (if specified) or `regexp-history'.
731 If DEFAULTS is a function, we call it with no arguments and use
732 what it returns, which should be either nil, a string, or a list of strings.
734 We append the standard values from `read-regexp-suggestions' to DEFAULTS
737 If the first element of DEFAULTS is non-nil (and if PROMPT does not end
738 in \":\", followed by optional whitespace), we add it to the prompt.
740 The optional argument HISTORY is a symbol to use for the history list.
741 If nil, uses `regexp-history'."
743 (if (and defaults (symbolp defaults))
745 ((eq (or read-regexp-defaults-function defaults)
746 'regexp-history-last)
747 (car (symbol-value (or history 'regexp-history))))
748 ((functionp (or read-regexp-defaults-function defaults))
749 (funcall (or read-regexp-defaults-function defaults))))
751 (default (if (consp defaults) (car defaults) defaults))
752 (suggestions (if (listp defaults) defaults (list defaults)))
753 (suggestions (append suggestions (read-regexp-suggestions)))
754 (suggestions (delete-dups (delq nil (delete "" suggestions))))
755 ;; Do not automatically add default to the history for empty input.
756 (history-add-new-input nil)
757 (input (read-from-minibuffer
758 (cond ((string-match-p ":[ \t]*\\'" prompt)
760 ((and default (> (length default) 0))
761 (format "%s (default %s): " prompt
762 (query-replace-descr default)))
764 (format "%s: " prompt)))
765 nil nil nil (or history 'regexp-history) suggestions t)))
767 ;; Return the default value when the user enters empty input.
768 (prog1 (or default input)
770 (add-to-history (or history 'regexp-history) default)))
771 ;; Otherwise, add non-empty input to the history and return input.
773 (add-to-history (or history 'regexp-history) input)))))
776 (defalias 'delete-non-matching-lines 'keep-lines)
777 (defalias 'delete-matching-lines 'flush-lines)
778 (defalias 'count-matches 'how-many)
781 (defun keep-lines-read-args (prompt)
782 "Read arguments for `keep-lines' and friends.
783 Prompt for a regexp with PROMPT.
784 Value is a list, (REGEXP)."
785 (list (read-regexp prompt) nil nil t))
787 (defun keep-lines (regexp &optional rstart rend interactive)
788 "Delete all lines except those containing matches for REGEXP.
789 A match split across lines preserves all the lines it lies in.
790 When called from Lisp (and usually interactively as well, see below)
791 applies to all lines starting after point.
793 If REGEXP contains upper case characters (excluding those preceded by `\\')
794 and `search-upper-case' is non-nil, the matching is case-sensitive.
796 Second and third arg RSTART and REND specify the region to operate on.
797 This command operates on (the accessible part of) all lines whose
798 accessible part is entirely contained in the region determined by RSTART
799 and REND. (A newline ending a line counts as part of that line.)
801 Interactively, in Transient Mark mode when the mark is active, operate
802 on all lines whose accessible part is entirely contained in the region.
803 Otherwise, the command applies to all lines starting after point.
804 When calling this function from Lisp, you can pretend that it was
805 called interactively by passing a non-nil INTERACTIVE argument.
807 This function starts looking for the next match from the end of
808 the previous match. Hence, it ignores matches that overlap
809 a previously found match."
813 (barf-if-buffer-read-only)
814 (keep-lines-read-args "Keep lines containing match for regexp")))
817 (goto-char (min rstart rend))
821 (goto-char (max rstart rend))
822 (unless (or (bolp) (eobp))
825 (if (and interactive (use-region-p))
826 (setq rstart (region-beginning)
828 (goto-char (region-end))
829 (unless (or (bolp) (eobp))
833 rend (point-max-marker)))
836 (or (bolp) (forward-line 1))
837 (let ((start (point))
839 (if (and case-fold-search search-upper-case)
840 (isearch-no-upper-case-p regexp t)
842 (while (< (point) rend)
843 ;; Start is first char not preserved by previous match.
844 (if (not (re-search-forward regexp rend 'move))
845 (delete-region start rend)
846 (let ((end (save-excursion (goto-char (match-beginning 0))
849 ;; Now end is first char preserved by the new match.
851 (delete-region start end))))
853 (setq start (save-excursion (forward-line 1) (point)))
854 ;; If the match was empty, avoid matching again at same place.
855 (and (< (point) rend)
856 (= (match-beginning 0) (match-end 0))
858 (set-marker rend nil)
862 (defun flush-lines (regexp &optional rstart rend interactive)
863 "Delete lines containing matches for REGEXP.
864 When called from Lisp (and usually when called interactively as
865 well, see below), applies to the part of the buffer after point.
866 The line point is in is deleted if and only if it contains a
867 match for regexp starting after point.
869 If REGEXP contains upper case characters (excluding those preceded by `\\')
870 and `search-upper-case' is non-nil, the matching is case-sensitive.
872 Second and third arg RSTART and REND specify the region to operate on.
873 Lines partially contained in this region are deleted if and only if
874 they contain a match entirely contained in it.
876 Interactively, in Transient Mark mode when the mark is active, operate
877 on the contents of the region. Otherwise, operate from point to the
878 end of (the accessible portion of) the buffer. When calling this function
879 from Lisp, you can pretend that it was called interactively by passing
880 a non-nil INTERACTIVE argument.
882 If a match is split across lines, all the lines it lies in are deleted.
883 They are deleted _before_ looking for the next match. Hence, a match
884 starting on the same line at which another match ended is ignored."
888 (barf-if-buffer-read-only)
889 (keep-lines-read-args "Flush lines containing match for regexp")))
892 (goto-char (min rstart rend))
893 (setq rend (copy-marker (max rstart rend))))
894 (if (and interactive (use-region-p))
895 (setq rstart (region-beginning)
896 rend (copy-marker (region-end)))
898 rend (point-max-marker)))
900 (let ((case-fold-search
901 (if (and case-fold-search search-upper-case)
902 (isearch-no-upper-case-p regexp t)
905 (while (and (< (point) rend)
906 (re-search-forward regexp rend t))
907 (delete-region (save-excursion (goto-char (match-beginning 0))
910 (progn (forward-line 1) (point))))))
911 (set-marker rend nil)
915 (defun how-many (regexp &optional rstart rend interactive)
916 "Print and return number of matches for REGEXP following point.
917 When called from Lisp and INTERACTIVE is omitted or nil, just return
918 the number, do not print it; if INTERACTIVE is t, the function behaves
919 in all respects as if it had been called interactively.
921 If REGEXP contains upper case characters (excluding those preceded by `\\')
922 and `search-upper-case' is non-nil, the matching is case-sensitive.
924 Second and third arg RSTART and REND specify the region to operate on.
926 Interactively, in Transient Mark mode when the mark is active, operate
927 on the contents of the region. Otherwise, operate from point to the
928 end of (the accessible portion of) the buffer.
930 This function starts looking for the next match from the end of
931 the previous match. Hence, it ignores matches that overlap
932 a previously found match."
935 (keep-lines-read-args "How many matches for regexp"))
940 (goto-char (min rstart rend))
941 (setq rend (max rstart rend)))
943 (setq rend (point-max)))
944 (if (and interactive (use-region-p))
945 (setq rstart (region-beginning)
953 (if (and case-fold-search search-upper-case)
954 (isearch-no-upper-case-p regexp t)
956 (while (and (< (point) rend)
957 (progn (setq opoint (point))
958 (re-search-forward regexp rend t)))
959 (if (= opoint (point))
961 (setq count (1+ count))))
962 (when interactive (message "%d occurrence%s"
964 (if (= count 1) "" "s")))
968 (defvar occur-menu-map
969 (let ((map (make-sparse-keymap)))
970 (bindings--define-key map [next-error-follow-minor-mode]
971 '(menu-item "Auto Occurrence Display"
972 next-error-follow-minor-mode
973 :help "Display another occurrence when moving the cursor"
974 :button (:toggle . (and (boundp 'next-error-follow-minor-mode)
975 next-error-follow-minor-mode))))
976 (bindings--define-key map [separator-1] menu-bar-separator)
977 (bindings--define-key map [kill-this-buffer]
978 '(menu-item "Kill Occur Buffer" kill-this-buffer
979 :help "Kill the current *Occur* buffer"))
980 (bindings--define-key map [quit-window]
981 '(menu-item "Quit Occur Window" quit-window
982 :help "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
983 (bindings--define-key map [revert-buffer]
984 '(menu-item "Revert Occur Buffer" revert-buffer
985 :help "Replace the text in the *Occur* buffer with the results of rerunning occur"))
986 (bindings--define-key map [clone-buffer]
987 '(menu-item "Clone Occur Buffer" clone-buffer
988 :help "Create and return a twin copy of the current *Occur* buffer"))
989 (bindings--define-key map [occur-rename-buffer]
990 '(menu-item "Rename Occur Buffer" occur-rename-buffer
991 :help "Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
992 (bindings--define-key map [occur-edit-buffer]
993 '(menu-item "Edit Occur Buffer" occur-edit-mode
994 :help "Edit the *Occur* buffer and apply changes to the original buffers."))
995 (bindings--define-key map [separator-2] menu-bar-separator)
996 (bindings--define-key map [occur-mode-goto-occurrence-other-window]
997 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
998 :help "Go to the occurrence the current line describes, in another window"))
999 (bindings--define-key map [occur-mode-goto-occurrence]
1000 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
1001 :help "Go to the occurrence the current line describes"))
1002 (bindings--define-key map [occur-mode-display-occurrence]
1003 '(menu-item "Display Occurrence" occur-mode-display-occurrence
1004 :help "Display in another window the occurrence the current line describes"))
1005 (bindings--define-key map [occur-next]
1006 '(menu-item "Move to Next Match" occur-next
1007 :help "Move to the Nth (default 1) next match in an Occur mode buffer"))
1008 (bindings--define-key map [occur-prev]
1009 '(menu-item "Move to Previous Match" occur-prev
1010 :help "Move to the Nth (default 1) previous match in an Occur mode buffer"))
1012 "Menu keymap for `occur-mode'.")
1014 (defvar occur-mode-map
1015 (let ((map (make-sparse-keymap)))
1016 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
1017 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1018 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
1019 (define-key map "e" 'occur-edit-mode)
1020 (define-key map "\C-m" 'occur-mode-goto-occurrence)
1021 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
1022 (define-key map "\C-o" 'occur-mode-display-occurrence)
1023 (define-key map "\M-n" 'occur-next)
1024 (define-key map "\M-p" 'occur-prev)
1025 (define-key map "r" 'occur-rename-buffer)
1026 (define-key map "c" 'clone-buffer)
1027 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1028 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1030 "Keymap for `occur-mode'.")
1032 (defvar occur-revert-arguments nil
1033 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
1034 See `occur-revert-function'.")
1035 (make-variable-buffer-local 'occur-revert-arguments)
1036 (put 'occur-revert-arguments 'permanent-local t)
1038 (defcustom occur-mode-hook '(turn-on-font-lock)
1039 "Hook run when entering Occur mode."
1043 (defcustom occur-hook nil
1044 "Hook run by Occur when there are any matches."
1048 (defcustom occur-mode-find-occurrence-hook nil
1049 "Hook run by Occur after locating an occurrence.
1050 This will be called with the cursor position at the occurrence. An application
1051 for this is to reveal context in an outline-mode when the occurrence is hidden."
1055 (put 'occur-mode 'mode-class 'special)
1056 (define-derived-mode occur-mode special-mode "Occur"
1057 "Major mode for output from \\[occur].
1058 \\<occur-mode-map>Move point to one of the items in this buffer, then use
1059 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
1060 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
1063 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
1064 (setq next-error-function 'occur-next-error))
1069 (defvar occur-edit-mode-map
1070 (let ((map (make-sparse-keymap)))
1071 (set-keymap-parent map text-mode-map)
1072 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1073 (define-key map "\C-c\C-c" 'occur-cease-edit)
1074 (define-key map "\C-o" 'occur-mode-display-occurrence)
1075 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1076 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1078 "Keymap for `occur-edit-mode'.")
1080 (define-derived-mode occur-edit-mode occur-mode "Occur-Edit"
1081 "Major mode for editing *Occur* buffers.
1082 In this mode, changes to the *Occur* buffer are also applied to
1083 the originating buffer.
1085 To return to ordinary Occur mode, use \\[occur-cease-edit]."
1086 (setq buffer-read-only nil)
1087 (add-hook 'after-change-functions 'occur-after-change-function nil t)
1088 (message (substitute-command-keys
1089 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
1091 (defun occur-cease-edit ()
1092 "Switch from Occur Edit mode to Occur mode."
1094 (when (derived-mode-p 'occur-edit-mode)
1096 (message "Switching to Occur mode.")))
1098 (defun occur-after-change-function (beg end length)
1101 (let* ((line-beg (line-beginning-position))
1102 (m (get-text-property line-beg 'occur-target))
1103 (buf (marker-buffer m))
1105 (when (and (get-text-property line-beg 'occur-prefix)
1106 (not (get-text-property end 'occur-prefix)))
1108 ;; Apply occur-target property to inserted (e.g. yanked) text.
1109 (put-text-property beg end 'occur-target m)
1110 ;; Did we insert a newline? Occur Edit mode can't create new
1111 ;; Occur entries; just discard everything after the newline.
1113 (and (search-forward "\n" end t)
1114 (delete-region (1- (point)) end))))
1115 (let* ((line (- (line-number-at-pos)
1116 (line-number-at-pos (window-start))))
1117 (readonly (with-current-buffer buf buffer-read-only))
1118 (win (or (get-buffer-window buf)
1120 '(nil (inhibit-same-window . t)
1121 (inhibit-switch-frame . t)))))
1122 (line-end (line-end-position))
1123 (text (save-excursion
1124 (goto-char (next-single-property-change
1125 line-beg 'occur-prefix nil
1127 (setq col (- (point) line-beg))
1128 (buffer-substring-no-properties (point) line-end))))
1129 (with-selected-window win
1133 (message "Buffer `%s' is read only." buf)
1134 (delete-region (line-beginning-position) (line-end-position))
1136 (move-to-column col)))))))
1139 (defun occur-revert-function (_ignore1 _ignore2)
1140 "Handle `revert-buffer' for Occur mode buffers."
1141 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
1143 (defun occur-mode-find-occurrence ()
1144 (let ((pos (get-text-property (point) 'occur-target)))
1146 (error "No occurrence on this line"))
1147 (unless (buffer-live-p (marker-buffer pos))
1148 (error "Buffer for this occurrence was killed"))
1151 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
1152 (defun occur-mode-goto-occurrence (&optional event)
1153 "Go to the occurrence on the current line."
1154 (interactive (list last-nonmenu-event))
1157 ;; Actually `event-end' works correctly with a nil argument as
1158 ;; well, so we could dispense with this test, but let's not
1159 ;; rely on this undocumented behavior.
1160 (occur-mode-find-occurrence)
1161 (with-current-buffer (window-buffer (posn-window (event-end event)))
1163 (goto-char (posn-point (event-end event)))
1164 (occur-mode-find-occurrence))))))
1165 (pop-to-buffer (marker-buffer pos))
1167 (run-hooks 'occur-mode-find-occurrence-hook)))
1169 (defun occur-mode-goto-occurrence-other-window ()
1170 "Go to the occurrence the current line describes, in another window."
1172 (let ((pos (occur-mode-find-occurrence)))
1173 (switch-to-buffer-other-window (marker-buffer pos))
1175 (run-hooks 'occur-mode-find-occurrence-hook)))
1177 (defun occur-mode-display-occurrence ()
1178 "Display in another window the occurrence the current line describes."
1180 (let ((pos (occur-mode-find-occurrence))
1182 (setq window (display-buffer (marker-buffer pos) t))
1183 ;; This is the way to set point in the proper window.
1184 (save-selected-window
1185 (select-window window)
1187 (run-hooks 'occur-mode-find-occurrence-hook))))
1189 (defun occur-find-match (n search message)
1190 (if (not n) (setq n 1))
1193 (setq r (funcall search (point) 'occur-match))
1195 (get-text-property r 'occur-match)
1196 (setq r (funcall search r 'occur-match)))
1202 (defun occur-next (&optional n)
1203 "Move to the Nth (default 1) next match in an Occur mode buffer."
1205 (occur-find-match n #'next-single-property-change "No more matches"))
1207 (defun occur-prev (&optional n)
1208 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1210 (occur-find-match n #'previous-single-property-change "No earlier matches"))
1212 (defun occur-next-error (&optional argp reset)
1213 "Move to the Nth (default 1) next match in an Occur mode buffer.
1214 Compatibility function for \\[next-error] invocations."
1216 ;; we need to run occur-find-match from within the Occur buffer
1217 (with-current-buffer
1218 ;; Choose the buffer and make it current.
1219 (if (next-error-buffer-p (current-buffer))
1221 (next-error-find-buffer nil nil
1223 (eq major-mode 'occur-mode))))
1225 (goto-char (cond (reset (point-min))
1226 ((< argp 0) (line-beginning-position))
1227 ((> argp 0) (line-end-position))
1232 #'previous-single-property-change
1233 #'next-single-property-change)
1235 ;; In case the *Occur* buffer is visible in a nonselected window.
1236 (let ((win (get-buffer-window (current-buffer) t)))
1237 (if win (set-window-point win (point))))
1238 (occur-mode-goto-occurrence)))
1241 '((((class color) (min-colors 88) (background light))
1242 :background "yellow1")
1243 (((class color) (min-colors 88) (background dark))
1244 :background "RoyalBlue3")
1245 (((class color) (min-colors 8) (background light))
1246 :background "yellow" :foreground "black")
1247 (((class color) (min-colors 8) (background dark))
1248 :background "blue" :foreground "white")
1249 (((type tty) (class mono))
1251 (t :background "gray"))
1252 "Face used to highlight matches permanently."
1256 (defcustom list-matching-lines-default-context-lines 0
1257 "Default number of context lines included around `list-matching-lines' matches.
1258 A negative number means to include that many lines before the match.
1259 A positive number means to include that many lines both before and after."
1263 (defalias 'list-matching-lines 'occur)
1265 (defcustom list-matching-lines-face 'match
1266 "Face used by \\[list-matching-lines] to show the text that matches.
1267 If the value is nil, don't highlight the matching portions specially."
1271 (defcustom list-matching-lines-buffer-name-face 'underline
1272 "Face used by \\[list-matching-lines] to show the names of buffers.
1273 If the value is nil, don't highlight the buffer names specially."
1277 (defcustom list-matching-lines-prefix-face 'shadow
1278 "Face used by \\[list-matching-lines] to show the prefix column.
1279 If the face doesn't differ from the default face,
1280 don't highlight the prefix with line numbers specially."
1285 (defcustom occur-excluded-properties
1286 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1287 yank-handler follow-link)
1288 "Text properties to discard when copying lines to the *Occur* buffer.
1289 The value should be a list of text properties to discard or t,
1290 which means to discard all text properties."
1291 :type '(choice (const :tag "All" t) (repeat symbol))
1295 (defun occur-read-primary-args ()
1296 (let* ((perform-collect (consp current-prefix-arg))
1297 (regexp (read-regexp (if perform-collect
1298 "Collect strings matching regexp"
1299 "List lines matching regexp")
1300 'regexp-history-last)))
1303 ;; Perform collect operation
1304 (if (zerop (regexp-opt-depth regexp))
1305 ;; No subexpression so collect the entire match.
1307 ;; Get the regexp for collection pattern.
1308 (let ((default (car occur-collect-regexp-history)))
1310 (format "Regexp to collect (default %s): " default)
1311 default 'occur-collect-regexp-history)))
1312 ;; Otherwise normal occur takes numerical prefix argument.
1313 (when current-prefix-arg
1314 (prefix-numeric-value current-prefix-arg))))))
1316 (defun occur-rename-buffer (&optional unique-p interactive-p)
1317 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1318 Here `original-buffer-name' is the buffer name where Occur was originally run.
1319 When given the prefix argument, or called non-interactively, the renaming
1320 will not clobber the existing buffer(s) of that name, but use
1321 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1322 if you always want a separate *Occur* buffer for each buffer where you
1324 (interactive "P\np")
1325 (with-current-buffer
1326 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1327 (rename-buffer (concat "*Occur: "
1328 (mapconcat #'buffer-name
1329 (car (cddr occur-revert-arguments)) "/")
1331 (or unique-p (not interactive-p)))))
1333 (defun occur (regexp &optional nlines)
1334 "Show all lines in the current buffer containing a match for REGEXP.
1335 If a match spreads across multiple lines, all those lines are shown.
1337 Each line is displayed with NLINES lines before and after, or -NLINES
1338 before if NLINES is negative.
1339 NLINES defaults to `list-matching-lines-default-context-lines'.
1340 Interactively it is the prefix arg.
1342 The lines are shown in a buffer named `*Occur*'.
1343 It serves as a menu to find any of the occurrences in this buffer.
1344 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1346 If REGEXP contains upper case characters (excluding those preceded by `\\')
1347 and `search-upper-case' is non-nil, the matching is case-sensitive.
1349 When NLINES is a string or when the function is called
1350 interactively with prefix argument without a number (`C-u' alone
1351 as prefix) the matching strings are collected into the `*Occur*'
1352 buffer by using NLINES as a replacement regexp. NLINES may
1353 contain \\& and \\N which convention follows `replace-match'.
1354 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1355 \"\\1\" for NLINES collects all the function names in a lisp
1356 program. When there is no parenthesized subexpressions in REGEXP
1357 the entire match is collected. In any case the searched buffer
1359 (interactive (occur-read-primary-args))
1360 (occur-1 regexp nlines (list (current-buffer))))
1362 (defvar ido-ignore-item-temp-list)
1364 (defun multi-occur (bufs regexp &optional nlines)
1365 "Show all lines in buffers BUFS containing a match for REGEXP.
1366 This function acts on multiple buffers; otherwise, it is exactly like
1367 `occur'. When you invoke this command interactively, you must specify
1368 the buffer names that you want, one by one.
1369 See also `multi-occur-in-matching-buffers'."
1372 (let* ((bufs (list (read-buffer "First buffer to search: "
1373 (current-buffer) t)))
1375 (ido-ignore-item-temp-list bufs))
1376 (while (not (string-equal
1377 (setq buf (read-buffer
1378 (if (eq read-buffer-function #'ido-read-buffer)
1379 "Next buffer to search (C-j to end): "
1380 "Next buffer to search (RET to end): ")
1383 (add-to-list 'bufs buf)
1384 (setq ido-ignore-item-temp-list bufs))
1385 (nreverse (mapcar #'get-buffer bufs)))
1386 (occur-read-primary-args)))
1387 (occur-1 regexp nlines bufs))
1389 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1390 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1391 Normally BUFREGEXP matches against each buffer's visited file name,
1392 but if you specify a prefix argument, it matches against the buffer name.
1393 See also `multi-occur'."
1396 (let* ((default (car regexp-history))
1399 (if current-prefix-arg
1400 "List lines in buffers whose names match regexp: "
1401 "List lines in buffers whose filenames match regexp: "))))
1402 (if (equal input "")
1405 (occur-read-primary-args)))
1409 (mapcar (lambda (buf)
1411 (string-match bufregexp
1413 (and (buffer-file-name buf)
1414 (string-match bufregexp
1415 (buffer-file-name buf))))
1419 (defun occur-1 (regexp nlines bufs &optional buf-name)
1420 (unless (and regexp (not (equal regexp "")))
1421 (error "Occur doesn't work with the empty regexp"))
1423 (setq buf-name "*Occur*"))
1425 (active-bufs (delq nil (mapcar #'(lambda (buf)
1426 (when (buffer-live-p buf) buf))
1428 ;; Handle the case where one of the buffers we're searching is the
1429 ;; output buffer. Just rename it.
1430 (when (member buf-name (mapcar 'buffer-name active-bufs))
1431 (with-current-buffer (get-buffer buf-name)
1434 ;; Now find or create the output buffer.
1435 ;; If we just renamed that buffer, we will make a new one here.
1436 (setq occur-buf (get-buffer-create buf-name))
1438 (with-current-buffer occur-buf
1439 (if (stringp nlines)
1440 (fundamental-mode) ;; This is for collect operation.
1442 (let ((inhibit-read-only t)
1443 ;; Don't generate undo entries for creation of the initial contents.
1444 (buffer-undo-list t))
1447 (if (stringp nlines)
1448 ;; Treat nlines as a regexp to collect.
1449 (let ((bufs active-bufs)
1452 (with-current-buffer (car bufs)
1454 (goto-char (point-min))
1455 (while (re-search-forward regexp nil t)
1456 ;; Insert the replacement regexp.
1457 (let ((str (match-substitute-replacement nlines)))
1459 (with-current-buffer occur-buf
1461 (setq count (1+ count))
1462 (or (zerop (current-column))
1463 (insert "\n"))))))))
1464 (setq bufs (cdr bufs)))
1466 ;; Perform normal occur.
1468 regexp active-bufs occur-buf
1469 (or nlines list-matching-lines-default-context-lines)
1470 (if (and case-fold-search search-upper-case)
1471 (isearch-no-upper-case-p regexp t)
1473 list-matching-lines-buffer-name-face
1474 (if (face-differs-from-default-p list-matching-lines-prefix-face)
1475 list-matching-lines-prefix-face)
1476 list-matching-lines-face
1477 (not (eq occur-excluded-properties t))))))
1478 (let* ((bufcount (length active-bufs))
1479 (diff (- (length bufs) bufcount)))
1480 (message "Searched %d buffer%s%s; %s match%s%s"
1481 bufcount (if (= bufcount 1) "" "s")
1482 (if (zerop diff) "" (format " (%d killed)" diff))
1483 (if (zerop count) "no" (format "%d" count))
1484 (if (= count 1) "" "es")
1485 ;; Don't display regexp if with remaining text
1486 ;; it is longer than window-width.
1487 (if (> (+ (length regexp) 42) (window-width))
1489 " for `%s'" (query-replace-descr regexp)))))
1490 (setq occur-revert-arguments (list regexp nlines bufs))
1492 (kill-buffer occur-buf)
1493 (display-buffer occur-buf)
1494 (setq next-error-last-buffer occur-buf)
1495 (setq buffer-read-only t)
1496 (set-buffer-modified-p nil)
1497 (run-hooks 'occur-hook)))))))
1499 (defun occur-engine (regexp buffers out-buf nlines case-fold
1500 title-face prefix-face match-face keep-props)
1501 (with-current-buffer out-buf
1502 (let ((global-lines 0) ;; total count of matching lines
1503 (global-matches 0) ;; total count of matches
1505 (case-fold-search case-fold))
1506 ;; Map over all the buffers
1507 (dolist (buf buffers)
1508 (when (buffer-live-p buf)
1509 (let ((lines 0) ;; count of matching lines
1510 (matches 0) ;; count of matches
1511 (curr-line 1) ;; line count
1512 (prev-line nil) ;; line number of prev match endpt
1513 (prev-after-lines nil) ;; context lines of prev match
1521 (inhibit-field-text-motion t)
1522 (headerpt (with-current-buffer out-buf (point))))
1523 (with-current-buffer buf
1525 ;; Set CODING only if the current buffer locally
1526 ;; binds buffer-file-coding-system.
1527 (not (local-variable-p 'buffer-file-coding-system))
1528 (setq coding buffer-file-coding-system))
1530 (goto-char (point-min)) ;; begin searching in the buffer
1532 (setq origpt (point))
1533 (when (setq endpt (re-search-forward regexp nil t))
1534 (setq lines (1+ lines)) ;; increment matching lines count
1535 (setq matchbeg (match-beginning 0))
1536 ;; Get beginning of first match line and end of the last.
1538 (goto-char matchbeg)
1539 (setq begpt (line-beginning-position))
1541 (setq endpt (line-end-position)))
1542 ;; Sum line numbers up to the first match line.
1543 (setq curr-line (+ curr-line (count-lines origpt begpt)))
1544 (setq marker (make-marker))
1545 (set-marker marker matchbeg)
1546 (setq curstring (occur-engine-line begpt endpt keep-props))
1547 ;; Highlight the matches
1548 (let ((len (length curstring))
1550 (while (and (< start len)
1551 (string-match regexp curstring start))
1552 (setq matches (1+ matches))
1553 (add-text-properties
1554 (match-beginning 0) (match-end 0)
1555 '(occur-match t) curstring)
1557 ;; Add `match-face' to faces copied from the buffer.
1558 (add-face-text-property
1559 (match-beginning 0) (match-end 0)
1560 match-face nil curstring))
1561 ;; Avoid infloop (Bug#7593).
1562 (let ((end (match-end 0)))
1563 (setq start (if (= start end) (1+ start) end)))))
1564 ;; Generate the string to insert for this match
1565 (let* ((match-prefix
1566 ;; Using 7 digits aligns tabs properly.
1567 (apply #'propertize (format "%7d:" curr-line)
1570 `(font-lock-face ,prefix-face))
1571 `(occur-prefix t mouse-face (highlight)
1572 ;; Allow insertion of text at
1573 ;; the end of the prefix (for
1574 ;; Occur Edit mode).
1575 front-sticky t rear-nonsticky t
1576 occur-target ,marker follow-link t
1577 help-echo "mouse-2: go to this occurrence"))))
1579 ;; We don't put `mouse-face' on the newline,
1580 ;; because that loses. And don't put it
1581 ;; on context lines to reduce flicker.
1582 (propertize curstring 'mouse-face (list 'highlight)
1583 'occur-target marker
1586 "mouse-2: go to this occurrence"))
1590 ;; Add non-numeric prefix to all non-first lines
1591 ;; of multi-line matches.
1592 (replace-regexp-in-string
1595 (propertize "\n :" 'font-lock-face prefix-face)
1598 ;; Add marker at eol, but no mouse props.
1599 (propertize "\n" 'occur-target marker)))
1602 ;; The simple display style
1604 ;; The complex multi-line display style.
1605 (setq ret (occur-context-lines
1606 out-line nlines keep-props begpt endpt
1607 curr-line prev-line prev-after-lines
1609 ;; Set first elem of the returned list to `data',
1610 ;; and the second elem to `prev-after-lines'.
1611 (setq prev-after-lines (nth 1 ret))
1613 ;; Actually insert the match display data
1614 (with-current-buffer out-buf
1619 ;; Sum line numbers between first and last match lines.
1620 (setq curr-line (+ curr-line (count-lines begpt endpt)
1621 ;; Add 1 for empty last match line since
1622 ;; count-lines returns 1 line less.
1623 (if (and (bolp) (eolp)) 1 0)))
1624 ;; On to the next match...
1626 (goto-char (point-max)))
1627 (setq prev-line (1- curr-line)))
1628 ;; Flush remaining context after-lines.
1629 (when prev-after-lines
1630 (with-current-buffer out-buf
1631 (insert (apply #'concat (occur-engine-add-prefix
1632 prev-after-lines prefix-face)))))))
1633 (when (not (zerop lines)) ;; is the count zero?
1634 (setq global-lines (+ global-lines lines)
1635 global-matches (+ global-matches matches))
1636 (with-current-buffer out-buf
1637 (goto-char headerpt)
1641 (format "%d match%s%s%s in buffer: %s\n"
1642 matches (if (= matches 1) "" "es")
1643 ;; Don't display the same number of lines
1644 ;; and matches in case of 1 match per line.
1645 (if (= lines matches)
1646 "" (format " in %d line%s"
1647 lines (if (= lines 1) "" "s")))
1648 ;; Don't display regexp for multi-buffer.
1649 (if (> (length buffers) 1)
1650 "" (format " for \"%s\""
1651 (query-replace-descr regexp)))
1655 (add-text-properties beg end `(occur-title ,buf))
1657 (add-face-text-property beg end title-face)))
1658 (goto-char (point-min)))))))
1659 ;; Display total match count and regexp for multi-buffer.
1660 (when (and (not (zerop global-lines)) (> (length buffers) 1))
1661 (goto-char (point-min))
1664 (insert (format "%d match%s%s total for \"%s\":\n"
1665 global-matches (if (= global-matches 1) "" "es")
1666 ;; Don't display the same number of lines
1667 ;; and matches in case of 1 match per line.
1668 (if (= global-lines global-matches)
1669 "" (format " in %d line%s"
1670 global-lines (if (= global-lines 1) "" "s")))
1671 (query-replace-descr regexp)))
1674 (add-face-text-property beg end title-face)))
1675 (goto-char (point-min)))
1677 ;; CODING is buffer-file-coding-system of the first buffer
1678 ;; that locally binds it. Let's use it also for the output
1680 (set-buffer-file-coding-system coding))
1681 ;; Return the number of matches
1684 (defun occur-engine-line (beg end &optional keep-props)
1685 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1686 (text-property-not-all beg end 'fontified t))
1687 (if (fboundp 'jit-lock-fontify-now)
1688 (jit-lock-fontify-now beg end)))
1689 (if (and keep-props (not (eq occur-excluded-properties t)))
1690 (let ((str (buffer-substring beg end)))
1691 (remove-list-of-text-properties
1692 0 (length str) occur-excluded-properties str)
1694 (buffer-substring-no-properties beg end)))
1696 (defun occur-engine-add-prefix (lines &optional prefix-face)
1699 (concat (if prefix-face
1700 (propertize " :" 'font-lock-face prefix-face)
1705 (defun occur-accumulate-lines (count &optional keep-props pt)
1709 (let ((forwardp (> count 0))
1710 result beg end moved)
1711 (while (not (or (zerop count)
1714 (and (bobp) (not moved)))))
1715 (setq count (+ count (if forwardp -1 1)))
1716 (setq beg (line-beginning-position)
1717 end (line-end-position))
1718 (push (occur-engine-line beg end keep-props) result)
1719 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1720 (nreverse result))))
1722 ;; Generate context display for occur.
1723 ;; OUT-LINE is the line where the match is.
1724 ;; NLINES and KEEP-PROPS are args to occur-engine.
1725 ;; CURR-LINE is line count of the current match,
1726 ;; PREV-LINE is line count of the previous match,
1727 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1728 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1729 ;; then concatenate them all together.
1730 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1731 curr-line prev-line prev-after-lines
1732 &optional prefix-face)
1733 ;; Find after- and before-context lines of the current match.
1735 (nreverse (cdr (occur-accumulate-lines
1736 (- (1+ (abs nlines))) keep-props begpt))))
1738 (cdr (occur-accumulate-lines
1739 (1+ nlines) keep-props endpt)))
1742 ;; Combine after-lines of the previous match
1743 ;; with before-lines of the current match.
1745 (when prev-after-lines
1746 ;; Don't overlap prev after-lines with current before-lines.
1747 (if (>= (+ prev-line (length prev-after-lines))
1748 (- curr-line (length before-lines)))
1749 (setq prev-after-lines
1750 (butlast prev-after-lines
1751 (- (length prev-after-lines)
1752 (- curr-line prev-line (length before-lines) 1))))
1753 ;; Separate non-overlapping context lines with a dashed line.
1754 (setq separator "-------\n")))
1757 ;; Don't overlap current before-lines with previous match line.
1758 (if (<= (- curr-line (length before-lines))
1761 (nthcdr (- (length before-lines)
1762 (- curr-line prev-line 1))
1764 ;; Separate non-overlapping before-context lines.
1765 (unless (> nlines 0)
1766 (setq separator "-------\n"))))
1769 ;; Return a list where the first element is the output line.
1772 (if prev-after-lines
1773 (occur-engine-add-prefix prev-after-lines prefix-face))
1775 (list (if prefix-face
1776 (propertize separator 'font-lock-face prefix-face)
1778 (occur-engine-add-prefix before-lines prefix-face)
1780 ;; And the second element is the list of context after-lines.
1781 (if (> nlines 0) after-lines))))
1784 ;; It would be nice to use \\[...], but there is no reasonable way
1785 ;; to make that display both SPC and Y.
1786 (defconst query-replace-help
1787 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1788 RET or `q' to exit, Period to replace one match and exit,
1789 Comma to replace but not move point immediately,
1790 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1791 C-w to delete match and recursive edit,
1792 C-l to clear the screen, redisplay, and offer same replacement again,
1793 ! to replace all remaining matches in this buffer with no more questions,
1794 ^ to move point back to previous match,
1795 E to edit the replacement string.
1796 In multi-buffer replacements type `Y' to replace all remaining
1797 matches in all remaining buffers with no more questions,
1798 `N' to skip to the next buffer without replacing remaining matches
1799 in the current buffer."
1800 "Help message while in `query-replace'.")
1802 (defvar query-replace-map
1803 (let ((map (make-sparse-keymap)))
1804 (define-key map " " 'act)
1805 (define-key map "\d" 'skip)
1806 (define-key map [delete] 'skip)
1807 (define-key map [backspace] 'skip)
1808 (define-key map "y" 'act)
1809 (define-key map "n" 'skip)
1810 (define-key map "Y" 'act)
1811 (define-key map "N" 'skip)
1812 (define-key map "e" 'edit-replacement)
1813 (define-key map "E" 'edit-replacement)
1814 (define-key map "," 'act-and-show)
1815 (define-key map "q" 'exit)
1816 (define-key map "\r" 'exit)
1817 (define-key map [return] 'exit)
1818 (define-key map "." 'act-and-exit)
1819 (define-key map "\C-r" 'edit)
1820 (define-key map "\C-w" 'delete-and-edit)
1821 (define-key map "\C-l" 'recenter)
1822 (define-key map "!" 'automatic)
1823 (define-key map "^" 'backup)
1824 (define-key map "\C-h" 'help)
1825 (define-key map [f1] 'help)
1826 (define-key map [help] 'help)
1827 (define-key map "?" 'help)
1828 (define-key map "\C-g" 'quit)
1829 (define-key map "\C-]" 'quit)
1830 (define-key map "\C-v" 'scroll-up)
1831 (define-key map "\M-v" 'scroll-down)
1832 (define-key map [next] 'scroll-up)
1833 (define-key map [prior] 'scroll-down)
1834 (define-key map [?\C-\M-v] 'scroll-other-window)
1835 (define-key map [M-next] 'scroll-other-window)
1836 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1837 (define-key map [M-prior] 'scroll-other-window-down)
1838 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1839 ;; should check for ESC specially.
1840 ;; (define-key map "\e" 'exit-prefix)
1841 (define-key map [escape] 'exit-prefix)
1843 "Keymap of responses to questions posed by commands like `query-replace'.
1844 The \"bindings\" in this map are not commands; they are answers.
1845 The valid answers include `act', `skip', `act-and-show',
1846 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1847 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1848 `edit', `edit-replacement', `delete-and-edit', `automatic',
1849 `backup', `quit', and `help'.
1851 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1853 (defvar multi-query-replace-map
1854 (let ((map (make-sparse-keymap)))
1855 (set-keymap-parent map query-replace-map)
1856 (define-key map "Y" 'automatic-all)
1857 (define-key map "N" 'exit-current)
1859 "Keymap that defines additional bindings for multi-buffer replacements.
1860 It extends its parent map `query-replace-map' with new bindings to
1861 operate on a set of buffers/files. The difference with its parent map
1862 is the additional answers `automatic-all' to replace all remaining
1863 matches in all remaining buffers with no more questions, and
1864 `exit-current' to skip remaining matches in the current buffer
1865 and to continue with the next buffer in the sequence.")
1867 (defun replace-match-string-symbols (n)
1868 "Process a list (and any sub-lists), expanding certain symbols.
1870 N (match-string N) (where N is a string of digits)
1871 #N (string-to-number (match-string N))
1873 #& (string-to-number (match-string 0))
1876 Note that these symbols must be preceded by a backslash in order to
1877 type them using Lisp syntax."
1881 (replace-match-string-symbols (car n))) ;Process sub-list
1883 (let ((name (symbol-name (car n))))
1885 ((string-match "^[0-9]+$" name)
1886 (setcar n (list 'match-string (string-to-number name))))
1887 ((string-match "^#[0-9]+$" name)
1888 (setcar n (list 'string-to-number
1890 (string-to-number (substring name 1))))))
1892 (setcar n '(match-string 0)))
1893 ((string= "#&" name)
1894 (setcar n '(string-to-number (match-string 0))))
1896 (setcar n 'replace-count))))))
1899 (defun replace-eval-replacement (expression count)
1900 (let* ((replace-count count)
1906 (error "Error evaluating replacement expression: %S" err)))))
1907 (if (stringp replacement)
1909 (prin1-to-string replacement t))))
1911 (defun replace-quote (replacement)
1912 "Quote a replacement string.
1913 This just doubles all backslashes in REPLACEMENT and
1914 returns the resulting string. If REPLACEMENT is not
1915 a string, it is first passed through `prin1-to-string'
1916 with the `noescape' argument set.
1918 `match-data' is preserved across the call."
1920 (replace-regexp-in-string "\\\\" "\\\\"
1921 (if (stringp replacement)
1923 (prin1-to-string replacement t))
1926 (defun replace-loop-through-replacements (data count)
1927 ;; DATA is a vector containing the following values:
1928 ;; 0 next-rotate-count
1930 ;; 2 next-replacement
1932 (if (= (aref data 0) count)
1934 (aset data 0 (+ count (aref data 1)))
1935 (let ((next (cdr (aref data 2))))
1936 (aset data 2 (if (consp next) next (aref data 3))))))
1937 (car (aref data 2)))
1939 (defun replace-match-data (integers reuse &optional new)
1940 "Like `match-data', but markers in REUSE get invalidated.
1941 If NEW is non-nil, it is set and returned instead of fresh data,
1942 but coerced to the correct value of INTEGERS."
1945 (set-match-data new)
1947 (eq (null integers) (markerp (car reuse)))
1949 (match-data integers reuse t)))
1951 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data backward)
1952 "Make a replacement with `replace-match', editing `\\?'.
1953 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
1954 After possibly editing it (if `\\?' is present), NEWTEXT is also
1955 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
1956 is made (to save time). MATCH-DATA is used for the replacement.
1957 In case editing is done, it is changed to use markers.
1959 The return value is non-nil if there has been no `\\?' or NOEDIT was
1960 passed in. If LITERAL is set, no checking is done, anyway."
1961 (unless (or literal noedit)
1963 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1966 (read-string "Edit replacement string: "
1969 (replace-match "" t t newtext 3)
1970 (1+ (match-beginning 3)))
1973 nil match-data match-data))))
1975 (set-match-data match-data)
1976 (replace-match newtext fixedcase literal)
1977 ;; `replace-match' leaves point at the end of the replacement text,
1978 ;; so move point to the beginning when replacing backward.
1979 (when backward (goto-char (nth 0 match-data)))
1982 (defvar replace-search-function nil
1983 "Function to use when searching for strings to replace.
1984 It is used by `query-replace' and `replace-string', and is called
1985 with three arguments, as if it were `search-forward'.")
1987 (defvar replace-re-search-function nil
1988 "Function to use when searching for regexps to replace.
1989 It is used by `query-replace-regexp', `replace-regexp',
1990 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1991 It is called with three arguments, as if it were
1992 `re-search-forward'.")
1994 (defun replace-search (search-string limit regexp-flag delimited-flag
1995 case-fold-search backward)
1996 "Search for the next occurrence of SEARCH-STRING to replace."
1997 ;; Let-bind global isearch-* variables to values used
1998 ;; to search the next replacement. These let-bindings
1999 ;; should be effective both at the time of calling
2000 ;; `isearch-search-fun-default' and also at the
2001 ;; time of funcalling `search-function'.
2002 ;; These isearch-* bindings can't be placed higher
2003 ;; outside of this function because then another I-search
2004 ;; used after `recursive-edit' might override them.
2005 (let* ((isearch-regexp regexp-flag)
2006 (isearch-regexp-function (or delimited-flag
2007 (and replace-character-fold
2009 #'character-fold-to-regexp)))
2010 (isearch-lax-whitespace
2011 replace-lax-whitespace)
2012 (isearch-regexp-lax-whitespace
2013 replace-regexp-lax-whitespace)
2014 (isearch-case-fold-search case-fold-search)
2015 (isearch-adjusted nil)
2016 (isearch-nonincremental t) ; don't use lax word mode
2017 (isearch-forward (not backward))
2020 replace-re-search-function
2021 replace-search-function)
2022 (isearch-search-fun-default))))
2023 (funcall search-function search-string limit t)))
2025 (defvar replace-overlay nil)
2027 (defun replace-highlight (match-beg match-end range-beg range-end
2028 search-string regexp-flag delimited-flag
2029 case-fold-search backward)
2030 (if query-replace-highlight
2032 (move-overlay replace-overlay match-beg match-end (current-buffer))
2033 (setq replace-overlay (make-overlay match-beg match-end))
2034 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2035 (overlay-put replace-overlay 'face 'query-replace)))
2036 (if query-replace-lazy-highlight
2037 (let ((isearch-string search-string)
2038 (isearch-regexp regexp-flag)
2039 (isearch-regexp-function delimited-flag)
2040 (isearch-lax-whitespace
2041 replace-lax-whitespace)
2042 (isearch-regexp-lax-whitespace
2043 replace-regexp-lax-whitespace)
2044 (isearch-case-fold-search case-fold-search)
2045 (isearch-forward (not backward))
2046 (isearch-other-end match-beg)
2047 (isearch-error nil))
2048 (isearch-lazy-highlight-new-loop range-beg range-end))))
2050 (defun replace-dehighlight ()
2051 (when replace-overlay
2052 (delete-overlay replace-overlay))
2053 (when query-replace-lazy-highlight
2054 (lazy-highlight-cleanup lazy-highlight-cleanup)
2055 (setq isearch-lazy-highlight-last-string nil))
2056 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2057 (isearch-clean-overlays))
2059 (defun perform-replace (from-string replacements
2060 query-flag regexp-flag delimited-flag
2061 &optional repeat-count map start end backward region-noncontiguous-p)
2062 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2063 Don't use this in your own program unless you want to query and set the mark
2064 just as `query-replace' does. Instead, write a simple loop like this:
2066 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2067 (replace-match \"foobar\" nil nil))
2069 which will run faster and probably do exactly what you want. Please
2070 see the documentation of `replace-match' to find out how to simulate
2073 This function returns nil if and only if there were no matches to
2074 make, or the user didn't cancel the call.
2076 REPLACEMENTS is either a string, a list of strings, or a cons cell
2077 containing a function and its first argument. The function is
2078 called to generate each replacement like this:
2079 (funcall (car replacements) (cdr replacements) replace-count)
2080 It must return a string."
2081 (or map (setq map query-replace-map))
2082 (and query-flag minibuffer-auto-raise
2083 (raise-frame (window-frame (minibuffer-window))))
2084 (let* ((case-fold-search
2085 (if (and case-fold-search search-upper-case)
2086 (isearch-no-upper-case-p from-string regexp-flag)
2088 (nocasify (not (and case-replace case-fold-search)))
2089 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2090 (search-string from-string)
2091 (real-match-data nil) ; The match data for the current match.
2092 (next-replacement nil)
2093 ;; This is non-nil if we know there is nothing for the user
2094 ;; to edit in the replacement.
2099 (skip-read-only-count 0)
2100 (skip-filtered-count 0)
2101 (skip-invisible-count 0)
2102 (nonempty-match nil)
2104 (recenter-last-op nil) ; Start cycling order with initial position.
2106 ;; If non-nil, it is marker saying where in the buffer to stop.
2108 ;; Use local binding in add-function below.
2109 (isearch-filter-predicate isearch-filter-predicate)
2112 ;; Data for the next match. If a cons, it has the same format as
2113 ;; (match-data); otherwise it is t if a match is possible at point.
2119 (substitute-command-keys
2120 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2121 minibuffer-prompt-properties))))
2123 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
2124 (when region-noncontiguous-p
2126 (mapcar (lambda (position)
2127 (cons (copy-marker (car position))
2128 (copy-marker (cdr position))))
2129 (funcall region-extract-function 'bounds)))
2130 (add-function :after-while isearch-filter-predicate
2135 (>= start (car bounds))
2136 (<= start (cdr bounds))
2137 (>= end (car bounds))
2138 (<= end (cdr bounds))))
2141 ;; If region is active, in Transient Mark mode, operate on region.
2144 (setq limit (copy-marker (min start end)))
2145 (goto-char (max start end))
2148 (setq limit (copy-marker (max start end)))
2149 (goto-char (min start end))
2152 ;; If last typed key in previous call of multi-buffer perform-replace
2153 ;; was `automatic-all', don't ask more questions in next files
2154 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2155 (setq query-flag nil multi-buffer t))
2158 ((stringp replacements)
2159 (setq next-replacement replacements
2161 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2162 (or repeat-count (setq repeat-count 1))
2163 (setq replacements (cons 'replace-loop-through-replacements
2164 (vector repeat-count repeat-count
2165 replacements replacements)))))
2167 (when query-replace-lazy-highlight
2168 (setq isearch-lazy-highlight-last-string nil))
2173 ;; Loop finding occurrences that perhaps should be replaced.
2174 (while (and keep-going
2176 (not (or (bobp) (and limit (<= (point) limit))))
2177 (not (or (eobp) (and limit (>= (point) limit)))))
2178 ;; Use the next match if it is already known;
2179 ;; otherwise, search for a match after moving forward
2180 ;; one char if progress is required.
2181 (setq real-match-data
2182 (cond ((consp match-again)
2183 (goto-char (if backward
2185 (nth 1 match-again)))
2187 t real-match-data match-again))
2188 ;; MATCH-AGAIN non-nil means accept an
2192 (replace-search search-string limit
2193 regexp-flag delimited-flag
2194 case-fold-search backward)
2195 ;; For speed, use only integers and
2196 ;; reuse the list used last time.
2197 (replace-match-data t real-match-data)))
2199 (> (1- (point)) (point-min))
2200 (< (1+ (point)) (point-max)))
2203 (> (1- (point)) limit)
2204 (< (1+ (point)) limit))))
2205 ;; If not accepting adjacent matches,
2206 ;; move one char to the right before
2207 ;; searching again. Undo the motion
2208 ;; if the search fails.
2209 (let ((opoint (point)))
2210 (forward-char (if backward -1 1))
2211 (if (replace-search search-string limit
2212 regexp-flag delimited-flag
2213 case-fold-search backward)
2219 ;; Record whether the match is nonempty, to avoid an infinite loop
2220 ;; repeatedly matching the same empty string.
2221 (setq nonempty-match
2222 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2224 ;; If the match is empty, record that the next one can't be
2227 ;; Otherwise, if matching a regular expression, do the next
2228 ;; match now, since the replacement for this match may
2229 ;; affect whether the next match is adjacent to this one.
2230 ;; If that match is empty, don't use it.
2233 (or (not regexp-flag)
2235 (looking-back search-string)
2236 (looking-at search-string))
2237 (let ((match (match-data)))
2238 (and (/= (nth 0 match) (nth 1 match))
2242 ;; Optionally ignore matches that have a read-only property.
2243 ((not (or (not query-replace-skip-read-only)
2244 (not (text-property-not-all
2245 (nth 0 real-match-data) (nth 1 real-match-data)
2247 (setq skip-read-only-count (1+ skip-read-only-count)))
2248 ;; Optionally filter out matches.
2249 ((not (funcall isearch-filter-predicate
2250 (nth 0 real-match-data) (nth 1 real-match-data)))
2251 (setq skip-filtered-count (1+ skip-filtered-count)))
2252 ;; Optionally ignore invisible matches.
2253 ((not (or (eq search-invisible t)
2254 ;; Don't open overlays for automatic replacements.
2255 (and (not query-flag) search-invisible)
2256 ;; Open hidden overlays for interactive replacements.
2257 (not (isearch-range-invisible
2258 (nth 0 real-match-data) (nth 1 real-match-data)))))
2259 (setq skip-invisible-count (1+ skip-invisible-count)))
2261 ;; Calculate the replacement string, if necessary.
2263 (set-match-data real-match-data)
2264 (setq next-replacement
2265 (funcall (car replacements) (cdr replacements)
2267 (if (not query-flag)
2269 (unless (or literal noedit)
2271 (nth 0 real-match-data) (nth 1 real-match-data)
2272 start end search-string
2273 regexp-flag delimited-flag case-fold-search backward))
2275 (replace-match-maybe-edit
2276 next-replacement nocasify literal
2277 noedit real-match-data backward)
2278 replace-count (1+ replace-count)))
2280 (let (done replaced key def)
2281 ;; Loop reading commands until one of them sets done,
2282 ;; which means it has finished handling this
2283 ;; occurrence. Any command that sets `done' should
2284 ;; leave behind proper match data for the stack.
2285 ;; Commands not setting `done' need to adjust
2286 ;; `real-match-data'.
2288 (set-match-data real-match-data)
2290 (match-beginning 0) (match-end 0)
2291 start end search-string
2292 regexp-flag delimited-flag case-fold-search backward)
2293 ;; Bind message-log-max so we don't fill up the message log
2294 ;; with a bunch of identical messages.
2295 (let ((message-log-max nil)
2296 (replacement-presentation
2297 (if query-replace-show-replacement
2299 (set-match-data real-match-data)
2300 (match-substitute-replacement next-replacement
2304 (query-replace-descr from-string)
2305 (query-replace-descr replacement-presentation)))
2306 (setq key (read-event))
2307 ;; Necessary in case something happens during read-event
2308 ;; that clobbers the match data.
2309 (set-match-data real-match-data)
2310 (setq key (vector key))
2311 (setq def (lookup-key map key))
2312 ;; Restore the match data while we process the command.
2313 (cond ((eq def 'help)
2314 (with-output-to-temp-buffer "*Help*"
2316 (concat "Query replacing "
2318 (or (and (symbolp delimited-flag)
2319 (get delimited-flag 'isearch-message-prefix))
2321 (if regexp-flag "regexp " "")
2322 (if backward "backward " "")
2323 from-string " with "
2324 next-replacement ".\n\n"
2325 (substitute-command-keys
2326 query-replace-help)))
2327 (with-current-buffer standard-output
2330 (setq keep-going nil)
2332 ((eq def 'exit-current)
2333 (setq multi-buffer t keep-going nil done t))
2336 (let ((elt (pop stack)))
2337 (goto-char (nth 0 elt))
2338 (setq replaced (nth 1 elt)
2343 (message "No previous match")
2344 (ding 'no-terminate)
2349 (replace-match-maybe-edit
2350 next-replacement nocasify literal
2351 noedit real-match-data backward)
2352 replace-count (1+ replace-count)))
2353 (setq done t replaced t))
2354 ((eq def 'act-and-exit)
2357 (replace-match-maybe-edit
2358 next-replacement nocasify literal
2359 noedit real-match-data backward)
2360 replace-count (1+ replace-count)))
2361 (setq keep-going nil)
2362 (setq done t replaced t))
2363 ((eq def 'act-and-show)
2366 (replace-match-maybe-edit
2367 next-replacement nocasify literal
2368 noedit real-match-data backward)
2369 replace-count (1+ replace-count)
2370 real-match-data (replace-match-data
2373 ((or (eq def 'automatic) (eq def 'automatic-all))
2376 (replace-match-maybe-edit
2377 next-replacement nocasify literal
2378 noedit real-match-data backward)
2379 replace-count (1+ replace-count)))
2380 (setq done t query-flag nil replaced t)
2381 (if (eq def 'automatic-all) (setq multi-buffer t)))
2385 ;; `this-command' has the value `query-replace',
2386 ;; so we need to bind it to `recenter-top-bottom'
2387 ;; to allow it to detect a sequence of `C-l'.
2388 (let ((this-command 'recenter-top-bottom)
2389 (last-command 'recenter-top-bottom))
2390 (recenter-top-bottom)))
2392 (let ((opos (point-marker)))
2393 (setq real-match-data (replace-match-data
2396 (goto-char (match-beginning 0))
2398 (save-window-excursion
2401 (set-marker opos nil))
2402 ;; Before we make the replacement,
2403 ;; decide whether the search string
2404 ;; can match again just after this match.
2405 (if (and regexp-flag nonempty-match)
2406 (setq match-again (and (looking-at search-string)
2408 ;; Edit replacement.
2409 ((eq def 'edit-replacement)
2410 (setq real-match-data (replace-match-data
2414 (read-string "Edit replacement string: "
2418 (set-match-data real-match-data)
2420 (replace-match-maybe-edit
2421 next-replacement nocasify literal noedit
2422 real-match-data backward)
2426 ((eq def 'delete-and-edit)
2427 (replace-match "" t t)
2428 (setq real-match-data (replace-match-data
2429 nil real-match-data))
2430 (replace-dehighlight)
2431 (save-excursion (recursive-edit))
2433 ;; Note: we do not need to treat `exit-prefix'
2434 ;; specially here, since we reread
2435 ;; any unrecognized character.
2437 (setq this-command 'mode-exited)
2438 (setq keep-going nil)
2439 (setq unread-command-events
2440 (append (listify-key-sequence key)
2441 unread-command-events))
2443 (when query-replace-lazy-highlight
2444 ;; Force lazy rehighlighting only after replacements.
2445 (if (not (memq def '(skip backup)))
2446 (setq isearch-lazy-highlight-last-string nil)))
2447 (unless (eq def 'recenter)
2448 ;; Reset recenter cycling order to initial position.
2449 (setq recenter-last-op nil)))
2450 ;; Record previous position for ^ when we move on.
2451 ;; Change markers to numbers in the match data
2452 ;; since lots of markers slow down editing.
2453 (push (list (point) replaced
2454 ;;; If the replacement has already happened, all we need is the
2455 ;;; current match start and end. We could get this with a trivial
2457 ;;; (save-excursion (goto-char (match-beginning 0))
2458 ;;; (search-forward (match-string 0))
2460 ;;; if we really wanted to avoid manually constructing match data.
2461 ;;; Adding current-buffer is necessary so that match-data calls can
2462 ;;; return markers which are appropriate for editing.
2471 (replace-dehighlight))
2472 (or unread-command-events
2473 (message "Replaced %d occurrence%s%s"
2475 (if (= replace-count 1) "" "s")
2476 (if (> (+ skip-read-only-count
2478 skip-invisible-count) 0)
2479 (format " (skipped %s)"
2483 (if (> skip-read-only-count 0)
2484 (format "%s read-only"
2485 skip-read-only-count))
2486 (if (> skip-invisible-count 0)
2487 (format "%s invisible"
2488 skip-invisible-count))
2489 (if (> skip-filtered-count 0)
2490 (format "%s filtered out"
2491 skip-filtered-count))))
2494 (or (and keep-going stack) multi-buffer)))
2496 ;;; replace.el ends here