1 ;;; replace.el --- replace commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2018 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 <https://www.gnu.org/licenses/>.
26 ;; This package supplies the string and regular-expression replace functions
27 ;; documented in the Emacs user's manual.
32 (eval-when-compile (require 'cl-lib
))
34 (defcustom case-replace t
35 "Non-nil means `query-replace' should preserve case in replacements."
39 (defcustom replace-char-fold nil
40 "Non-nil means replacement commands should do character folding in matches.
41 This means, for instance, that \\=' will match a large variety of
43 This variable affects `query-replace' and `replace-string', but not
49 (defcustom replace-lax-whitespace nil
50 "Non-nil means `query-replace' matches a sequence of whitespace chars.
51 When you enter a space or spaces in the strings to be replaced,
52 it will match any sequence matched by the regexp `search-whitespace-regexp'."
57 (defcustom replace-regexp-lax-whitespace nil
58 "Non-nil means `query-replace-regexp' matches a sequence of whitespace chars.
59 When you enter a space or spaces in the regexps to be replaced,
60 it will match any sequence matched by the regexp `search-whitespace-regexp'."
65 (defvar query-replace-history nil
66 "Default history list for query-replace commands.
67 See `query-replace-from-history-variable' and
68 `query-replace-to-history-variable'.")
70 (defvar query-replace-defaults nil
71 "Default values of FROM-STRING and TO-STRING for `query-replace'.
72 This is a list of cons cells (FROM-STRING . TO-STRING), or nil
73 if there are no default values.")
75 (defvar query-replace-interactive nil
76 "Non-nil means `query-replace' uses the last search string.
77 That becomes the \"string to replace\".")
78 (make-obsolete-variable 'query-replace-interactive
79 "use `M-n' to pull the last incremental search string
80 to the minibuffer that reads the string to replace, or invoke replacements
81 from Isearch by using a key sequence like `C-s C-s M-%'." "24.3")
83 (defcustom query-replace-from-to-separator
" → "
84 "String that separates FROM and TO in the history of replacement pairs.
85 When nil, the pair will not be added to the history (same behavior
89 (const :tag
"Disabled" nil
)
93 (defcustom query-replace-from-history-variable
'query-replace-history
94 "History list to use for the FROM argument of `query-replace' commands.
95 The value of this variable should be a symbol; that symbol
96 is used as a variable to hold a history list for the strings
97 or patterns to be replaced."
102 (defcustom query-replace-to-history-variable
'query-replace-history
103 "History list to use for the TO argument of `query-replace' commands.
104 The value of this variable should be a symbol; that symbol
105 is used as a variable to hold a history list for replacement
106 strings or patterns."
111 (defcustom query-replace-skip-read-only nil
112 "Non-nil means `query-replace' and friends ignore read-only matches."
117 (defcustom query-replace-show-replacement t
118 "Non-nil means show substituted replacement text in the minibuffer.
119 This variable affects only `query-replace-regexp'."
124 (defcustom query-replace-highlight t
125 "Non-nil means to highlight matches during query replacement."
129 (defcustom query-replace-lazy-highlight t
130 "Controls the lazy-highlighting during query replacements.
131 When non-nil, all text in the buffer matching the current match
132 is highlighted lazily using isearch lazy highlighting (see
133 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
135 :group
'lazy-highlight
139 (defface query-replace
140 '((t (:inherit isearch
)))
141 "Face for highlighting query replacement matches."
145 (defvar replace-count
0
146 "Number of replacements done so far.
147 See `replace-regexp' and `query-replace-regexp-eval'.")
149 (defun query-replace-descr (string)
150 (setq string
(copy-sequence string
))
151 (dotimes (i (length string
))
152 (let ((c (aref string i
)))
154 ((< c ?\s
) (add-text-properties
156 `(display ,(propertize (format "^%c" (+ c
64)) 'face
'escape-glyph
))
158 ((= c ?\^?
) (add-text-properties
160 `(display ,(propertize "^?" 'face
'escape-glyph
))
164 (defun query-replace--split-string (string)
165 "Split string STRING at a substring with property `separator'."
166 (let* ((length (length string
))
167 (split-pos (text-property-any 0 length
'separator t string
)))
170 (cons (substring string
0 split-pos
)
171 (substring-no-properties
172 string
(or (text-property-not-all
173 (1+ split-pos
) length
'separator t string
)
177 (defun query-replace-read-from (prompt regexp-flag
)
178 "Query and return the `from' argument of a query-replace operation.
179 The return value can also be a pair (FROM . TO) indicating that the user
180 wants to replace FROM with TO."
181 (if query-replace-interactive
182 (car (if regexp-flag regexp-search-ring search-ring
))
183 (let* ((history-add-new-input nil
)
185 (when query-replace-from-to-separator
186 ;; Check if the first non-whitespace char is displayable
187 (if (char-displayable-p
188 (string-to-char (replace-regexp-in-string
189 " " "" query-replace-from-to-separator
)))
190 query-replace-from-to-separator
193 (when separator-string
194 (propertize separator-string
195 'display separator-string
196 'face
'minibuffer-prompt
201 (mapcar (lambda (from-to)
202 (concat (query-replace-descr (car from-to
))
204 (query-replace-descr (cdr from-to
))))
205 query-replace-defaults
))
206 (symbol-value query-replace-from-history-variable
)))
207 (minibuffer-allow-text-properties t
) ; separator uses text-properties
209 (cond ((and query-replace-defaults separator
)
210 (format "%s (default %s): " prompt
(car minibuffer-history
)))
211 (query-replace-defaults
212 (format "%s (default %s -> %s): " prompt
213 (query-replace-descr (caar query-replace-defaults
))
214 (query-replace-descr (cdar query-replace-defaults
))))
215 (t (format "%s: " prompt
))))
217 ;; The save-excursion here is in case the user marks and copies
218 ;; a region in order to specify the minibuffer input.
219 ;; That should not clobber the region for the query-replace itself.
221 (minibuffer-with-setup-hook
223 (setq-local text-property-default-nonsticky
224 (append '((separator . t
) (face . t
))
225 text-property-default-nonsticky
)))
227 (read-regexp prompt nil
'minibuffer-history
)
228 (read-from-minibuffer
229 prompt nil nil nil nil
(car search-ring
) t
)))))
231 (if (and (zerop (length from
)) query-replace-defaults
)
232 (cons (caar query-replace-defaults
)
233 (query-replace-compile-replacement
234 (cdar query-replace-defaults
) regexp-flag
))
235 (setq from
(query-replace--split-string from
))
236 (when (consp from
) (setq to
(cdr from
) from
(car from
)))
237 (add-to-history query-replace-from-history-variable from nil t
)
238 ;; Warn if user types \n or \t, but don't reject the input.
240 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
241 (let ((match (match-string 3 from
)))
243 ((string= match
"\\n")
244 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
245 ((string= match
"\\t")
246 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
250 (add-to-history query-replace-to-history-variable to nil t
)
251 (add-to-history 'query-replace-defaults
(cons from to
) nil t
)
252 (cons from
(query-replace-compile-replacement to regexp-flag
)))))))
254 (defun query-replace-compile-replacement (to regexp-flag
)
255 "Maybe convert a regexp replacement TO to Lisp.
256 Returns a list suitable for `perform-replace' if necessary,
257 the original string if not."
259 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
))
263 (setq pos
(match-end 0))
264 (push (substring to
0 (- pos
2)) list
)
265 (setq char
(aref to
(1- pos
))
266 to
(substring to pos
))
268 (push '(number-to-string replace-count
) list
))
270 (setq pos
(read-from-string to
))
271 (push `(replace-quote ,(car pos
)) list
)
273 ;; Swallow a space after a symbol
274 ;; if there is a space.
275 (if (and (or (symbolp (car pos
))
276 ;; Swallow a space after 'foo
277 ;; but not after (quote foo).
278 (and (eq (car-safe (car pos
)) 'quote
)
279 (not (= ?\
( (aref to
0)))))
280 (eq (string-match " " to
(cdr pos
))
284 (setq to
(substring to end
)))))
285 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
)))
286 (setq to
(nreverse (delete "" (cons to list
))))
287 (replace-match-string-symbols to
)
288 (cons 'replace-eval-replacement
295 (defun query-replace-read-to (from prompt regexp-flag
)
296 "Query and return the `to' argument of a query-replace operation."
297 (query-replace-compile-replacement
299 (let* ((history-add-new-input nil
)
300 (to (read-from-minibuffer
301 (format "%s %s with: " prompt
(query-replace-descr from
))
303 query-replace-to-history-variable from t
)))
304 (add-to-history query-replace-to-history-variable to nil t
)
305 (add-to-history 'query-replace-defaults
(cons from to
) nil t
)
309 (defun query-replace-read-args (prompt regexp-flag
&optional noerror
)
311 (barf-if-buffer-read-only))
312 (let* ((from (query-replace-read-from prompt regexp-flag
))
313 (to (if (consp from
) (prog1 (cdr from
) (setq from
(car from
)))
314 (query-replace-read-to from prompt regexp-flag
))))
316 (or (and current-prefix-arg
(not (eq current-prefix-arg
'-
)))
317 (and (plist-member (text-properties-at 0 from
) 'isearch-regexp-function
)
318 (get-text-property 0 'isearch-regexp-function from
)))
319 (and current-prefix-arg
(eq current-prefix-arg
'-
)))))
321 (defun query-replace (from-string to-string
&optional delimited start end backward region-noncontiguous-p
)
322 "Replace some occurrences of FROM-STRING with TO-STRING.
323 As each match is found, the user must type a character saying
324 what to do with it. For directions, type \\[help-command] at that time.
326 In Transient Mark mode, if the mark is active, operate on the contents
327 of the region. Otherwise, operate from point to the end of the buffer's
330 In interactive use, the prefix arg (non-nil DELIMITED in
331 non-interactive use), means replace only matches surrounded by
332 word boundaries. A negative prefix arg means replace backward.
334 Use \\<minibuffer-local-map>\\[next-history-element] \
335 to pull the last incremental search string to the minibuffer
336 that reads FROM-STRING, or invoke replacements from
337 incremental search with a key sequence like `C-s C-s M-%'
338 to use its current search string as the string to replace.
340 Matching is independent of case if `case-fold-search' is non-nil and
341 FROM-STRING has no uppercase letters. Replacement transfers the case
342 pattern of the old text to the new text, if `case-replace' and
343 `case-fold-search' are non-nil and FROM-STRING has no uppercase
344 letters. (Transferring the case pattern means that if the old text
345 matched is all caps, or capitalized, then its replacement is upcased
348 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
349 ignore hidden matches if `search-invisible' is nil, and ignore more
350 matches using `isearch-filter-predicate'.
352 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
353 to be replaced will match a sequence of whitespace chars defined by the
354 regexp in `search-whitespace-regexp'.
356 If `replace-char-fold' is non-nil, matching uses character folding,
357 i.e. it ignores diacritics and other differences between equivalent
360 Fourth and fifth arg START and END specify the region to operate on.
362 Arguments FROM-STRING, TO-STRING, DELIMITED, START, END, BACKWARD, and
363 REGION-NONCONTIGUOUS-P are passed to `perform-replace' (which see).
365 To customize possible responses, change the bindings in `query-replace-map'."
368 (query-replace-read-args
369 (concat "Query replace"
370 (if current-prefix-arg
371 (if (eq current-prefix-arg
'-
) " backward" " word")
373 (if (use-region-p) " in region" ""))
375 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
376 ;; These are done separately here
377 ;; so that command-history will record these expressions
378 ;; rather than the values they had this time.
379 (if (use-region-p) (region-beginning))
380 (if (use-region-p) (region-end))
382 (if (use-region-p) (region-noncontiguous-p)))))
383 (perform-replace from-string to-string t nil delimited nil nil start end backward region-noncontiguous-p
))
385 (define-key esc-map
"%" 'query-replace
)
387 (defun query-replace-regexp (regexp to-string
&optional delimited start end backward region-noncontiguous-p
)
388 "Replace some things after point matching REGEXP with TO-STRING.
389 As each match is found, the user must type a character saying
390 what to do with it. For directions, type \\[help-command] at that time.
392 In Transient Mark mode, if the mark is active, operate on the contents
393 of the region. Otherwise, operate from point to the end of the buffer's
396 Use \\<minibuffer-local-map>\\[next-history-element] \
397 to pull the last incremental search regexp to the minibuffer
398 that reads REGEXP, or invoke replacements from
399 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
400 to use its current search regexp as the regexp to replace.
402 Matching is independent of case if `case-fold-search' is non-nil and
403 REGEXP has no uppercase letters. Replacement transfers the case
404 pattern of the old text to the new text, if `case-replace' and
405 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
406 \(Transferring the case pattern means that if the old text matched is
407 all caps, or capitalized, then its replacement is upcased or
410 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
411 ignore hidden matches if `search-invisible' is nil, and ignore more
412 matches using `isearch-filter-predicate'.
414 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
415 to be replaced will match a sequence of whitespace chars defined by the
416 regexp in `search-whitespace-regexp'.
418 This function is not affected by `replace-char-fold'.
420 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
421 only matches surrounded by word boundaries. A negative prefix arg means
424 Fourth and fifth arg START and END specify the region to operate on.
426 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
427 and `\\=\\N' (where N is a digit) stands for whatever matched
428 the Nth `\\(...\\)' (1-based) in REGEXP. The `\\(...\\)' groups are
430 `\\?' lets you edit the replacement text in the minibuffer
431 at the given position for each replacement.
433 In interactive calls, the replacement text can contain `\\,'
434 followed by a Lisp expression. Each
435 replacement evaluates that expression to compute the replacement
436 string. Inside of that expression, `\\&' is a string denoting the
437 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
438 for the whole or a partial match converted to a number with
439 `string-to-number', and `\\#' itself for the number of replacements
440 done so far (starting with zero).
442 If the replacement expression is a symbol, write a space after it
443 to terminate it. One space there, if any, will be discarded.
445 When using those Lisp features interactively in the replacement
446 text, TO-STRING is actually made a list instead of a string.
447 Use \\[repeat-complex-command] after this command for details.
449 Arguments REGEXP, TO-STRING, DELIMITED, START, END, BACKWARD, and
450 REGION-NONCONTIGUOUS-P are passed to `perform-replace' (which see)."
453 (query-replace-read-args
454 (concat "Query replace"
455 (if current-prefix-arg
456 (if (eq current-prefix-arg
'-
) " backward" " word")
459 (if (use-region-p) " in region" ""))
461 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
462 ;; These are done separately here
463 ;; so that command-history will record these expressions
464 ;; rather than the values they had this time.
465 (if (use-region-p) (region-beginning))
466 (if (use-region-p) (region-end))
468 (if (use-region-p) (region-noncontiguous-p)))))
469 (perform-replace regexp to-string t t delimited nil nil start end backward region-noncontiguous-p
))
471 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
473 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end region-noncontiguous-p
)
474 "Replace some things after point matching REGEXP with the result of TO-EXPR.
476 Interactive use of this function is deprecated in favor of the
477 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
478 using `search-forward-regexp' and `replace-match' is preferred.
480 As each match is found, the user must type a character saying
481 what to do with it. For directions, type \\[help-command] at that time.
483 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
484 reference `replace-count' to get the number of replacements already made.
485 If the result of TO-EXPR is not a string, it is converted to one using
486 `prin1-to-string' with the NOESCAPE argument (which see).
488 For convenience, when entering TO-EXPR interactively, you can use `\\&'
489 to stand for whatever matched the whole of REGEXP, and `\\N' (where
490 N is a digit) to stand for whatever matched the Nth `\\(...\\)' (1-based)
493 Use `\\#&' or `\\#N' if you want a number instead of a string.
494 In interactive use, `\\#' in itself stands for `replace-count'.
496 In Transient Mark mode, if the mark is active, operate on the contents
497 of the region. Otherwise, operate from point to the end of the buffer's
500 Use \\<minibuffer-local-map>\\[next-history-element] \
501 to pull the last incremental search regexp to the minibuffer
504 Preserves case in each replacement if `case-replace' and `case-fold-search'
505 are non-nil and REGEXP has no uppercase letters.
507 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
508 ignore hidden matches if `search-invisible' is nil, and ignore more
509 matches using `isearch-filter-predicate'.
511 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
512 to be replaced will match a sequence of whitespace chars defined by the
513 regexp in `search-whitespace-regexp'.
515 This function is not affected by `replace-char-fold'.
517 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
518 only matches that are surrounded by word boundaries.
519 Fourth and fifth arg START and END specify the region to operate on.
521 Arguments REGEXP, DELIMITED, START, END, and REGION-NONCONTIGUOUS-P
522 are passed to `perform-replace' (which see)."
523 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
524 for interactive calls, and `search-forward-regexp'/`replace-match'
525 for Lisp calls." "22.1"))
528 (barf-if-buffer-read-only)
530 ;; Let-bind the history var to disable the "foo -> bar"
531 ;; default. Maybe we shouldn't disable this default, but
532 ;; for now I'll leave it off. --Stef
533 (let ((query-replace-defaults nil
))
534 (query-replace-read-from "Query replace regexp" t
)))
535 (to (list (read-from-minibuffer
536 (format "Query replace regexp %s with eval: "
537 (query-replace-descr from
))
538 nil nil t query-replace-to-history-variable from t
))))
539 ;; We make TO a list because replace-match-string-symbols requires one,
540 ;; and the user might enter a single token.
541 (replace-match-string-symbols to
)
542 (list from
(car to
) current-prefix-arg
543 (if (use-region-p) (region-beginning))
544 (if (use-region-p) (region-end))
545 (if (use-region-p) (region-noncontiguous-p))))))
546 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
547 t
'literal delimited nil nil start end nil region-noncontiguous-p
))
549 (defun map-query-replace-regexp (regexp to-strings
&optional n start end region-noncontiguous-p
)
550 "Replace some matches for REGEXP with various strings, in rotation.
551 The second argument TO-STRINGS contains the replacement strings, separated
552 by spaces. This command works like `query-replace-regexp' except that
553 each successive replacement uses the next successive replacement string,
554 wrapping around from the last such string to the first.
556 In Transient Mark mode, if the mark is active, operate on the contents
557 of the region. Otherwise, operate from point to the end of the buffer's
560 Non-interactively, TO-STRINGS may be a list of replacement strings.
562 Interactively, reads the regexp using `read-regexp'.
563 Use \\<minibuffer-local-map>\\[next-history-element] \
564 to pull the last incremental search regexp to the minibuffer
567 A prefix argument N says to use each replacement string N times
568 before rotating to the next.
569 Fourth and fifth arg START and END specify the region to operate on.
571 Arguments REGEXP, START, END, and REGION-NONCONTIGUOUS-P are passed to
572 `perform-replace' (which see)."
574 (let* ((from (read-regexp "Map query replace (regexp): " nil
575 query-replace-from-history-variable
))
576 (to (read-from-minibuffer
577 (format "Query replace %s with (space-separated strings): "
578 (query-replace-descr from
))
580 query-replace-to-history-variable from t
)))
582 (and current-prefix-arg
583 (prefix-numeric-value current-prefix-arg
))
584 (if (use-region-p) (region-beginning))
585 (if (use-region-p) (region-end))
586 (if (use-region-p) (region-noncontiguous-p)))))
588 (if (listp to-strings
)
589 (setq replacements to-strings
)
590 (while (/= (length to-strings
) 0)
591 (if (string-match " " to-strings
)
594 (list (substring to-strings
0
595 (string-match " " to-strings
))))
596 to-strings
(substring to-strings
597 (1+ (string-match " " to-strings
))))
598 (setq replacements
(append replacements
(list to-strings
))
600 (perform-replace regexp replacements t t nil n nil start end nil region-noncontiguous-p
)))
602 (defun replace-string (from-string to-string
&optional delimited start end backward region-noncontiguous-p
)
603 "Replace occurrences of FROM-STRING with TO-STRING.
604 Preserve case in each match if `case-replace' and `case-fold-search'
605 are non-nil and FROM-STRING has no uppercase letters.
606 \(Preserving case means that if the string matched is all caps, or capitalized,
607 then its replacement is upcased or capitalized.)
609 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
610 ignore hidden matches if `search-invisible' is nil, and ignore more
611 matches using `isearch-filter-predicate'.
613 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
614 to be replaced will match a sequence of whitespace chars defined by the
615 regexp in `search-whitespace-regexp'.
617 If `replace-char-fold' is non-nil, matching uses character folding,
618 i.e. it ignores diacritics and other differences between equivalent
621 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
622 only matches surrounded by word boundaries. A negative prefix arg means
625 Operates on the region between START and END (if both are nil, from point
626 to the end of the buffer). Interactively, if Transient Mark mode is
627 enabled and the mark is active, operates on the contents of the region;
628 otherwise from point to the end of the buffer's accessible portion.
630 Use \\<minibuffer-local-map>\\[next-history-element] \
631 to pull the last incremental search string to the minibuffer
632 that reads FROM-STRING.
634 This function is usually the wrong thing to use in a Lisp program.
635 What you probably want is a loop like this:
636 (while (search-forward FROM-STRING nil t)
637 (replace-match TO-STRING nil t))
638 which will run faster and will not set the mark or print anything.
639 \(You may need a more complex loop if FROM-STRING can match the null string
640 and TO-STRING is also null.)"
641 (declare (interactive-only
642 "use `search-forward' and `replace-match' instead."))
645 (query-replace-read-args
647 (if current-prefix-arg
648 (if (eq current-prefix-arg
'-
) " backward" " word")
651 (if (use-region-p) " in region" ""))
653 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
654 (if (use-region-p) (region-beginning))
655 (if (use-region-p) (region-end))
657 (if (use-region-p) (region-noncontiguous-p)))))
658 (perform-replace from-string to-string nil nil delimited nil nil start end backward region-noncontiguous-p
))
660 (defun replace-regexp (regexp to-string
&optional delimited start end backward region-noncontiguous-p
)
661 "Replace things after point matching REGEXP with TO-STRING.
662 Preserve case in each match if `case-replace' and `case-fold-search'
663 are non-nil and REGEXP has no uppercase letters.
665 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
666 ignore hidden matches if `search-invisible' is nil, and ignore more
667 matches using `isearch-filter-predicate'.
669 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
670 to be replaced will match a sequence of whitespace chars defined by the
671 regexp in `search-whitespace-regexp'.
673 This function is not affected by `replace-char-fold'
675 In Transient Mark mode, if the mark is active, operate on the contents
676 of the region. Otherwise, operate from point to the end of the buffer's
679 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
680 only matches surrounded by word boundaries. A negative prefix arg means
683 Fourth and fifth arg START and END specify the region to operate on.
685 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
686 and `\\=\\N' (where N is a digit) stands for whatever matched
687 the Nth `\\(...\\)' (1-based) in REGEXP.
688 `\\?' lets you edit the replacement text in the minibuffer
689 at the given position for each replacement.
691 In interactive calls, the replacement text may contain `\\,'
692 followed by a Lisp expression used as part of the replacement
693 text. Inside of that expression, `\\&' is a string denoting the
694 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
695 numeric values from `string-to-number', and `\\#' itself for
696 `replace-count', the number of replacements occurred so far, starting
699 If your Lisp expression is an identifier and the next letter in
700 the replacement string would be interpreted as part of it, you
701 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
702 for this particular case you may also enter `\\#' in the
703 replacement text directly.
705 When using those Lisp features interactively in the replacement
706 text, TO-STRING is actually made a list instead of a string.
707 Use \\[repeat-complex-command] after this command for details.
709 Use \\<minibuffer-local-map>\\[next-history-element] \
710 to pull the last incremental search regexp to the minibuffer
713 This function is usually the wrong thing to use in a Lisp program.
714 What you probably want is a loop like this:
715 (while (re-search-forward REGEXP nil t)
716 (replace-match TO-STRING nil nil))
717 which will run faster and will not set the mark or print anything."
718 (declare (interactive-only
719 "use `re-search-forward' and `replace-match' instead."))
722 (query-replace-read-args
724 (if current-prefix-arg
725 (if (eq current-prefix-arg
'-
) " backward" " word")
728 (if (use-region-p) " in region" ""))
730 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
731 (if (use-region-p) (region-beginning))
732 (if (use-region-p) (region-end))
734 (if (use-region-p) (region-noncontiguous-p)))))
735 (perform-replace regexp to-string nil t delimited nil nil start end backward region-noncontiguous-p
))
738 (defvar regexp-history nil
739 "History list for some commands that read regular expressions.
741 Maximum length of the history list is determined by the value
742 of `history-length', which see.")
744 (defvar occur-collect-regexp-history
'("\\1")
745 "History of regexp for occur's collect operation")
747 (defcustom read-regexp-defaults-function nil
748 "Function that provides default regexp(s) for `read-regexp'.
749 This function should take no arguments and return one of: nil, a
750 regexp, or a list of regexps. Interactively, `read-regexp' uses
751 the return value of this function for its DEFAULT argument.
753 As an example, set this variable to `find-tag-default-as-regexp'
754 to default to the symbol at point.
756 To provide different default regexps for different commands,
757 the function that you set this to can check `this-command'."
759 (const :tag
"No default regexp reading function" nil
)
760 (const :tag
"Latest regexp history" regexp-history-last
)
761 (function-item :tag
"Tag at point"
763 (function-item :tag
"Tag at point as regexp"
764 find-tag-default-as-regexp
)
765 (function-item :tag
"Tag at point as symbol regexp"
766 find-tag-default-as-symbol-regexp
)
767 (function :tag
"Your choice of function"))
771 (defun read-regexp-suggestions ()
772 "Return a list of standard suggestions for `read-regexp'.
773 By default, the list includes the tag at point, the last isearch regexp,
774 the last isearch string, and the last replacement regexp. `read-regexp'
775 appends the list returned by this function to the end of values available
776 via \\<minibuffer-local-map>\\[next-history-element]."
778 (find-tag-default-as-regexp)
779 (find-tag-default-as-symbol-regexp)
780 (car regexp-search-ring
)
781 (regexp-quote (or (car search-ring
) ""))
782 (car (symbol-value query-replace-from-history-variable
))))
784 (defun read-regexp (prompt &optional defaults history
)
785 "Read and return a regular expression as a string.
786 Prompt with the string PROMPT. If PROMPT ends in \":\" (followed by
787 optional whitespace), use it as-is. Otherwise, add \": \" to the end,
788 possibly preceded by the default result (see below).
790 The optional argument DEFAULTS can be either: nil, a string, a list
791 of strings, or a symbol. We use DEFAULTS to construct the default
792 return value in case of empty input.
794 If DEFAULTS is a string, we use it as-is.
796 If DEFAULTS is a list of strings, the first element is the
797 default return value, but all the elements are accessible
798 using the history command \\<minibuffer-local-map>\\[next-history-element].
800 If DEFAULTS is a non-nil symbol, then if `read-regexp-defaults-function'
801 is non-nil, we use that in place of DEFAULTS in the following:
802 If DEFAULTS is the symbol `regexp-history-last', we use the first
803 element of HISTORY (if specified) or `regexp-history'.
804 If DEFAULTS is a function, we call it with no arguments and use
805 what it returns, which should be either nil, a string, or a list of strings.
807 We append the standard values from `read-regexp-suggestions' to DEFAULTS
810 If the first element of DEFAULTS is non-nil (and if PROMPT does not end
811 in \":\", followed by optional whitespace), we add it to the prompt.
813 The optional argument HISTORY is a symbol to use for the history list.
814 If nil, uses `regexp-history'."
816 (if (and defaults
(symbolp defaults
))
818 ((eq (or read-regexp-defaults-function defaults
)
819 'regexp-history-last
)
820 (car (symbol-value (or history
'regexp-history
))))
821 ((functionp (or read-regexp-defaults-function defaults
))
822 (funcall (or read-regexp-defaults-function defaults
))))
824 (default (if (consp defaults
) (car defaults
) defaults
))
825 (suggestions (if (listp defaults
) defaults
(list defaults
)))
826 (suggestions (append suggestions
(read-regexp-suggestions)))
827 (suggestions (delete-dups (delq nil
(delete "" suggestions
))))
828 ;; Do not automatically add default to the history for empty input.
829 (history-add-new-input nil
)
830 (input (read-from-minibuffer
831 (cond ((string-match-p ":[ \t]*\\'" prompt
)
833 ((and default
(> (length default
) 0))
834 (format "%s (default %s): " prompt
835 (query-replace-descr default
)))
837 (format "%s: " prompt
)))
838 nil nil nil
(or history
'regexp-history
) suggestions t
)))
840 ;; Return the default value when the user enters empty input.
841 (prog1 (or default input
)
843 (add-to-history (or history
'regexp-history
) default
)))
844 ;; Otherwise, add non-empty input to the history and return input.
846 (add-to-history (or history
'regexp-history
) input
)))))
849 (defalias 'delete-non-matching-lines
'keep-lines
)
850 (defalias 'delete-matching-lines
'flush-lines
)
851 (defalias 'count-matches
'how-many
)
854 (defun keep-lines-read-args (prompt)
855 "Read arguments for `keep-lines' and friends.
856 Prompt for a regexp with PROMPT.
857 Value is a list, (REGEXP)."
858 (list (read-regexp prompt
) nil nil t
))
860 (defun keep-lines (regexp &optional rstart rend interactive
)
861 "Delete all lines except those containing matches for REGEXP.
862 A match split across lines preserves all the lines it lies in.
863 When called from Lisp (and usually interactively as well, see below)
864 applies to all lines starting after point.
866 If REGEXP contains upper case characters (excluding those preceded by `\\')
867 and `search-upper-case' is non-nil, the matching is case-sensitive.
869 Second and third arg RSTART and REND specify the region to operate on.
870 This command operates on (the accessible part of) all lines whose
871 accessible part is entirely contained in the region determined by RSTART
872 and REND. (A newline ending a line counts as part of that line.)
874 Interactively, in Transient Mark mode when the mark is active, operate
875 on all lines whose accessible part is entirely contained in the region.
876 Otherwise, the command applies to all lines starting after point.
877 When calling this function from Lisp, you can pretend that it was
878 called interactively by passing a non-nil INTERACTIVE argument.
880 This function starts looking for the next match from the end of
881 the previous match. Hence, it ignores matches that overlap
882 a previously found match."
885 (barf-if-buffer-read-only)
886 (keep-lines-read-args "Keep lines containing match for regexp")))
889 (goto-char (min rstart rend
))
893 (goto-char (max rstart rend
))
894 (unless (or (bolp) (eobp))
897 (if (and interactive
(use-region-p))
898 (setq rstart
(region-beginning)
900 (goto-char (region-end))
901 (unless (or (bolp) (eobp))
905 rend
(point-max-marker)))
908 (or (bolp) (forward-line 1))
909 (let ((start (point))
911 (if (and case-fold-search search-upper-case
)
912 (isearch-no-upper-case-p regexp t
)
914 (while (< (point) rend
)
915 ;; Start is first char not preserved by previous match.
916 (if (not (re-search-forward regexp rend
'move
))
917 (delete-region start rend
)
918 (let ((end (save-excursion (goto-char (match-beginning 0))
921 ;; Now end is first char preserved by the new match.
923 (delete-region start end
))))
925 (setq start
(save-excursion (forward-line 1) (point)))
926 ;; If the match was empty, avoid matching again at same place.
927 (and (< (point) rend
)
928 (= (match-beginning 0) (match-end 0))
930 (set-marker rend nil
)
934 (defun flush-lines (regexp &optional rstart rend interactive
)
935 "Delete lines containing matches for REGEXP.
936 When called from Lisp (and usually when called interactively as
937 well, see below), applies to the part of the buffer after point.
938 The line point is in is deleted if and only if it contains a
939 match for regexp starting after point.
941 If REGEXP contains upper case characters (excluding those preceded by `\\')
942 and `search-upper-case' is non-nil, the matching is case-sensitive.
944 Second and third arg RSTART and REND specify the region to operate on.
945 Lines partially contained in this region are deleted if and only if
946 they contain a match entirely contained in it.
948 Interactively, in Transient Mark mode when the mark is active, operate
949 on the contents of the region. Otherwise, operate from point to the
950 end of (the accessible portion of) the buffer. When calling this function
951 from Lisp, you can pretend that it was called interactively by passing
952 a non-nil INTERACTIVE argument.
954 If a match is split across lines, all the lines it lies in are deleted.
955 They are deleted _before_ looking for the next match. Hence, a match
956 starting on the same line at which another match ended is ignored."
959 (barf-if-buffer-read-only)
960 (keep-lines-read-args "Flush lines containing match for regexp")))
963 (goto-char (min rstart rend
))
964 (setq rend
(copy-marker (max rstart rend
))))
965 (if (and interactive
(use-region-p))
966 (setq rstart
(region-beginning)
967 rend
(copy-marker (region-end)))
969 rend
(point-max-marker)))
971 (let ((case-fold-search
972 (if (and case-fold-search search-upper-case
)
973 (isearch-no-upper-case-p regexp t
)
976 (while (and (< (point) rend
)
977 (re-search-forward regexp rend t
))
978 (delete-region (save-excursion (goto-char (match-beginning 0))
981 (progn (forward-line 1) (point))))))
982 (set-marker rend nil
)
986 (defun how-many (regexp &optional rstart rend interactive
)
987 "Print and return number of matches for REGEXP following point.
988 When called from Lisp and INTERACTIVE is omitted or nil, just return
989 the number, do not print it; if INTERACTIVE is t, the function behaves
990 in all respects as if it had been called interactively.
992 If REGEXP contains upper case characters (excluding those preceded by `\\')
993 and `search-upper-case' is non-nil, the matching is case-sensitive.
995 Second and third arg RSTART and REND specify the region to operate on.
997 Interactively, in Transient Mark mode when the mark is active, operate
998 on the contents of the region. Otherwise, operate from point to the
999 end of (the accessible portion of) the buffer.
1001 This function starts looking for the next match from the end of
1002 the previous match. Hence, it ignores matches that overlap
1003 a previously found match."
1005 (keep-lines-read-args "How many matches for regexp"))
1010 (goto-char (min rstart rend
))
1011 (setq rend
(max rstart rend
)))
1013 (setq rend
(point-max)))
1014 (if (and interactive
(use-region-p))
1015 (setq rstart
(region-beginning)
1017 (setq rstart
(point)
1023 (if (and case-fold-search search-upper-case
)
1024 (isearch-no-upper-case-p regexp t
)
1026 (while (and (< (point) rend
)
1027 (progn (setq opoint
(point))
1028 (re-search-forward regexp rend t
)))
1029 (if (= opoint
(point))
1031 (setq count
(1+ count
))))
1032 (when interactive
(message "%d occurrence%s"
1034 (if (= count
1) "" "s")))
1038 (defvar occur-menu-map
1039 (let ((map (make-sparse-keymap)))
1040 (bindings--define-key map
[next-error-follow-minor-mode
]
1041 '(menu-item "Auto Occurrence Display"
1042 next-error-follow-minor-mode
1043 :help
"Display another occurrence when moving the cursor"
1044 :button
(:toggle .
(and (boundp 'next-error-follow-minor-mode
)
1045 next-error-follow-minor-mode
))))
1046 (bindings--define-key map
[separator-1
] menu-bar-separator
)
1047 (bindings--define-key map
[kill-this-buffer
]
1048 '(menu-item "Kill Occur Buffer" kill-this-buffer
1049 :help
"Kill the current *Occur* buffer"))
1050 (bindings--define-key map
[quit-window
]
1051 '(menu-item "Quit Occur Window" quit-window
1052 :help
"Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
1053 (bindings--define-key map
[revert-buffer
]
1054 '(menu-item "Revert Occur Buffer" revert-buffer
1055 :help
"Replace the text in the *Occur* buffer with the results of rerunning occur"))
1056 (bindings--define-key map
[clone-buffer
]
1057 '(menu-item "Clone Occur Buffer" clone-buffer
1058 :help
"Create and return a twin copy of the current *Occur* buffer"))
1059 (bindings--define-key map
[occur-rename-buffer
]
1060 '(menu-item "Rename Occur Buffer" occur-rename-buffer
1061 :help
"Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
1062 (bindings--define-key map
[occur-edit-buffer
]
1063 '(menu-item "Edit Occur Buffer" occur-edit-mode
1064 :help
"Edit the *Occur* buffer and apply changes to the original buffers."))
1065 (bindings--define-key map
[separator-2
] menu-bar-separator
)
1066 (bindings--define-key map
[occur-mode-goto-occurrence-other-window
]
1067 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
1068 :help
"Go to the occurrence the current line describes, in another window"))
1069 (bindings--define-key map
[occur-mode-goto-occurrence
]
1070 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
1071 :help
"Go to the occurrence the current line describes"))
1072 (bindings--define-key map
[occur-mode-display-occurrence
]
1073 '(menu-item "Display Occurrence" occur-mode-display-occurrence
1074 :help
"Display in another window the occurrence the current line describes"))
1075 (bindings--define-key map
[occur-next
]
1076 '(menu-item "Move to Next Match" occur-next
1077 :help
"Move to the Nth (default 1) next match in an Occur mode buffer"))
1078 (bindings--define-key map
[occur-prev
]
1079 '(menu-item "Move to Previous Match" occur-prev
1080 :help
"Move to the Nth (default 1) previous match in an Occur mode buffer"))
1082 "Menu keymap for `occur-mode'.")
1084 (defvar occur-mode-map
1085 (let ((map (make-sparse-keymap)))
1086 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
1087 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
1088 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
1089 (define-key map
"e" 'occur-edit-mode
)
1090 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
1091 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
1092 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
1093 (define-key map
"\M-n" 'occur-next
)
1094 (define-key map
"\M-p" 'occur-prev
)
1095 (define-key map
"r" 'occur-rename-buffer
)
1096 (define-key map
"c" 'clone-buffer
)
1097 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
1098 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
1100 "Keymap for `occur-mode'.")
1102 (defvar occur-revert-arguments nil
1103 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
1104 See `occur-revert-function'.")
1105 (make-variable-buffer-local 'occur-revert-arguments
)
1106 (put 'occur-revert-arguments
'permanent-local t
)
1108 (defcustom occur-mode-hook
'(turn-on-font-lock)
1109 "Hook run when entering Occur mode."
1113 (defcustom occur-hook nil
1114 "Hook run by Occur when there are any matches."
1118 (defcustom occur-mode-find-occurrence-hook nil
1119 "Hook run by Occur after locating an occurrence.
1120 This will be called with the cursor position at the occurrence. An application
1121 for this is to reveal context in an outline-mode when the occurrence is hidden."
1125 (put 'occur-mode
'mode-class
'special
)
1126 (define-derived-mode occur-mode special-mode
"Occur"
1127 "Major mode for output from \\[occur].
1128 \\<occur-mode-map>Move point to one of the items in this buffer, then use
1129 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
1130 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
1133 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
1134 (setq next-error-function
'occur-next-error
))
1139 (defvar occur-edit-mode-map
1140 (let ((map (make-sparse-keymap)))
1141 (set-keymap-parent map text-mode-map
)
1142 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
1143 (define-key map
"\C-c\C-c" 'occur-cease-edit
)
1144 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
1145 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
1146 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
1148 "Keymap for `occur-edit-mode'.")
1150 (define-derived-mode occur-edit-mode occur-mode
"Occur-Edit"
1151 "Major mode for editing *Occur* buffers.
1152 In this mode, changes to the *Occur* buffer are also applied to
1153 the originating buffer.
1155 To return to ordinary Occur mode, use \\[occur-cease-edit]."
1156 (setq buffer-read-only nil
)
1157 (add-hook 'after-change-functions
'occur-after-change-function nil t
)
1158 (message (substitute-command-keys
1159 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
1161 (defun occur-cease-edit ()
1162 "Switch from Occur Edit mode to Occur mode."
1164 (when (derived-mode-p 'occur-edit-mode
)
1166 (message "Switching to Occur mode.")))
1168 (defun occur-after-change-function (beg end length
)
1171 (let* ((line-beg (line-beginning-position))
1172 (m (get-text-property line-beg
'occur-target
))
1173 (buf (marker-buffer m
))
1175 (when (and (get-text-property line-beg
'occur-prefix
)
1176 (not (get-text-property end
'occur-prefix
)))
1178 ;; Apply occur-target property to inserted (e.g. yanked) text.
1179 (put-text-property beg end
'occur-target m
)
1180 ;; Did we insert a newline? Occur Edit mode can't create new
1181 ;; Occur entries; just discard everything after the newline.
1183 (and (search-forward "\n" end t
)
1184 (delete-region (1- (point)) end
))))
1185 (let* ((line (- (line-number-at-pos)
1186 (line-number-at-pos (window-start))))
1187 (readonly (with-current-buffer buf buffer-read-only
))
1188 (win (or (get-buffer-window buf
)
1190 '(nil (inhibit-same-window . t
)
1191 (inhibit-switch-frame . t
)))))
1192 (line-end (line-end-position))
1193 (text (save-excursion
1194 (goto-char (next-single-property-change
1195 line-beg
'occur-prefix nil
1197 (setq col
(- (point) line-beg
))
1198 (buffer-substring-no-properties (point) line-end
))))
1199 (with-selected-window win
1203 (message "Buffer `%s' is read only." buf
)
1204 (delete-region (line-beginning-position) (line-end-position))
1206 (move-to-column col
)))))))
1209 (defun occur-revert-function (_ignore1 _ignore2
)
1210 "Handle `revert-buffer' for Occur mode buffers."
1211 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
1213 (defun occur-mode-find-occurrence ()
1214 (let ((pos (get-text-property (point) 'occur-target
)))
1216 (error "No occurrence on this line"))
1217 (unless (buffer-live-p (marker-buffer pos
))
1218 (error "Buffer for this occurrence was killed"))
1221 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
1222 (defun occur-mode-goto-occurrence (&optional event
)
1223 "Go to the occurrence on the current line."
1224 (interactive (list last-nonmenu-event
))
1225 (let ((buffer (when event
(current-buffer)))
1228 ;; Actually `event-end' works correctly with a nil argument as
1229 ;; well, so we could dispense with this test, but let's not
1230 ;; rely on this undocumented behavior.
1231 (occur-mode-find-occurrence)
1232 (with-current-buffer (window-buffer (posn-window (event-end event
)))
1234 (goto-char (posn-point (event-end event
)))
1235 (occur-mode-find-occurrence))))))
1236 (pop-to-buffer (marker-buffer pos
))
1238 (when buffer
(next-error-found buffer
(current-buffer)))
1239 (run-hooks 'occur-mode-find-occurrence-hook
)))
1241 (defun occur-mode-goto-occurrence-other-window ()
1242 "Go to the occurrence the current line describes, in another window."
1244 (let ((buffer (current-buffer))
1245 (pos (occur-mode-find-occurrence)))
1246 (switch-to-buffer-other-window (marker-buffer pos
))
1248 (next-error-found buffer
(current-buffer))
1249 (run-hooks 'occur-mode-find-occurrence-hook
)))
1251 (defun occur-mode-display-occurrence ()
1252 "Display in another window the occurrence the current line describes."
1254 (let ((buffer (current-buffer))
1255 (pos (occur-mode-find-occurrence))
1257 (setq window
(display-buffer (marker-buffer pos
) t
))
1258 ;; This is the way to set point in the proper window.
1259 (save-selected-window
1260 (select-window window
)
1262 (next-error-found buffer
(current-buffer))
1263 (run-hooks 'occur-mode-find-occurrence-hook
))))
1265 (defun occur-find-match (n search message
)
1266 (if (not n
) (setq n
1))
1269 (setq r
(funcall search
(point) 'occur-match
))
1271 (get-text-property r
'occur-match
)
1272 (setq r
(funcall search r
'occur-match
)))
1275 (user-error message
))
1278 (defun occur-next (&optional n
)
1279 "Move to the Nth (default 1) next match in an Occur mode buffer."
1281 (occur-find-match n
#'next-single-property-change
"No more matches"))
1283 (defun occur-prev (&optional n
)
1284 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1286 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
1288 (defun occur-next-error (&optional argp reset
)
1289 "Move to the Nth (default 1) next match in an Occur mode buffer.
1290 Compatibility function for \\[next-error] invocations."
1292 (goto-char (cond (reset (point-min))
1293 ((< argp
0) (line-beginning-position))
1294 ((> argp
0) (line-end-position))
1299 #'previous-single-property-change
1300 #'next-single-property-change
)
1302 ;; In case the *Occur* buffer is visible in a nonselected window.
1303 (let ((win (get-buffer-window (current-buffer) t
)))
1304 (if win
(set-window-point win
(point))))
1305 (occur-mode-goto-occurrence))
1308 '((((class color
) (min-colors 88) (background light
))
1309 :background
"yellow1")
1310 (((class color
) (min-colors 88) (background dark
))
1311 :background
"RoyalBlue3")
1312 (((class color
) (min-colors 8) (background light
))
1313 :background
"yellow" :foreground
"black")
1314 (((class color
) (min-colors 8) (background dark
))
1315 :background
"blue" :foreground
"white")
1316 (((type tty
) (class mono
))
1318 (t :background
"gray"))
1319 "Face used to highlight matches permanently."
1324 (defcustom list-matching-lines-default-context-lines
0
1325 "Default number of context lines included around `list-matching-lines' matches.
1326 A negative number means to include that many lines before the match.
1327 A positive number means to include that many lines both before and after."
1331 (defalias 'list-matching-lines
'occur
)
1333 (defcustom list-matching-lines-face
'match
1334 "Face used by \\[list-matching-lines] to show the text that matches.
1335 If the value is nil, don't highlight the matching portions specially."
1339 (defcustom list-matching-lines-buffer-name-face
'underline
1340 "Face used by \\[list-matching-lines] to show the names of buffers.
1341 If the value is nil, don't highlight the buffer names specially."
1345 (defcustom list-matching-lines-current-line-face
'lazy-highlight
1346 "Face used by \\[list-matching-lines] to highlight the current line."
1351 (defcustom list-matching-lines-jump-to-current-line nil
1352 "If non-nil, \\[list-matching-lines] shows the current line highlighted.
1353 Set the point right after such line when there are matches after it."
1358 (defcustom list-matching-lines-prefix-face
'shadow
1359 "Face used by \\[list-matching-lines] to show the prefix column.
1360 If the face doesn't differ from the default face,
1361 don't highlight the prefix with line numbers specially."
1366 (defcustom occur-excluded-properties
1367 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1368 yank-handler follow-link
)
1369 "Text properties to discard when copying lines to the *Occur* buffer.
1370 The value should be a list of text properties to discard or t,
1371 which means to discard all text properties."
1372 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
1376 (defun occur-read-primary-args ()
1377 (let* ((perform-collect (consp current-prefix-arg
))
1378 (regexp (read-regexp (if perform-collect
1379 "Collect strings matching regexp"
1380 "List lines matching regexp")
1381 'regexp-history-last
)))
1384 ;; Perform collect operation
1385 (if (zerop (regexp-opt-depth regexp
))
1386 ;; No subexpression so collect the entire match.
1388 ;; Get the regexp for collection pattern.
1389 (let ((default (car occur-collect-regexp-history
)))
1391 (format "Regexp to collect (default %s): " default
)
1392 default
'occur-collect-regexp-history
)))
1393 ;; Otherwise normal occur takes numerical prefix argument.
1394 (when current-prefix-arg
1395 (prefix-numeric-value current-prefix-arg
))))))
1397 (defun occur-rename-buffer (&optional unique-p interactive-p
)
1398 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1399 Here `original-buffer-name' is the buffer name where Occur was originally run.
1400 When given the prefix argument, or called non-interactively, the renaming
1401 will not clobber the existing buffer(s) of that name, but use
1402 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1403 if you always want a separate *Occur* buffer for each buffer where you
1405 (interactive "P\np")
1406 (with-current-buffer
1407 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
1408 (rename-buffer (concat "*Occur: "
1409 (mapconcat #'buffer-name
1410 (car (cddr occur-revert-arguments
)) "/")
1412 (or unique-p
(not interactive-p
)))))
1414 ;; Region limits when `occur' applies on a region.
1415 (defvar occur--region-start nil
)
1416 (defvar occur--region-end nil
)
1417 (defvar occur--region-start-line nil
)
1418 (defvar occur--orig-line nil
)
1419 (defvar occur--final-pos nil
)
1421 (defun occur (regexp &optional nlines region
)
1422 "Show all lines in the current buffer containing a match for REGEXP.
1423 If a match spreads across multiple lines, all those lines are shown.
1425 Each match is extended to include complete lines. Only non-overlapping
1426 matches are considered. (Note that extending matches to complete
1427 lines could cause some of the matches to overlap; if so, they will not
1428 be shown as separate matches.)
1430 Each line is displayed with NLINES lines before and after, or -NLINES
1431 before if NLINES is negative.
1432 NLINES defaults to `list-matching-lines-default-context-lines'.
1433 Interactively it is the prefix arg.
1435 Optional arg REGION, if non-nil, mean restrict search to the
1436 specified region. Otherwise search the entire buffer.
1437 REGION must be a list of (START . END) positions as returned by
1440 The lines are shown in a buffer named `*Occur*'.
1441 It serves as a menu to find any of the occurrences in this buffer.
1442 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1443 If `list-matching-lines-jump-to-current-line' is non-nil, then show
1444 the current line highlighted with `list-matching-lines-current-line-face'
1445 and set point at the first match after such line.
1447 If REGEXP contains upper case characters (excluding those preceded by `\\')
1448 and `search-upper-case' is non-nil, the matching is case-sensitive.
1450 When NLINES is a string or when the function is called
1451 interactively with prefix argument without a number (`C-u' alone
1452 as prefix) the matching strings are collected into the `*Occur*'
1453 buffer by using NLINES as a replacement regexp. NLINES may
1454 contain \\& and \\N which convention follows `replace-match'.
1455 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1456 \"\\1\" for NLINES collects all the function names in a lisp
1457 program. When there is no parenthesized subexpressions in REGEXP
1458 the entire match is collected. In any case the searched buffer
1461 (nconc (occur-read-primary-args)
1462 (and (use-region-p) (list (region-bounds)))))
1463 (let* ((start (and (caar region
) (max (caar region
) (point-min))))
1464 (end (and (cdar region
) (min (cdar region
) (point-max))))
1465 (in-region-p (or start end
)))
1467 (or start
(setq start
(point-min)))
1468 (or end
(setq end
(point-max))))
1469 (let ((occur--region-start start
)
1470 (occur--region-end end
)
1471 (occur--region-start-line
1473 (line-number-at-pos (min start end
))))
1475 (line-number-at-pos (point))))
1476 (save-excursion ; If no matches `occur-1' doesn't restore the point.
1477 (and in-region-p
(narrow-to-region
1478 (save-excursion (goto-char start
) (line-beginning-position))
1479 (save-excursion (goto-char end
) (line-end-position))))
1480 (occur-1 regexp nlines
(list (current-buffer)))
1481 (and in-region-p
(widen))))))
1483 (defvar ido-ignore-item-temp-list
)
1485 (defun multi-occur (bufs regexp
&optional nlines
)
1486 "Show all lines in buffers BUFS containing a match for REGEXP.
1487 This function acts on multiple buffers; otherwise, it is exactly like
1488 `occur'. When you invoke this command interactively, you must specify
1489 the buffer names that you want, one by one.
1490 See also `multi-occur-in-matching-buffers'."
1493 (let* ((bufs (list (read-buffer "First buffer to search: "
1494 (current-buffer) t
)))
1496 (ido-ignore-item-temp-list bufs
))
1497 (while (not (string-equal
1498 (setq buf
(read-buffer
1499 (if (eq read-buffer-function
#'ido-read-buffer
)
1500 "Next buffer to search (C-j to end): "
1501 "Next buffer to search (RET to end): ")
1504 (cl-pushnew buf bufs
)
1505 (setq ido-ignore-item-temp-list bufs
))
1506 (nreverse (mapcar #'get-buffer bufs
)))
1507 (occur-read-primary-args)))
1508 (occur-1 regexp nlines bufs
))
1510 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1511 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1512 Normally BUFREGEXP matches against each buffer's visited file name,
1513 but if you specify a prefix argument, it matches against the buffer name.
1514 See also `multi-occur'."
1517 (let* ((default (car regexp-history
))
1520 (if current-prefix-arg
1521 "List lines in buffers whose names match regexp: "
1522 "List lines in buffers whose filenames match regexp: "))))
1523 (if (equal input
"")
1526 (occur-read-primary-args)))
1530 (mapcar (lambda (buf)
1532 (string-match bufregexp
1534 (and (buffer-file-name buf
)
1535 (string-match bufregexp
1536 (buffer-file-name buf
))))
1540 (defun occur-regexp-descr (regexp)
1541 (format " for %s\"%s\""
1542 (or (get-text-property 0 'isearch-regexp-function-descr regexp
)
1544 (if (get-text-property 0 'isearch-string regexp
)
1546 (query-replace-descr
1547 (get-text-property 0 'isearch-string regexp
))
1549 (query-replace-descr regexp
))))
1551 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1552 (unless (and regexp
(not (equal regexp
"")))
1553 (error "Occur doesn't work with the empty regexp"))
1555 (setq buf-name
"*Occur*"))
1557 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1558 (when (buffer-live-p buf
) buf
))
1560 ;; Handle the case where one of the buffers we're searching is the
1561 ;; output buffer. Just rename it.
1562 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1563 (with-current-buffer (get-buffer buf-name
)
1566 ;; Now find or create the output buffer.
1567 ;; If we just renamed that buffer, we will make a new one here.
1568 (setq occur-buf
(get-buffer-create buf-name
))
1570 (with-current-buffer occur-buf
1571 (if (stringp nlines
)
1572 (fundamental-mode) ;; This is for collect operation.
1574 (let ((inhibit-read-only t
)
1575 ;; Don't generate undo entries for creation of the initial contents.
1576 (buffer-undo-list t
)
1577 (occur--final-pos nil
))
1580 (if (stringp nlines
)
1581 ;; Treat nlines as a regexp to collect.
1582 (let ((bufs active-bufs
)
1585 (with-current-buffer (car bufs
)
1587 (goto-char (point-min))
1588 (while (re-search-forward regexp nil t
)
1589 ;; Insert the replacement regexp.
1590 (let ((str (match-substitute-replacement nlines
)))
1592 (with-current-buffer occur-buf
1594 (setq count
(1+ count
))
1595 (or (zerop (current-column))
1596 (insert "\n"))))))))
1597 (setq bufs
(cdr bufs
)))
1599 ;; Perform normal occur.
1601 regexp active-bufs occur-buf
1602 (or nlines list-matching-lines-default-context-lines
)
1603 (if (and case-fold-search search-upper-case
)
1604 (isearch-no-upper-case-p regexp t
)
1606 list-matching-lines-buffer-name-face
1607 (if (face-differs-from-default-p list-matching-lines-prefix-face
)
1608 list-matching-lines-prefix-face
)
1609 list-matching-lines-face
1610 (not (eq occur-excluded-properties t
))))))
1611 (let* ((bufcount (length active-bufs
))
1612 (diff (- (length bufs
) bufcount
)))
1613 (message "Searched %d buffer%s%s; %s match%s%s"
1614 bufcount
(if (= bufcount
1) "" "s")
1615 (if (zerop diff
) "" (format " (%d killed)" diff
))
1616 (if (zerop count
) "no" (format "%d" count
))
1617 (if (= count
1) "" "es")
1618 ;; Don't display regexp if with remaining text
1619 ;; it is longer than window-width.
1620 (if (> (+ (length (or (get-text-property 0 'isearch-string regexp
)
1624 "" (occur-regexp-descr regexp
))))
1625 (setq occur-revert-arguments
(list regexp nlines bufs
))
1627 (kill-buffer occur-buf
)
1628 (display-buffer occur-buf
)
1629 (when occur--final-pos
1631 (get-buffer-window occur-buf
'all-frames
)
1633 (setq next-error-last-buffer occur-buf
)
1634 (setq buffer-read-only t
)
1635 (set-buffer-modified-p nil
)
1636 (run-hooks 'occur-hook
)))))))
1638 (defun occur-engine (regexp buffers out-buf nlines case-fold
1639 title-face prefix-face match-face keep-props
)
1640 (with-current-buffer out-buf
1641 (let ((global-lines 0) ;; total count of matching lines
1642 (global-matches 0) ;; total count of matches
1644 (case-fold-search case-fold
)
1645 (in-region-p (and occur--region-start occur--region-end
))
1646 (multi-occur-p (cdr buffers
)))
1647 ;; Map over all the buffers
1648 (dolist (buf buffers
)
1649 (when (buffer-live-p buf
)
1650 (let ((lines 0) ;; count of matching lines
1651 (matches 0) ;; count of matches
1652 (curr-line ;; line count
1653 (or occur--region-start-line
1))
1654 (orig-line occur--orig-line
)
1656 (prev-line nil
) ;; line number of prev match endpt
1657 (prev-after-lines nil
) ;; context lines of prev match
1665 (inhibit-field-text-motion t
)
1666 (headerpt (with-current-buffer out-buf
(point))))
1667 (with-current-buffer buf
1668 ;; The following binding is for when case-fold-search
1669 ;; has a local binding in the original buffer, in which
1670 ;; case we cannot bind it globally and let that have
1671 ;; effect in every buffer we search.
1672 (let ((case-fold-search case-fold
))
1674 ;; Set CODING only if the current buffer locally
1675 ;; binds buffer-file-coding-system.
1676 (not (local-variable-p 'buffer-file-coding-system
))
1677 (setq coding buffer-file-coding-system
))
1679 (goto-char (point-min)) ;; begin searching in the buffer
1681 (setq origpt
(point))
1682 (when (setq endpt
(re-search-forward regexp nil t
))
1683 (setq lines
(1+ lines
)) ;; increment matching lines count
1684 (setq matchbeg
(match-beginning 0))
1685 ;; Get beginning of first match line and end of the last.
1687 (goto-char matchbeg
)
1688 (setq begpt
(line-beginning-position))
1690 (setq endpt
(line-end-position)))
1691 ;; Sum line numbers up to the first match line.
1692 (setq curr-line
(+ curr-line
(count-lines origpt begpt
)))
1693 (setq marker
(make-marker))
1694 (set-marker marker matchbeg
)
1695 (setq curstring
(occur-engine-line begpt endpt keep-props
))
1696 ;; Highlight the matches
1697 (let ((len (length curstring
))
1699 ;; Count empty lines that don't use next loop (Bug#22062).
1701 (setq matches
(1+ matches
)))
1702 (when (and list-matching-lines-jump-to-current-line
1703 (not multi-occur-p
))
1704 (when (= curr-line orig-line
)
1705 (add-face-text-property
1706 0 len list-matching-lines-current-line-face nil curstring
)
1707 (add-text-properties 0 len
'(current-line t
) curstring
))
1708 (when (and (>= orig-line
(- curr-line nlines
))
1709 (<= orig-line
(+ curr-line nlines
)))
1710 ;; Shown either here or will be shown by occur-context-lines
1711 (setq orig-line-shown-p t
)))
1712 (while (and (< start len
)
1713 (string-match regexp curstring start
))
1714 (setq matches
(1+ matches
))
1715 (add-text-properties
1716 (match-beginning 0) (match-end 0)
1717 '(occur-match t
) curstring
)
1719 ;; Add `match-face' to faces copied from the buffer.
1720 (add-face-text-property
1721 (match-beginning 0) (match-end 0)
1722 match-face nil curstring
))
1723 ;; Avoid infloop (Bug#7593).
1724 (let ((end (match-end 0)))
1725 (setq start
(if (= start end
) (1+ start
) end
)))))
1726 ;; Generate the string to insert for this match
1727 (let* ((match-prefix
1728 ;; Using 7 digits aligns tabs properly.
1729 (apply #'propertize
(format "%7d:" curr-line
)
1732 `(font-lock-face ,prefix-face
))
1733 `(occur-prefix t mouse-face
(highlight)
1734 ;; Allow insertion of text
1735 ;; at the end of the prefix
1736 ;; (for Occur Edit mode).
1739 occur-target
,marker
1741 help-echo
"mouse-2: go to this occurrence"))))
1743 ;; We don't put `mouse-face' on the newline,
1744 ;; because that loses. And don't put it
1745 ;; on context lines to reduce flicker.
1746 (propertize curstring
'mouse-face
(list 'highlight
)
1747 'occur-target marker
1750 "mouse-2: go to this occurrence"))
1754 ;; Add non-numeric prefix to all non-first lines
1755 ;; of multi-line matches.
1756 (replace-regexp-in-string
1760 "\n :" 'font-lock-face prefix-face
)
1763 ;; Add marker at eol, but no mouse props.
1764 (propertize "\n" 'occur-target marker
)))
1767 ;; The simple display style
1769 ;; The complex multi-line display style.
1770 (setq ret
(occur-context-lines
1771 out-line nlines keep-props begpt
1772 endpt curr-line prev-line
1773 prev-after-lines prefix-face
1774 orig-line multi-occur-p
))
1775 ;; Set first elem of the returned list to `data',
1776 ;; and the second elem to `prev-after-lines'.
1777 (setq prev-after-lines
(nth 1 ret
))
1780 (when (and list-matching-lines-jump-to-current-line
1781 (null orig-line-shown-p
)
1782 (> curr-line orig-line
))
1783 (setq orig-line-shown-p t
)
1785 (goto-char (point-min))
1786 (forward-line (- orig-line
(or occur--region-start-line
1)))
1787 (occur-engine-line (line-beginning-position)
1788 (line-end-position) keep-props
)))))
1789 ;; Actually insert the match display data
1790 (with-current-buffer out-buf
1792 (add-face-text-property
1793 0 (length orig-line-str
)
1794 list-matching-lines-current-line-face nil orig-line-str
)
1795 (add-text-properties 0 (length orig-line-str
)
1796 '(current-line t
) orig-line-str
)
1797 (insert (car (occur-engine-add-prefix
1798 (list orig-line-str
) prefix-face
))))
1803 ;; Sum line numbers between first and last match lines.
1804 (setq curr-line
(+ curr-line
(count-lines begpt endpt
)
1805 ;; Add 1 for empty last match line
1806 ;; since count-lines returns one
1808 (if (and (bolp) (eolp)) 1 0)))
1809 ;; On to the next match...
1811 (goto-char (point-max)))
1812 (setq prev-line
(1- curr-line
)))
1813 ;; Flush remaining context after-lines.
1814 (when prev-after-lines
1815 (with-current-buffer out-buf
1816 (insert (apply #'concat
(occur-engine-add-prefix
1817 prev-after-lines prefix-face
)))))
1818 (when (and list-matching-lines-jump-to-current-line
1819 (null orig-line-shown-p
))
1820 (setq orig-line-shown-p t
)
1821 (let ((orig-line-str
1823 (goto-char (point-min))
1824 (forward-line (- orig-line
(or occur--region-start-line
1)))
1825 (occur-engine-line (line-beginning-position)
1826 (line-end-position) keep-props
))))
1827 (add-face-text-property
1828 0 (length orig-line-str
)
1829 list-matching-lines-current-line-face nil orig-line-str
)
1830 (add-text-properties 0 (length orig-line-str
)
1831 '(current-line t
) orig-line-str
)
1832 (with-current-buffer out-buf
1833 (insert (car (occur-engine-add-prefix
1834 (list orig-line-str
) prefix-face
))))))))
1835 (when (not (zerop lines
)) ;; is the count zero?
1836 (setq global-lines
(+ global-lines lines
)
1837 global-matches
(+ global-matches matches
))
1838 (with-current-buffer out-buf
1839 (goto-char headerpt
)
1843 (format "%d match%s%s%s in buffer: %s%s\n"
1844 matches
(if (= matches
1) "" "es")
1845 ;; Don't display the same number of lines
1846 ;; and matches in case of 1 match per line.
1847 (if (= lines matches
)
1848 "" (format " in %d line%s"
1850 (if (= lines
1) "" "s")))
1851 ;; Don't display regexp for multi-buffer.
1852 (if (> (length buffers
) 1)
1853 "" (occur-regexp-descr regexp
))
1856 (format " within region: %d-%d"
1862 (add-text-properties beg end
`(occur-title ,buf
))
1864 (add-face-text-property beg end title-face
))
1865 (goto-char (if (and list-matching-lines-jump-to-current-line
1866 (not multi-occur-p
))
1867 (setq occur--final-pos
1868 (and (goto-char (point-max))
1869 (or (previous-single-property-change (point) 'current-line
)
1871 (point-min))))))))))
1872 ;; Display total match count and regexp for multi-buffer.
1873 (when (and (not (zerop global-lines
)) (> (length buffers
) 1))
1874 (goto-char (point-min))
1877 (insert (format "%d match%s%s total%s:\n"
1878 global-matches
(if (= global-matches
1) "" "es")
1879 ;; Don't display the same number of lines
1880 ;; and matches in case of 1 match per line.
1881 (if (= global-lines global-matches
)
1882 "" (format " in %d line%s"
1883 global-lines
(if (= global-lines
1) "" "s")))
1884 (occur-regexp-descr regexp
)))
1887 (add-face-text-property beg end title-face
)))
1888 (goto-char (point-min)))
1890 ;; CODING is buffer-file-coding-system of the first buffer
1891 ;; that locally binds it. Let's use it also for the output
1893 (set-buffer-file-coding-system coding
))
1894 ;; Return the number of matches
1897 (defun occur-engine-line (beg end
&optional keep-props
)
1898 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
1899 (text-property-not-all beg end
'fontified t
))
1900 (if (fboundp 'jit-lock-fontify-now
)
1901 (jit-lock-fontify-now beg end
)))
1902 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1903 (let ((str (buffer-substring beg end
)))
1904 (remove-list-of-text-properties
1905 0 (length str
) occur-excluded-properties str
)
1907 (buffer-substring-no-properties beg end
)))
1909 (defun occur-engine-add-prefix (lines &optional prefix-face
)
1912 (concat (if prefix-face
1913 (propertize " :" 'font-lock-face prefix-face
)
1918 (defun occur-accumulate-lines (count &optional keep-props pt
)
1922 (let ((forwardp (> count
0))
1923 result beg end moved
)
1924 (while (not (or (zerop count
)
1927 (and (bobp) (not moved
)))))
1928 (setq count
(+ count
(if forwardp -
1 1)))
1929 (setq beg
(line-beginning-position)
1930 end
(line-end-position))
1931 (push (occur-engine-line beg end keep-props
) result
)
1932 (setq moved
(= 0 (forward-line (if forwardp
1 -
1)))))
1933 (nreverse result
))))
1935 ;; Generate context display for occur.
1936 ;; OUT-LINE is the line where the match is.
1937 ;; NLINES and KEEP-PROPS are args to occur-engine.
1938 ;; CURR-LINE is line count of the current match,
1939 ;; PREV-LINE is line count of the previous match,
1940 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1941 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1942 ;; then concatenate them all together.
1943 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1944 curr-line prev-line prev-after-lines
1945 &optional prefix-face
1946 orig-line multi-occur-p
)
1947 ;; Find after- and before-context lines of the current match.
1949 (nreverse (cdr (occur-accumulate-lines
1950 (- (1+ (abs nlines
))) keep-props begpt
))))
1952 (cdr (occur-accumulate-lines
1953 (1+ nlines
) keep-props endpt
)))
1956 (when (and list-matching-lines-jump-to-current-line
1957 (not multi-occur-p
))
1958 (when (and (>= orig-line
(- curr-line nlines
))
1959 (< orig-line curr-line
))
1960 (let ((curstring (nth (- (length before-lines
) (- curr-line orig-line
)) before-lines
)))
1961 (add-face-text-property
1962 0 (length curstring
)
1963 list-matching-lines-current-line-face nil curstring
)
1964 (add-text-properties 0 (length curstring
)
1965 '(current-line t
) curstring
)))
1966 (when (and (<= orig-line
(+ curr-line nlines
))
1967 (> orig-line curr-line
))
1968 (let ((curstring (nth (- orig-line curr-line
1) after-lines
)))
1969 (add-face-text-property
1970 0 (length curstring
)
1971 list-matching-lines-current-line-face nil curstring
)
1972 (add-text-properties 0 (length curstring
)
1973 '(current-line t
) curstring
))))
1975 ;; Combine after-lines of the previous match
1976 ;; with before-lines of the current match.
1978 (when prev-after-lines
1979 ;; Don't overlap prev after-lines with current before-lines.
1980 (if (>= (+ prev-line
(length prev-after-lines
))
1981 (- curr-line
(length before-lines
)))
1982 (setq prev-after-lines
1983 (butlast prev-after-lines
1984 (- (length prev-after-lines
)
1985 (- curr-line prev-line
(length before-lines
) 1))))
1986 ;; Separate non-overlapping context lines with a dashed line.
1987 (setq separator
"-------\n")))
1990 ;; Don't overlap current before-lines with previous match line.
1991 (if (<= (- curr-line
(length before-lines
))
1994 (nthcdr (- (length before-lines
)
1995 (- curr-line prev-line
1))
1997 ;; Separate non-overlapping before-context lines.
1998 (unless (> nlines
0)
1999 (setq separator
"-------\n"))))
2002 ;; Return a list where the first element is the output line.
2005 (if prev-after-lines
2006 (occur-engine-add-prefix prev-after-lines prefix-face
))
2008 (list (if prefix-face
2009 (propertize separator
'font-lock-face prefix-face
)
2011 (occur-engine-add-prefix before-lines prefix-face
)
2013 ;; And the second element is the list of context after-lines.
2014 (if (> nlines
0) after-lines
))))
2017 ;; It would be nice to use \\[...], but there is no reasonable way
2018 ;; to make that display both SPC and Y.
2019 (defconst query-replace-help
2020 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
2021 RET or `q' to exit, Period to replace one match and exit,
2022 Comma to replace but not move point immediately,
2023 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
2024 C-w to delete match and recursive edit,
2025 C-l to clear the screen, redisplay, and offer same replacement again,
2026 ! to replace all remaining matches in this buffer with no more questions,
2027 ^ to move point back to previous match,
2028 u to undo previous replacement,
2029 U to undo all replacements,
2030 E to edit the replacement string.
2031 In multi-buffer replacements type `Y' to replace all remaining
2032 matches in all remaining buffers with no more questions,
2033 `N' to skip to the next buffer without replacing remaining matches
2034 in the current buffer."
2035 "Help message while in `query-replace'.")
2037 (defvar query-replace-map
2038 (let ((map (make-sparse-keymap)))
2039 (define-key map
" " 'act
)
2040 (define-key map
"\d" 'skip
)
2041 (define-key map
[delete] 'skip)
2042 (define-key map [backspace] 'skip)
2043 (define-key map "y" 'act)
2044 (define-key map "n" 'skip)
2045 (define-key map "Y" 'act)
2046 (define-key map "N" 'skip)
2047 (define-key map "e" 'edit-replacement)
2048 (define-key map "E" 'edit-replacement)
2049 (define-key map "," 'act-and-show)
2050 (define-key map "q" 'exit)
2051 (define-key map "\r" 'exit)
2052 (define-key map [return] 'exit)
2053 (define-key map "." 'act-and-exit)
2054 (define-key map "\C-r" 'edit)
2055 (define-key map "\C-w" 'delete-and-edit)
2056 (define-key map "\C-l" 'recenter)
2057 (define-key map "!" 'automatic)
2058 (define-key map "^" 'backup)
2059 (define-key map "u" 'undo)
2060 (define-key map "U" 'undo-all)
2061 (define-key map "\C-h" 'help)
2062 (define-key map [f1] 'help)
2063 (define-key map [help] 'help)
2064 (define-key map "?" 'help)
2065 (define-key map "\C-g" 'quit)
2066 (define-key map "\C-]" 'quit)
2067 (define-key map "\C-v" 'scroll-up)
2068 (define-key map "\M-v" 'scroll-down)
2069 (define-key map [next] 'scroll-up)
2070 (define-key map [prior] 'scroll-down)
2071 (define-key map [?\C-\M-v] 'scroll-other-window)
2072 (define-key map [M-next] 'scroll-other-window)
2073 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
2074 (define-key map [M-prior] 'scroll-other-window-down)
2075 ;; Binding ESC would prohibit the M-v binding. Instead, callers
2076 ;; should check for ESC specially.
2077 ;; (define-key map "\e" 'exit-prefix)
2078 (define-key map [escape] 'exit-prefix)
2080 "Keymap of responses to questions posed by commands like `query-replace'.
2081 The \"bindings\" in this map are not commands; they are answers.
2082 The valid answers include `act', `skip', `act-and-show',
2083 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
2084 `scroll-down', `scroll-other-window', `scroll-other-window-down',
2085 `edit', `edit-replacement', `delete-and-edit', `automatic',
2086 `backup', `undo', `undo-all', `quit', and `help'.
2088 This keymap is used by `y-or-n-p' as well as `query-replace'.")
2090 (defvar multi-query-replace-map
2091 (let ((map (make-sparse-keymap)))
2092 (set-keymap-parent map query-replace-map)
2093 (define-key map "Y" 'automatic-all)
2094 (define-key map "N" 'exit-current)
2096 "Keymap that defines additional bindings for multi-buffer replacements.
2097 It extends its parent map `query-replace-map' with new bindings to
2098 operate on a set of buffers/files. The difference with its parent map
2099 is the additional answers `automatic-all' to replace all remaining
2100 matches in all remaining buffers with no more questions, and
2101 `exit-current' to skip remaining matches in the current buffer
2102 and to continue with the next buffer in the sequence.")
2104 (defun replace-match-string-symbols (n)
2105 "Process a list (and any sub-lists), expanding certain symbols.
2107 N (match-string N) (where N is a string of digits)
2108 #N (string-to-number (match-string N))
2110 #& (string-to-number (match-string 0))
2113 Note that these symbols must be preceded by a backslash in order to
2114 type them using Lisp syntax."
2118 (replace-match-string-symbols (car n))) ;Process sub-list
2120 (let ((name (symbol-name (car n))))
2122 ((string-match "^[0-9]+$" name)
2123 (setcar n (list 'match-string (string-to-number name))))
2124 ((string-match "^#[0-9]+$" name)
2125 (setcar n (list 'string-to-number
2127 (string-to-number (substring name 1))))))
2129 (setcar n '(match-string 0)))
2130 ((string= "#&" name)
2131 (setcar n '(string-to-number (match-string 0))))
2133 (setcar n 'replace-count))))))
2136 (defun replace-eval-replacement (expression count)
2137 (let* ((replace-count count)
2142 (error "Error evaluating replacement expression: %S" err)))))
2143 (if (stringp replacement)
2145 (prin1-to-string replacement t))))
2147 (defun replace-quote (replacement)
2148 "Quote a replacement string.
2149 This just doubles all backslashes in REPLACEMENT and
2150 returns the resulting string. If REPLACEMENT is not
2151 a string, it is first passed through `prin1-to-string'
2152 with the `noescape' argument set.
2154 `match-data' is preserved across the call."
2156 (replace-regexp-in-string "\\\\" "\\\\"
2157 (if (stringp replacement)
2159 (prin1-to-string replacement t))
2162 (defun replace-loop-through-replacements (data count)
2163 ;; DATA is a vector containing the following values:
2164 ;; 0 next-rotate-count
2166 ;; 2 next-replacement
2168 (if (= (aref data 0) count)
2170 (aset data 0 (+ count (aref data 1)))
2171 (let ((next (cdr (aref data 2))))
2172 (aset data 2 (if (consp next) next (aref data 3))))))
2173 (car (aref data 2)))
2175 (defun replace-match-data (integers reuse &optional new)
2176 "Like `match-data', but markers in REUSE get invalidated.
2177 If NEW is non-nil, it is set and returned instead of fresh data,
2178 but coerced to the correct value of INTEGERS."
2181 (set-match-data new)
2183 (eq (null integers) (markerp (car reuse)))
2185 (match-data integers reuse t)))
2187 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data
2189 "Make a replacement with `replace-match', editing `\\?'.
2190 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
2191 After possibly editing it (if `\\?' is present), NEWTEXT is also
2192 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
2193 is made (to save time).
2194 MATCH-DATA is used for the replacement, and is a data structure
2195 as returned from the `match-data' function.
2196 In case editing is done, it is changed to use markers. BACKWARD is
2197 used to reverse the replacement direction.
2199 The return value is non-nil if there has been no `\\?' or NOEDIT was
2200 passed in. If LITERAL is set, no checking is done, anyway."
2201 (unless (or literal noedit)
2203 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
2206 (read-string "Edit replacement string: "
2209 (replace-match "" t t newtext 3)
2210 (1+ (match-beginning 3)))
2213 nil match-data match-data))))
2215 (set-match-data match-data)
2216 (replace-match newtext fixedcase literal)
2217 ;; `query-replace' undo feature needs the beginning of the match position,
2218 ;; but `replace-match' may change it, for instance, with a regexp like "^".
2219 ;; Ensure that this function preserves the match data (Bug#31492).
2220 (set-match-data match-data)
2221 ;; `replace-match' leaves point at the end of the replacement text,
2222 ;; so move point to the beginning when replacing backward.
2223 (when backward (goto-char (nth 0 match-data)))
2226 (defvar replace-update-post-hook nil
2227 "Function(s) to call after query-replace has found a match in the buffer.")
2229 (defvar replace-search-function nil
2230 "Function to use when searching for strings to replace.
2231 It is used by `query-replace' and `replace-string', and is called
2232 with three arguments, as if it were `search-forward'.")
2234 (defvar replace-re-search-function nil
2235 "Function to use when searching for regexps to replace.
2236 It is used by `query-replace-regexp', `replace-regexp',
2237 `query-replace-regexp-eval', and `map-query-replace-regexp'.
2238 It is called with three arguments, as if it were
2239 `re-search-forward'.")
2241 (defun replace-search (search-string limit regexp-flag delimited-flag
2242 case-fold &optional backward)
2243 "Search for the next occurrence of SEARCH-STRING to replace."
2244 ;; Let-bind global isearch-* variables to values used
2245 ;; to search the next replacement. These let-bindings
2246 ;; should be effective both at the time of calling
2247 ;; `isearch-search-fun-default' and also at the
2248 ;; time of funcalling `search-function'.
2249 ;; These isearch-* bindings can't be placed higher
2250 ;; outside of this function because then another I-search
2251 ;; used after `recursive-edit' might override them.
2252 (let* ((isearch-regexp regexp-flag)
2253 (isearch-regexp-function (or delimited-flag
2254 (and replace-char-fold
2256 #'char-fold-to-regexp)))
2257 (isearch-lax-whitespace
2258 replace-lax-whitespace)
2259 (isearch-regexp-lax-whitespace
2260 replace-regexp-lax-whitespace)
2261 (isearch-case-fold-search case-fold)
2262 (isearch-adjusted nil)
2263 (isearch-nonincremental t) ; don't use lax word mode
2264 (isearch-forward (not backward))
2267 replace-re-search-function
2268 replace-search-function)
2269 (isearch-search-fun-default))))
2270 (funcall search-function search-string limit t)))
2272 (defvar replace-overlay nil)
2274 (defun replace-highlight (match-beg match-end range-beg range-end
2275 search-string regexp-flag delimited-flag
2276 case-fold &optional backward)
2277 (if query-replace-highlight
2279 (move-overlay replace-overlay match-beg match-end (current-buffer))
2280 (setq replace-overlay (make-overlay match-beg match-end))
2281 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2282 (overlay-put replace-overlay 'face 'query-replace)))
2283 (if query-replace-lazy-highlight
2284 (let ((isearch-string search-string)
2285 (isearch-regexp regexp-flag)
2286 (isearch-regexp-function (or delimited-flag
2287 (and replace-char-fold
2289 #'char-fold-to-regexp)))
2290 (isearch-lax-whitespace
2291 replace-lax-whitespace)
2292 (isearch-regexp-lax-whitespace
2293 replace-regexp-lax-whitespace)
2294 (isearch-case-fold-search case-fold)
2295 (isearch-forward (not backward))
2296 (isearch-other-end match-beg)
2297 (isearch-error nil))
2298 (isearch-lazy-highlight-new-loop range-beg range-end))))
2300 (defun replace-dehighlight ()
2301 (when replace-overlay
2302 (delete-overlay replace-overlay))
2303 (when query-replace-lazy-highlight
2304 (lazy-highlight-cleanup lazy-highlight-cleanup)
2305 (setq isearch-lazy-highlight-last-string nil))
2306 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2307 (isearch-clean-overlays))
2309 ;; A macro because we push STACK, i.e. a local var in `perform-replace'.
2310 (defmacro replace--push-stack (replaced search-str next-replace stack)
2311 (declare (indent 0) (debug (form form form gv-place)))
2312 `(push (list (point) ,replaced
2313 ;;; If the replacement has already happened, all we need is the
2314 ;;; current match start and end. We could get this with a trivial
2316 ;;; (save-excursion (goto-char (match-beginning 0))
2317 ;;; (search-forward (match-string 0))
2319 ;;; if we really wanted to avoid manually constructing match data.
2320 ;;; Adding current-buffer is necessary so that match-data calls can
2321 ;;; return markers which are appropriate for editing.
2324 (match-beginning 0) (match-end 0) (current-buffer))
2326 ,search-str ,next-replace)
2329 (defun perform-replace (from-string replacements
2330 query-flag regexp-flag delimited-flag
2331 &optional repeat-count map start end backward region-noncontiguous-p)
2332 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2333 Don't use this in your own program unless you want to query and set the mark
2334 just as `query-replace' does. Instead, write a simple loop like this:
2336 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2337 (replace-match \"foobar\" nil nil))
2339 which will run faster and probably do exactly what you want. Please
2340 see the documentation of `replace-match' to find out how to simulate
2343 This function returns nil if and only if there were no matches to
2344 make, or the user didn't cancel the call.
2346 REPLACEMENTS is either a string, a list of strings, or a cons cell
2347 containing a function and its first argument. The function is
2348 called to generate each replacement like this:
2349 (funcall (car replacements) (cdr replacements) replace-count)
2350 It must return a string.
2352 Non-nil REGION-NONCONTIGUOUS-P means that the region is composed of
2353 noncontiguous pieces. The most common example of this is a
2354 rectangular region, where the pieces are separated by newline
2356 (or map (setq map query-replace-map))
2357 (and query-flag minibuffer-auto-raise
2358 (raise-frame (window-frame (minibuffer-window))))
2359 (let* ((case-fold-search
2360 (if (and case-fold-search search-upper-case)
2361 (isearch-no-upper-case-p from-string regexp-flag)
2363 (nocasify (not (and case-replace case-fold-search)))
2364 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2365 (search-string from-string)
2366 (real-match-data nil) ; The match data for the current match.
2367 (next-replacement nil)
2368 ;; This is non-nil if we know there is nothing for the user
2369 ;; to edit in the replacement.
2373 (search-string-replaced nil) ; last string matching `from-string'
2374 (next-replacement-replaced nil) ; replacement string
2375 ; (substituted regexp)
2377 (last-was-act-and-show)
2380 (skip-read-only-count 0)
2381 (skip-filtered-count 0)
2382 (skip-invisible-count 0)
2383 (nonempty-match nil)
2385 (recenter-last-op nil) ; Start cycling order with initial position.
2387 ;; If non-nil, it is marker saying where in the buffer to stop.
2389 ;; Use local binding in add-function below.
2390 (isearch-filter-predicate isearch-filter-predicate)
2393 ;; Data for the next match. If a cons, it has the same format as
2394 ;; (match-data); otherwise it is t if a match is possible at point.
2400 (concat "Query replacing "
2401 (if backward "backward " "")
2403 (or (and (symbolp delimited-flag)
2405 'isearch-message-prefix))
2407 (if regexp-flag "regexp " "")
2409 (substitute-command-keys
2410 "(\\<query-replace-map>\\[help] for help) "))
2411 minibuffer-prompt-properties))))
2413 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
2414 (when region-noncontiguous-p
2416 (mapcar (lambda (position)
2417 (cons (copy-marker (car position))
2418 (copy-marker (cdr position))))
2419 (funcall region-extract-function 'bounds)))
2420 (add-function :after-while isearch-filter-predicate
2425 (>= start (car bounds))
2426 (<= start (cdr bounds))
2427 (>= end (car bounds))
2428 (<= end (cdr bounds))))
2431 ;; If region is active, in Transient Mark mode, operate on region.
2434 (setq limit (copy-marker (min start end)))
2435 (goto-char (max start end))
2438 (setq limit (copy-marker (max start end)))
2439 (goto-char (min start end))
2442 ;; If last typed key in previous call of multi-buffer perform-replace
2443 ;; was `automatic-all', don't ask more questions in next files
2444 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2445 (setq query-flag nil multi-buffer t))
2448 ((stringp replacements)
2449 (setq next-replacement replacements
2451 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2452 (or repeat-count (setq repeat-count 1))
2453 (setq replacements (cons 'replace-loop-through-replacements
2454 (vector repeat-count repeat-count
2455 replacements replacements)))))
2457 (when query-replace-lazy-highlight
2458 (setq isearch-lazy-highlight-last-string nil))
2463 ;; Loop finding occurrences that perhaps should be replaced.
2464 (while (and keep-going
2466 (not (or (bobp) (and limit (<= (point) limit))))
2467 (not (or (eobp) (and limit (>= (point) limit)))))
2468 ;; Use the next match if it is already known;
2469 ;; otherwise, search for a match after moving forward
2470 ;; one char if progress is required.
2471 (setq real-match-data
2472 (cond ((consp match-again)
2473 (goto-char (if backward
2475 (nth 1 match-again)))
2477 t real-match-data match-again))
2478 ;; MATCH-AGAIN non-nil means accept an
2482 (replace-search search-string limit
2483 regexp-flag delimited-flag
2484 case-fold-search backward)
2485 ;; For speed, use only integers and
2486 ;; reuse the list used last time.
2487 (replace-match-data t real-match-data)))
2489 (> (1- (point)) (point-min))
2490 (< (1+ (point)) (point-max)))
2493 (> (1- (point)) limit)
2494 (< (1+ (point)) limit))))
2495 ;; If not accepting adjacent matches,
2496 ;; move one char to the right before
2497 ;; searching again. Undo the motion
2498 ;; if the search fails.
2499 (let ((opoint (point)))
2500 (forward-char (if backward -1 1))
2501 (if (replace-search search-string limit
2502 regexp-flag delimited-flag
2503 case-fold-search backward)
2509 ;; Record whether the match is nonempty, to avoid an infinite loop
2510 ;; repeatedly matching the same empty string.
2511 (setq nonempty-match
2512 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2514 ;; If the match is empty, record that the next one can't be
2517 ;; Otherwise, if matching a regular expression, do the next
2518 ;; match now, since the replacement for this match may
2519 ;; affect whether the next match is adjacent to this one.
2520 ;; If that match is empty, don't use it.
2523 (or (not regexp-flag)
2525 (looking-back search-string nil)
2526 (looking-at search-string))
2527 (let ((match (match-data)))
2528 (and (/= (nth 0 match) (nth 1 match))
2532 ;; Optionally ignore matches that have a read-only property.
2533 ((not (or (not query-replace-skip-read-only)
2534 (not (text-property-not-all
2535 (nth 0 real-match-data) (nth 1 real-match-data)
2537 (setq skip-read-only-count (1+ skip-read-only-count)))
2538 ;; Optionally filter out matches.
2539 ((not (funcall isearch-filter-predicate
2540 (nth 0 real-match-data) (nth 1 real-match-data)))
2541 (setq skip-filtered-count (1+ skip-filtered-count)))
2542 ;; Optionally ignore invisible matches.
2543 ((not (or (eq search-invisible t)
2544 ;; Don't open overlays for automatic replacements.
2545 (and (not query-flag) search-invisible)
2546 ;; Open hidden overlays for interactive replacements.
2547 (not (isearch-range-invisible
2548 (nth 0 real-match-data) (nth 1 real-match-data)))))
2549 (setq skip-invisible-count (1+ skip-invisible-count)))
2551 ;; Calculate the replacement string, if necessary.
2553 (set-match-data real-match-data)
2554 (setq next-replacement
2555 (funcall (car replacements) (cdr replacements)
2557 (if (not query-flag)
2559 (unless (or literal noedit)
2561 (nth 0 real-match-data) (nth 1 real-match-data)
2562 start end search-string
2563 regexp-flag delimited-flag case-fold-search backward))
2565 (replace-match-maybe-edit
2566 next-replacement nocasify literal
2567 noedit real-match-data backward)
2568 replace-count (1+ replace-count)))
2570 (let (done replaced key def)
2571 ;; Loop reading commands until one of them sets done,
2572 ;; which means it has finished handling this
2573 ;; occurrence. Any command that sets `done' should
2574 ;; leave behind proper match data for the stack.
2575 ;; Commands not setting `done' need to adjust
2576 ;; `real-match-data'.
2578 (set-match-data real-match-data)
2579 (run-hooks 'replace-update-post-hook) ; Before `replace-highlight'.
2581 (match-beginning 0) (match-end 0)
2582 start end search-string
2583 regexp-flag delimited-flag case-fold-search backward)
2584 ;; Obtain the matched groups: needed only when
2585 ;; regexp-flag non nil.
2586 (when (and last-was-undo regexp-flag)
2587 (setq last-was-undo nil
2590 (goto-char (match-beginning 0))
2591 (looking-at search-string)
2592 (match-data t real-match-data))))
2593 ;; Matched string and next-replacement-replaced
2595 (setq search-string-replaced (buffer-substring-no-properties
2598 next-replacement-replaced
2599 (query-replace-descr
2601 (set-match-data real-match-data)
2602 (match-substitute-replacement
2603 next-replacement nocasify literal))))
2604 ;; Bind message-log-max so we don't fill up the
2605 ;; message log with a bunch of identical messages.
2606 (let ((message-log-max nil)
2607 (replacement-presentation
2608 (if query-replace-show-replacement
2610 (set-match-data real-match-data)
2611 (match-substitute-replacement next-replacement
2615 (query-replace-descr from-string)
2616 (query-replace-descr replacement-presentation)))
2617 (setq key (read-event))
2618 ;; Necessary in case something happens during
2619 ;; read-event that clobbers the match data.
2620 (set-match-data real-match-data)
2621 (setq key (vector key))
2622 (setq def (lookup-key map key))
2623 ;; Restore the match data while we process the command.
2624 (cond ((eq def 'help)
2625 (with-output-to-temp-buffer "*Help*"
2627 (concat "Query replacing "
2628 (if backward "backward " "")
2630 (or (and (symbolp delimited-flag)
2632 'isearch-message-prefix))
2634 (if regexp-flag "regexp " "")
2635 from-string " with "
2636 next-replacement ".\n\n"
2637 (substitute-command-keys
2638 query-replace-help)))
2639 (with-current-buffer standard-output
2642 (setq keep-going nil)
2644 ((eq def 'exit-current)
2645 (setq multi-buffer t keep-going nil done t))
2648 (let ((elt (pop stack)))
2649 (goto-char (nth 0 elt))
2650 (setq replaced (nth 1 elt)
2655 (message "No previous match")
2656 (ding 'no-terminate)
2658 ((or (eq def 'undo) (eq def 'undo-all))
2661 (message "Nothing to undo")
2662 (ding 'no-terminate)
2665 (stack-len (length stack))
2666 (num-replacements 0)
2667 (nocasify t) ; Undo must preserve case (Bug#31073).
2670 (while (and (< stack-idx stack-len)
2672 (or (null replaced) last-was-act-and-show))
2673 (let* ((elt (nth stack-idx stack)))
2675 stack-idx (1+ stack-idx)
2676 replaced (nth 1 elt)
2677 ;; Bind swapped values
2678 ;; (search-string <--> replacement)
2679 search-string (nth (if replaced 4 3) elt)
2680 next-replacement (nth (if replaced 3 4) elt)
2681 search-string-replaced search-string
2682 next-replacement-replaced next-replacement
2683 last-was-act-and-show nil)
2685 (when (and (= stack-idx stack-len)
2686 (and (null replaced) (not last-was-act-and-show))
2687 (zerop num-replacements))
2688 (message "Nothing to undo")
2689 (ding 'no-terminate)
2693 (setq stack (nthcdr stack-idx stack))
2694 (goto-char (nth 0 elt))
2695 (set-match-data (nth 2 elt))
2696 (setq real-match-data
2698 (goto-char (match-beginning 0))
2699 (looking-at search-string)
2700 (match-data t (nth 2 elt)))
2702 (replace-match-maybe-edit
2703 next-replacement nocasify literal
2704 noedit real-match-data backward)
2705 replace-count (1- replace-count)
2708 (goto-char (match-beginning 0))
2709 (looking-at next-replacement)
2710 (match-data t (nth 2 elt))))
2711 ;; Set replaced nil to keep in loop
2712 (when (eq def 'undo-all)
2714 stack-len (- stack-len stack-idx)
2717 (1+ num-replacements))))))
2718 (when (and (eq def 'undo-all)
2719 (null (zerop num-replacements)))
2720 (message "Undid %d %s" num-replacements
2721 (if (= num-replacements 1)
2724 (ding 'no-terminate)
2726 (setq replaced nil last-was-undo t last-was-act-and-show nil)))
2730 (replace-match-maybe-edit
2731 next-replacement nocasify literal
2732 noedit real-match-data backward)
2733 replace-count (1+ replace-count)))
2734 (setq done t replaced t update-stack (not last-was-act-and-show)))
2735 ((eq def 'act-and-exit)
2738 (replace-match-maybe-edit
2739 next-replacement nocasify literal
2740 noedit real-match-data backward)
2741 replace-count (1+ replace-count)))
2742 (setq keep-going nil)
2743 (setq done t replaced t))
2744 ((eq def 'act-and-show)
2747 (replace-match-maybe-edit
2748 next-replacement nocasify literal
2749 noedit real-match-data backward)
2750 replace-count (1+ replace-count)
2751 real-match-data (replace-match-data
2753 replaced t last-was-act-and-show t)
2754 (replace--push-stack
2756 search-string-replaced
2757 next-replacement-replaced stack)))
2758 ((or (eq def 'automatic) (eq def 'automatic-all))
2761 (replace-match-maybe-edit
2762 next-replacement nocasify literal
2763 noedit real-match-data backward)
2764 replace-count (1+ replace-count)))
2765 (setq done t query-flag nil replaced t)
2766 (if (eq def 'automatic-all) (setq multi-buffer t)))
2768 (setq done t update-stack (not last-was-act-and-show)))
2770 ;; `this-command' has the value `query-replace',
2771 ;; so we need to bind it to `recenter-top-bottom'
2772 ;; to allow it to detect a sequence of `C-l'.
2773 (let ((this-command 'recenter-top-bottom)
2774 (last-command 'recenter-top-bottom))
2775 (recenter-top-bottom)))
2777 (let ((opos (point-marker)))
2778 (setq real-match-data (replace-match-data
2781 (goto-char (match-beginning 0))
2783 (save-window-excursion
2786 (set-marker opos nil))
2787 ;; Before we make the replacement,
2788 ;; decide whether the search string
2789 ;; can match again just after this match.
2790 (if (and regexp-flag nonempty-match)
2791 (setq match-again (and (looking-at search-string)
2793 ;; Edit replacement.
2794 ((eq def 'edit-replacement)
2795 (setq real-match-data (replace-match-data
2799 (read-string "Edit replacement string: "
2803 (set-match-data real-match-data)
2805 (replace-match-maybe-edit
2806 next-replacement nocasify literal noedit
2807 real-match-data backward)
2809 (setq next-replacement-replaced next-replacement))
2812 ((eq def 'delete-and-edit)
2813 (replace-match "" t t)
2814 (setq real-match-data (replace-match-data
2815 nil real-match-data))
2816 (replace-dehighlight)
2817 (save-excursion (recursive-edit))
2819 ;; Note: we do not need to treat `exit-prefix'
2820 ;; specially here, since we reread
2821 ;; any unrecognized character.
2823 (setq this-command 'mode-exited)
2824 (setq keep-going nil)
2825 (setq unread-command-events
2826 (append (listify-key-sequence key)
2827 unread-command-events))
2829 (when query-replace-lazy-highlight
2830 ;; Force lazy rehighlighting only after replacements.
2831 (if (not (memq def '(skip backup)))
2832 (setq isearch-lazy-highlight-last-string nil)))
2833 (unless (eq def 'recenter)
2834 ;; Reset recenter cycling order to initial position.
2835 (setq recenter-last-op nil)))
2836 ;; Record previous position for ^ when we move on.
2837 ;; Change markers to numbers in the match data
2838 ;; since lots of markers slow down editing.
2840 (replace--push-stack
2842 search-string-replaced
2843 next-replacement-replaced stack))
2844 (setq next-replacement-replaced nil
2845 search-string-replaced nil
2846 last-was-act-and-show nil))))))
2847 (replace-dehighlight))
2848 (or unread-command-events
2849 (message "Replaced %d occurrence%s%s"
2851 (if (= replace-count 1) "" "s")
2852 (if (> (+ skip-read-only-count
2854 skip-invisible-count) 0)
2855 (format " (skipped %s)"
2859 (if (> skip-read-only-count 0)
2860 (format "%s read-only"
2861 skip-read-only-count))
2862 (if (> skip-invisible-count 0)
2863 (format "%s invisible"
2864 skip-invisible-count))
2865 (if (> skip-filtered-count 0)
2866 (format "%s filtered out"
2867 skip-filtered-count))))
2870 (or (and keep-going stack) multi-buffer)))
2874 ;;; replace.el ends here