1 ;;; replace.el --- replace commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2017 Free
4 ;; Software Foundation, Inc.
6 ;; Maintainer: emacs-devel@gnu.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; This package supplies the string and regular-expression replace functions
27 ;; documented in the Emacs user's manual.
31 (eval-when-compile (require 'cl-lib
))
33 (defcustom case-replace t
34 "Non-nil means `query-replace' should preserve case in replacements."
38 (defcustom replace-char-fold nil
39 "Non-nil means replacement commands should do character folding in matches.
40 This means, for instance, that \\=' will match a large variety of
42 This variable affects `query-replace' and `replace-string', but not
48 (defcustom replace-lax-whitespace nil
49 "Non-nil means `query-replace' matches a sequence of whitespace chars.
50 When you enter a space or spaces in the strings to be replaced,
51 it will match any sequence matched by the regexp `search-whitespace-regexp'."
56 (defcustom replace-regexp-lax-whitespace nil
57 "Non-nil means `query-replace-regexp' matches a sequence of whitespace chars.
58 When you enter a space or spaces in the regexps to be replaced,
59 it will match any sequence matched by the regexp `search-whitespace-regexp'."
64 (defvar query-replace-history nil
65 "Default history list for query-replace commands.
66 See `query-replace-from-history-variable' and
67 `query-replace-to-history-variable'.")
69 (defvar query-replace-defaults nil
70 "Default values of FROM-STRING and TO-STRING for `query-replace'.
71 This is a list of cons cells (FROM-STRING . TO-STRING), or nil
72 if there are no default values.")
74 (defvar query-replace-interactive nil
75 "Non-nil means `query-replace' uses the last search string.
76 That becomes the \"string to replace\".")
77 (make-obsolete-variable 'query-replace-interactive
78 "use `M-n' to pull the last incremental search string
79 to the minibuffer that reads the string to replace, or invoke replacements
80 from Isearch by using a key sequence like `C-s C-s M-%'." "24.3")
82 (defcustom query-replace-from-to-separator
83 (propertize (if (char-displayable-p ?→
) " → " " -> ")
84 'face
'minibuffer-prompt
)
85 "String that separates FROM and TO in the history of replacement pairs."
86 ;; Avoids error when attempt to autoload char-displayable-p fails
87 ;; while preparing to dump, also stops customize-rogue listing this.
88 :initialize
'custom-initialize-delay
90 :type
'(choice string
(sexp :tag
"Display specification"))
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 (mapconcat 'isearch-text-char-description string
""))
152 (defun query-replace--split-string (string)
153 "Split string STRING at a character with property `separator'"
154 (let* ((length (length string
))
155 (split-pos (text-property-any 0 length
'separator t string
)))
157 (substring-no-properties string
)
158 (cl-assert (not (text-property-any (1+ split-pos
) length
'separator t string
)))
159 (cons (substring-no-properties string
0 split-pos
)
160 (substring-no-properties string
(1+ split-pos
) length
)))))
162 (defun query-replace-read-from (prompt regexp-flag
)
163 "Query and return the `from' argument of a query-replace operation.
164 The return value can also be a pair (FROM . TO) indicating that the user
165 wants to replace FROM with TO."
166 (if query-replace-interactive
167 (car (if regexp-flag regexp-search-ring search-ring
))
168 ;; Reevaluating will check char-displayable-p that is
169 ;; unavailable while preparing to dump.
170 (custom-reevaluate-setting 'query-replace-from-to-separator
)
171 (let* ((history-add-new-input nil
)
173 (when query-replace-from-to-separator
175 'display query-replace-from-to-separator
180 (mapcar (lambda (from-to)
181 (concat (query-replace-descr (car from-to
))
183 (query-replace-descr (cdr from-to
))))
184 query-replace-defaults
))
185 (symbol-value query-replace-from-history-variable
)))
186 (minibuffer-allow-text-properties t
) ; separator uses text-properties
188 (if (and query-replace-defaults separator
)
189 (format "%s (default %s): " prompt
(car minibuffer-history
))
190 (format "%s: " prompt
)))
192 ;; The save-excursion here is in case the user marks and copies
193 ;; a region in order to specify the minibuffer input.
194 ;; That should not clobber the region for the query-replace itself.
196 (minibuffer-with-setup-hook
198 (setq-local text-property-default-nonsticky
199 (cons '(separator . t
) text-property-default-nonsticky
)))
201 (read-regexp prompt nil
'minibuffer-history
)
202 (read-from-minibuffer
203 prompt nil nil nil nil
204 (car (if regexp-flag regexp-search-ring search-ring
)) t
)))))
206 (if (and (zerop (length from
)) query-replace-defaults
)
207 (cons (caar query-replace-defaults
)
208 (query-replace-compile-replacement
209 (cdar query-replace-defaults
) regexp-flag
))
210 (setq from
(query-replace--split-string from
))
211 (when (consp from
) (setq to
(cdr from
) from
(car from
)))
212 (add-to-history query-replace-from-history-variable from nil t
)
213 ;; Warn if user types \n or \t, but don't reject the input.
215 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
216 (let ((match (match-string 3 from
)))
218 ((string= match
"\\n")
219 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
220 ((string= match
"\\t")
221 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
225 (add-to-history query-replace-to-history-variable to nil t
)
226 (add-to-history 'query-replace-defaults
(cons from to
) nil t
)
227 (cons from
(query-replace-compile-replacement to regexp-flag
)))))))
229 (defun query-replace-compile-replacement (to regexp-flag
)
230 "Maybe convert a regexp replacement TO to Lisp.
231 Returns a list suitable for `perform-replace' if necessary,
232 the original string if not."
234 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
))
238 (setq pos
(match-end 0))
239 (push (substring to
0 (- pos
2)) list
)
240 (setq char
(aref to
(1- pos
))
241 to
(substring to pos
))
243 (push '(number-to-string replace-count
) list
))
245 (setq pos
(read-from-string to
))
246 (push `(replace-quote ,(car pos
)) list
)
248 ;; Swallow a space after a symbol
249 ;; if there is a space.
250 (if (and (or (symbolp (car pos
))
251 ;; Swallow a space after 'foo
252 ;; but not after (quote foo).
253 (and (eq (car-safe (car pos
)) 'quote
)
254 (not (= ?\
( (aref to
0)))))
255 (eq (string-match " " to
(cdr pos
))
259 (setq to
(substring to end
)))))
260 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
)))
261 (setq to
(nreverse (delete "" (cons to list
))))
262 (replace-match-string-symbols to
)
263 (cons 'replace-eval-replacement
270 (defun query-replace-read-to (from prompt regexp-flag
)
271 "Query and return the `to' argument of a query-replace operation."
272 (query-replace-compile-replacement
274 (let* ((history-add-new-input nil
)
275 (to (read-from-minibuffer
276 (format "%s %s with: " prompt
(query-replace-descr from
))
278 query-replace-to-history-variable from t
)))
279 (add-to-history query-replace-to-history-variable to nil t
)
280 (add-to-history 'query-replace-defaults
(cons from to
) nil t
)
284 (defun query-replace-read-args (prompt regexp-flag
&optional noerror
)
286 (barf-if-buffer-read-only))
287 (let* ((from (query-replace-read-from prompt regexp-flag
))
288 (to (if (consp from
) (prog1 (cdr from
) (setq from
(car from
)))
289 (query-replace-read-to from prompt regexp-flag
))))
291 (and current-prefix-arg
(not (eq current-prefix-arg
'-
)))
292 (and current-prefix-arg
(eq current-prefix-arg
'-
)))))
294 (defun query-replace (from-string to-string
&optional delimited start end backward region-noncontiguous-p
)
295 "Replace some occurrences of FROM-STRING with TO-STRING.
296 As each match is found, the user must type a character saying
297 what to do with it. For directions, type \\[help-command] at that time.
299 In Transient Mark mode, if the mark is active, operate on the contents
300 of the region. Otherwise, operate from point to the end of the buffer's
303 In interactive use, the prefix arg (non-nil DELIMITED in
304 non-interactive use), means replace only matches surrounded by
305 word boundaries. A negative prefix arg means replace backward.
307 Use \\<minibuffer-local-map>\\[next-history-element] \
308 to pull the last incremental search string to the minibuffer
309 that reads FROM-STRING, or invoke replacements from
310 incremental search with a key sequence like `C-s C-s M-%'
311 to use its current search string as the string to replace.
313 Matching is independent of case if `case-fold-search' is non-nil and
314 FROM-STRING has no uppercase letters. Replacement transfers the case
315 pattern of the old text to the new text, if `case-replace' and
316 `case-fold-search' are non-nil and FROM-STRING has no uppercase
317 letters. (Transferring the case pattern means that if the old text
318 matched is all caps, or capitalized, then its replacement is upcased
321 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
322 ignore hidden matches if `search-invisible' is nil, and ignore more
323 matches using `isearch-filter-predicate'.
325 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
326 to be replaced will match a sequence of whitespace chars defined by the
327 regexp in `search-whitespace-regexp'.
329 If `replace-char-fold' is non-nil, matching uses character folding,
330 i.e. it ignores diacritics and other differences between equivalent
333 Fourth and fifth arg START and END specify the region to operate on.
335 To customize possible responses, change the bindings in `query-replace-map'."
338 (query-replace-read-args
339 (concat "Query replace"
340 (if current-prefix-arg
341 (if (eq current-prefix-arg
'-
) " backward" " word")
343 (if (use-region-p) " in region" ""))
345 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
346 ;; These are done separately here
347 ;; so that command-history will record these expressions
348 ;; rather than the values they had this time.
349 (if (use-region-p) (region-beginning))
350 (if (use-region-p) (region-end))
352 (if (use-region-p) (region-noncontiguous-p)))))
353 (perform-replace from-string to-string t nil delimited nil nil start end backward region-noncontiguous-p
))
355 (define-key esc-map
"%" 'query-replace
)
357 (defun query-replace-regexp (regexp to-string
&optional delimited start end backward region-noncontiguous-p
)
358 "Replace some things after point matching REGEXP with TO-STRING.
359 As each match is found, the user must type a character saying
360 what to do with it. For directions, type \\[help-command] at that time.
362 In Transient Mark mode, if the mark is active, operate on the contents
363 of the region. Otherwise, operate from point to the end of the buffer's
366 Use \\<minibuffer-local-map>\\[next-history-element] \
367 to pull the last incremental search regexp to the minibuffer
368 that reads REGEXP, or invoke replacements from
369 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
370 to use its current search regexp as the regexp to replace.
372 Matching is independent of case if `case-fold-search' is non-nil and
373 REGEXP has no uppercase letters. Replacement transfers the case
374 pattern of the old text to the new text, if `case-replace' and
375 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
376 \(Transferring the case pattern means that if the old text matched is
377 all caps, or capitalized, then its replacement is upcased or
380 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
381 ignore hidden matches if `search-invisible' is nil, and ignore more
382 matches using `isearch-filter-predicate'.
384 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
385 to be replaced will match a sequence of whitespace chars defined by the
386 regexp in `search-whitespace-regexp'.
388 This function is not affected by `replace-char-fold'.
390 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
391 only matches surrounded by word boundaries. A negative prefix arg means
394 Fourth and fifth arg START and END specify the region to operate on.
396 In TO-STRING, `\\&' or `\\0' stands for whatever matched the whole of
397 REGEXP, and `\\=\\N' (where N is a digit) stands for whatever matched
398 the Nth `\\(...\\)' (1-based) in REGEXP. The `\\(...\\)' groups are
400 `\\?' lets you edit the replacement text in the minibuffer
401 at the given position for each replacement.
403 In interactive calls, the replacement text can contain `\\,'
404 followed by a Lisp expression. Each
405 replacement evaluates that expression to compute the replacement
406 string. Inside of that expression, `\\&' is a string denoting the
407 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
408 for the whole or a partial match converted to a number with
409 `string-to-number', and `\\#' itself for the number of replacements
410 done so far (starting with zero).
412 If the replacement expression is a symbol, write a space after it
413 to terminate it. One space there, if any, will be discarded.
415 When using those Lisp features interactively in the replacement
416 text, TO-STRING is actually made a list instead of a string.
417 Use \\[repeat-complex-command] after this command for details."
420 (query-replace-read-args
421 (concat "Query replace"
422 (if current-prefix-arg
423 (if (eq current-prefix-arg
'-
) " backward" " word")
426 (if (use-region-p) " in region" ""))
428 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
429 ;; These are done separately here
430 ;; so that command-history will record these expressions
431 ;; rather than the values they had this time.
432 (if (use-region-p) (region-beginning))
433 (if (use-region-p) (region-end))
435 (if (use-region-p) (region-noncontiguous-p)))))
436 (perform-replace regexp to-string t t delimited nil nil start end backward region-noncontiguous-p
))
438 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
440 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
441 "Replace some things after point matching REGEXP with the result of TO-EXPR.
443 Interactive use of this function is deprecated in favor of the
444 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
445 using `search-forward-regexp' and `replace-match' is preferred.
447 As each match is found, the user must type a character saying
448 what to do with it. For directions, type \\[help-command] at that time.
450 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
451 reference `replace-count' to get the number of replacements already made.
452 If the result of TO-EXPR is not a string, it is converted to one using
453 `prin1-to-string' with the NOESCAPE argument (which see).
455 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
456 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
457 N is a digit) to stand for whatever matched the Nth `\\(...\\)' (1-based)
460 Use `\\#&' or `\\#N' if you want a number instead of a string.
461 In interactive use, `\\#' in itself stands for `replace-count'.
463 In Transient Mark mode, if the mark is active, operate on the contents
464 of the region. Otherwise, operate from point to the end of the buffer's
467 Use \\<minibuffer-local-map>\\[next-history-element] \
468 to pull the last incremental search regexp to the minibuffer
471 Preserves case in each replacement if `case-replace' and `case-fold-search'
472 are non-nil and REGEXP has no uppercase letters.
474 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
475 ignore hidden matches if `search-invisible' is nil, and ignore more
476 matches using `isearch-filter-predicate'.
478 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
479 to be replaced will match a sequence of whitespace chars defined by the
480 regexp in `search-whitespace-regexp'.
482 This function is not affected by `replace-char-fold'.
484 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
485 only matches that are surrounded by word boundaries.
486 Fourth and fifth arg START and END specify the region to operate on."
487 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
488 for interactive calls, and `search-forward-regexp'/`replace-match'
489 for Lisp calls." "22.1"))
492 (barf-if-buffer-read-only)
494 ;; Let-bind the history var to disable the "foo -> bar"
495 ;; default. Maybe we shouldn't disable this default, but
496 ;; for now I'll leave it off. --Stef
497 (let ((query-replace-defaults nil
))
498 (query-replace-read-from "Query replace regexp" t
)))
499 (to (list (read-from-minibuffer
500 (format "Query replace regexp %s with eval: "
501 (query-replace-descr from
))
502 nil nil t query-replace-to-history-variable from t
))))
503 ;; We make TO a list because replace-match-string-symbols requires one,
504 ;; and the user might enter a single token.
505 (replace-match-string-symbols to
)
506 (list from
(car to
) current-prefix-arg
507 (if (use-region-p) (region-beginning))
508 (if (use-region-p) (region-end))))))
509 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
510 t
'literal delimited nil nil start end
))
512 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
513 "Replace some matches for REGEXP with various strings, in rotation.
514 The second argument TO-STRINGS contains the replacement strings, separated
515 by spaces. This command works like `query-replace-regexp' except that
516 each successive replacement uses the next successive replacement string,
517 wrapping around from the last such string to the first.
519 In Transient Mark mode, if the mark is active, operate on the contents
520 of the region. Otherwise, operate from point to the end of the buffer's
523 Non-interactively, TO-STRINGS may be a list of replacement strings.
525 Interactively, reads the regexp using `read-regexp'.
526 Use \\<minibuffer-local-map>\\[next-history-element] \
527 to pull the last incremental search regexp to the minibuffer
530 A prefix argument N says to use each replacement string N times
531 before rotating to the next.
532 Fourth and fifth arg START and END specify the region to operate on."
534 (let* ((from (read-regexp "Map query replace (regexp): " nil
535 query-replace-from-history-variable
))
536 (to (read-from-minibuffer
537 (format "Query replace %s with (space-separated strings): "
538 (query-replace-descr from
))
540 query-replace-to-history-variable from t
)))
542 (and current-prefix-arg
543 (prefix-numeric-value current-prefix-arg
))
544 (if (use-region-p) (region-beginning))
545 (if (use-region-p) (region-end)))))
547 (if (listp to-strings
)
548 (setq replacements to-strings
)
549 (while (/= (length to-strings
) 0)
550 (if (string-match " " to-strings
)
553 (list (substring to-strings
0
554 (string-match " " to-strings
))))
555 to-strings
(substring to-strings
556 (1+ (string-match " " to-strings
))))
557 (setq replacements
(append replacements
(list to-strings
))
559 (perform-replace regexp replacements t t nil n nil start end
)))
561 (defun replace-string (from-string to-string
&optional delimited start end backward
)
562 "Replace occurrences of FROM-STRING with TO-STRING.
563 Preserve case in each match if `case-replace' and `case-fold-search'
564 are non-nil and FROM-STRING has no uppercase letters.
565 \(Preserving case means that if the string matched is all caps, or capitalized,
566 then its replacement is upcased or capitalized.)
568 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
569 ignore hidden matches if `search-invisible' is nil, and ignore more
570 matches using `isearch-filter-predicate'.
572 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
573 to be replaced will match a sequence of whitespace chars defined by the
574 regexp in `search-whitespace-regexp'.
576 If `replace-char-fold' is non-nil, matching uses character folding,
577 i.e. it ignores diacritics and other differences between equivalent
580 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
581 only matches surrounded by word boundaries. A negative prefix arg means
584 Operates on the region between START and END (if both are nil, from point
585 to the end of the buffer). Interactively, if Transient Mark mode is
586 enabled and the mark is active, operates on the contents of the region;
587 otherwise from point to the end of the buffer's accessible portion.
589 Use \\<minibuffer-local-map>\\[next-history-element] \
590 to pull the last incremental search string to the minibuffer
591 that reads FROM-STRING.
593 This function is usually the wrong thing to use in a Lisp program.
594 What you probably want is a loop like this:
595 (while (search-forward FROM-STRING nil t)
596 (replace-match TO-STRING nil t))
597 which will run faster and will not set the mark or print anything.
598 \(You may need a more complex loop if FROM-STRING can match the null string
599 and TO-STRING is also null.)"
600 (declare (interactive-only
601 "use `search-forward' and `replace-match' instead."))
604 (query-replace-read-args
606 (if current-prefix-arg
607 (if (eq current-prefix-arg
'-
) " backward" " word")
610 (if (use-region-p) " in region" ""))
612 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
613 (if (use-region-p) (region-beginning))
614 (if (use-region-p) (region-end))
616 (perform-replace from-string to-string nil nil delimited nil nil start end backward
))
618 (defun replace-regexp (regexp to-string
&optional delimited start end backward
)
619 "Replace things after point matching REGEXP with TO-STRING.
620 Preserve case in each match if `case-replace' and `case-fold-search'
621 are non-nil and REGEXP has no uppercase letters.
623 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
624 ignore hidden matches if `search-invisible' is nil, and ignore more
625 matches using `isearch-filter-predicate'.
627 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
628 to be replaced will match a sequence of whitespace chars defined by the
629 regexp in `search-whitespace-regexp'.
631 This function is not affected by `replace-char-fold'
633 In Transient Mark mode, if the mark is active, operate on the contents
634 of the region. Otherwise, operate from point to the end of the buffer's
637 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
638 only matches surrounded by word boundaries. A negative prefix arg means
641 Fourth and fifth arg START and END specify the region to operate on.
643 In TO-STRING, `\\&' or `\\0' stands for whatever matched the whole of
644 REGEXP, and `\\=\\N' (where N is a digit) stands for
645 whatever matched the Nth `\\(...\\)' (1-based) in REGEXP.
646 `\\?' lets you edit the replacement text in the minibuffer
647 at the given position for each replacement.
649 In interactive calls, the replacement text may contain `\\,'
650 followed by a Lisp expression used as part of the replacement
651 text. Inside of that expression, `\\&' is a string denoting the
652 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
653 numeric values from `string-to-number', and `\\#' itself for
654 `replace-count', the number of replacements occurred so far.
656 If your Lisp expression is an identifier and the next letter in
657 the replacement string would be interpreted as part of it, you
658 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
659 for this particular case you may also enter `\\#' in the
660 replacement text directly.
662 When using those Lisp features interactively in the replacement
663 text, TO-STRING is actually made a list instead of a string.
664 Use \\[repeat-complex-command] after this command for details.
666 Use \\<minibuffer-local-map>\\[next-history-element] \
667 to pull the last incremental search regexp to the minibuffer
670 This function is usually the wrong thing to use in a Lisp program.
671 What you probably want is a loop like this:
672 (while (re-search-forward REGEXP nil t)
673 (replace-match TO-STRING nil nil))
674 which will run faster and will not set the mark or print anything."
675 (declare (interactive-only
676 "use `re-search-forward' and `replace-match' instead."))
679 (query-replace-read-args
681 (if current-prefix-arg
682 (if (eq current-prefix-arg
'-
) " backward" " word")
685 (if (use-region-p) " in region" ""))
687 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
688 (if (use-region-p) (region-beginning))
689 (if (use-region-p) (region-end))
691 (perform-replace regexp to-string nil t delimited nil nil start end backward
))
694 (defvar regexp-history nil
695 "History list for some commands that read regular expressions.
697 Maximum length of the history list is determined by the value
698 of `history-length', which see.")
700 (defvar occur-collect-regexp-history
'("\\1")
701 "History of regexp for occur's collect operation")
703 (defcustom read-regexp-defaults-function nil
704 "Function that provides default regexp(s) for `read-regexp'.
705 This function should take no arguments and return one of: nil, a
706 regexp, or a list of regexps. Interactively, `read-regexp' uses
707 the return value of this function for its DEFAULT argument.
709 As an example, set this variable to `find-tag-default-as-regexp'
710 to default to the symbol at point.
712 To provide different default regexps for different commands,
713 the function that you set this to can check `this-command'."
715 (const :tag
"No default regexp reading function" nil
)
716 (const :tag
"Latest regexp history" regexp-history-last
)
717 (function-item :tag
"Tag at point"
719 (function-item :tag
"Tag at point as regexp"
720 find-tag-default-as-regexp
)
721 (function-item :tag
"Tag at point as symbol regexp"
722 find-tag-default-as-symbol-regexp
)
723 (function :tag
"Your choice of function"))
727 (defun read-regexp-suggestions ()
728 "Return a list of standard suggestions for `read-regexp'.
729 By default, the list includes the tag at point, the last isearch regexp,
730 the last isearch string, and the last replacement regexp. `read-regexp'
731 appends the list returned by this function to the end of values available
732 via \\<minibuffer-local-map>\\[next-history-element]."
734 (find-tag-default-as-regexp)
735 (find-tag-default-as-symbol-regexp)
736 (car regexp-search-ring
)
737 (regexp-quote (or (car search-ring
) ""))
738 (car (symbol-value query-replace-from-history-variable
))))
740 (defun read-regexp (prompt &optional defaults history
)
741 "Read and return a regular expression as a string.
742 Prompt with the string PROMPT. If PROMPT ends in \":\" (followed by
743 optional whitespace), use it as-is. Otherwise, add \": \" to the end,
744 possibly preceded by the default result (see below).
746 The optional argument DEFAULTS can be either: nil, a string, a list
747 of strings, or a symbol. We use DEFAULTS to construct the default
748 return value in case of empty input.
750 If DEFAULTS is a string, we use it as-is.
752 If DEFAULTS is a list of strings, the first element is the
753 default return value, but all the elements are accessible
754 using the history command \\<minibuffer-local-map>\\[next-history-element].
756 If DEFAULTS is a non-nil symbol, then if `read-regexp-defaults-function'
757 is non-nil, we use that in place of DEFAULTS in the following:
758 If DEFAULTS is the symbol `regexp-history-last', we use the first
759 element of HISTORY (if specified) or `regexp-history'.
760 If DEFAULTS is a function, we call it with no arguments and use
761 what it returns, which should be either nil, a string, or a list of strings.
763 We append the standard values from `read-regexp-suggestions' to DEFAULTS
766 If the first element of DEFAULTS is non-nil (and if PROMPT does not end
767 in \":\", followed by optional whitespace), we add it to the prompt.
769 The optional argument HISTORY is a symbol to use for the history list.
770 If nil, uses `regexp-history'."
772 (if (and defaults
(symbolp defaults
))
774 ((eq (or read-regexp-defaults-function defaults
)
775 'regexp-history-last
)
776 (car (symbol-value (or history
'regexp-history
))))
777 ((functionp (or read-regexp-defaults-function defaults
))
778 (funcall (or read-regexp-defaults-function defaults
))))
780 (default (if (consp defaults
) (car defaults
) defaults
))
781 (suggestions (if (listp defaults
) defaults
(list defaults
)))
782 (suggestions (append suggestions
(read-regexp-suggestions)))
783 (suggestions (delete-dups (delq nil
(delete "" suggestions
))))
784 ;; Do not automatically add default to the history for empty input.
785 (history-add-new-input nil
)
786 (input (read-from-minibuffer
787 (cond ((string-match-p ":[ \t]*\\'" prompt
)
789 ((and default
(> (length default
) 0))
790 (format "%s (default %s): " prompt
791 (query-replace-descr default
)))
793 (format "%s: " prompt
)))
794 nil nil nil
(or history
'regexp-history
) suggestions t
)))
796 ;; Return the default value when the user enters empty input.
797 (prog1 (or default input
)
799 (add-to-history (or history
'regexp-history
) default
)))
800 ;; Otherwise, add non-empty input to the history and return input.
802 (add-to-history (or history
'regexp-history
) input
)))))
805 (defalias 'delete-non-matching-lines
'keep-lines
)
806 (defalias 'delete-matching-lines
'flush-lines
)
807 (defalias 'count-matches
'how-many
)
810 (defun keep-lines-read-args (prompt)
811 "Read arguments for `keep-lines' and friends.
812 Prompt for a regexp with PROMPT.
813 Value is a list, (REGEXP)."
814 (list (read-regexp prompt
) nil nil t
))
816 (defun keep-lines (regexp &optional rstart rend interactive
)
817 "Delete all lines except those containing matches for REGEXP.
818 A match split across lines preserves all the lines it lies in.
819 When called from Lisp (and usually interactively as well, see below)
820 applies to all lines starting after point.
822 If REGEXP contains upper case characters (excluding those preceded by `\\')
823 and `search-upper-case' is non-nil, the matching is case-sensitive.
825 Second and third arg RSTART and REND specify the region to operate on.
826 This command operates on (the accessible part of) all lines whose
827 accessible part is entirely contained in the region determined by RSTART
828 and REND. (A newline ending a line counts as part of that line.)
830 Interactively, in Transient Mark mode when the mark is active, operate
831 on all lines whose accessible part is entirely contained in the region.
832 Otherwise, the command applies to all lines starting after point.
833 When calling this function from Lisp, you can pretend that it was
834 called interactively by passing a non-nil INTERACTIVE argument.
836 This function starts looking for the next match from the end of
837 the previous match. Hence, it ignores matches that overlap
838 a previously found match."
842 (barf-if-buffer-read-only)
843 (keep-lines-read-args "Keep lines containing match for regexp")))
846 (goto-char (min rstart rend
))
850 (goto-char (max rstart rend
))
851 (unless (or (bolp) (eobp))
854 (if (and interactive
(use-region-p))
855 (setq rstart
(region-beginning)
857 (goto-char (region-end))
858 (unless (or (bolp) (eobp))
862 rend
(point-max-marker)))
865 (or (bolp) (forward-line 1))
866 (let ((start (point))
868 (if (and case-fold-search search-upper-case
)
869 (isearch-no-upper-case-p regexp t
)
871 (while (< (point) rend
)
872 ;; Start is first char not preserved by previous match.
873 (if (not (re-search-forward regexp rend
'move
))
874 (delete-region start rend
)
875 (let ((end (save-excursion (goto-char (match-beginning 0))
878 ;; Now end is first char preserved by the new match.
880 (delete-region start end
))))
882 (setq start
(save-excursion (forward-line 1) (point)))
883 ;; If the match was empty, avoid matching again at same place.
884 (and (< (point) rend
)
885 (= (match-beginning 0) (match-end 0))
887 (set-marker rend nil
)
891 (defun flush-lines (regexp &optional rstart rend interactive
)
892 "Delete lines containing matches for REGEXP.
893 When called from Lisp (and usually when called interactively as
894 well, see below), applies to the part of the buffer after point.
895 The line point is in is deleted if and only if it contains a
896 match for regexp starting after point.
898 If REGEXP contains upper case characters (excluding those preceded by `\\')
899 and `search-upper-case' is non-nil, the matching is case-sensitive.
901 Second and third arg RSTART and REND specify the region to operate on.
902 Lines partially contained in this region are deleted if and only if
903 they contain a match entirely contained in it.
905 Interactively, in Transient Mark mode when the mark is active, operate
906 on the contents of the region. Otherwise, operate from point to the
907 end of (the accessible portion of) the buffer. When calling this function
908 from Lisp, you can pretend that it was called interactively by passing
909 a non-nil INTERACTIVE argument.
911 If a match is split across lines, all the lines it lies in are deleted.
912 They are deleted _before_ looking for the next match. Hence, a match
913 starting on the same line at which another match ended is ignored."
917 (barf-if-buffer-read-only)
918 (keep-lines-read-args "Flush lines containing match for regexp")))
921 (goto-char (min rstart rend
))
922 (setq rend
(copy-marker (max rstart rend
))))
923 (if (and interactive
(use-region-p))
924 (setq rstart
(region-beginning)
925 rend
(copy-marker (region-end)))
927 rend
(point-max-marker)))
929 (let ((case-fold-search
930 (if (and case-fold-search search-upper-case
)
931 (isearch-no-upper-case-p regexp t
)
934 (while (and (< (point) rend
)
935 (re-search-forward regexp rend t
))
936 (delete-region (save-excursion (goto-char (match-beginning 0))
939 (progn (forward-line 1) (point))))))
940 (set-marker rend nil
)
944 (defun how-many (regexp &optional rstart rend interactive
)
945 "Print and return number of matches for REGEXP following point.
946 When called from Lisp and INTERACTIVE is omitted or nil, just return
947 the number, do not print it; if INTERACTIVE is t, the function behaves
948 in all respects as if it had been called interactively.
950 If REGEXP contains upper case characters (excluding those preceded by `\\')
951 and `search-upper-case' is non-nil, the matching is case-sensitive.
953 Second and third arg RSTART and REND specify the region to operate on.
955 Interactively, in Transient Mark mode when the mark is active, operate
956 on the contents of the region. Otherwise, operate from point to the
957 end of (the accessible portion of) the buffer.
959 This function starts looking for the next match from the end of
960 the previous match. Hence, it ignores matches that overlap
961 a previously found match."
964 (keep-lines-read-args "How many matches for regexp"))
969 (goto-char (min rstart rend
))
970 (setq rend
(max rstart rend
)))
972 (setq rend
(point-max)))
973 (if (and interactive
(use-region-p))
974 (setq rstart
(region-beginning)
982 (if (and case-fold-search search-upper-case
)
983 (isearch-no-upper-case-p regexp t
)
985 (while (and (< (point) rend
)
986 (progn (setq opoint
(point))
987 (re-search-forward regexp rend t
)))
988 (if (= opoint
(point))
990 (setq count
(1+ count
))))
991 (when interactive
(message "%d occurrence%s"
993 (if (= count
1) "" "s")))
997 (defvar occur-menu-map
998 (let ((map (make-sparse-keymap)))
999 (bindings--define-key map
[next-error-follow-minor-mode
]
1000 '(menu-item "Auto Occurrence Display"
1001 next-error-follow-minor-mode
1002 :help
"Display another occurrence when moving the cursor"
1003 :button
(:toggle .
(and (boundp 'next-error-follow-minor-mode
)
1004 next-error-follow-minor-mode
))))
1005 (bindings--define-key map
[separator-1
] menu-bar-separator
)
1006 (bindings--define-key map
[kill-this-buffer
]
1007 '(menu-item "Kill Occur Buffer" kill-this-buffer
1008 :help
"Kill the current *Occur* buffer"))
1009 (bindings--define-key map
[quit-window
]
1010 '(menu-item "Quit Occur Window" quit-window
1011 :help
"Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
1012 (bindings--define-key map
[revert-buffer
]
1013 '(menu-item "Revert Occur Buffer" revert-buffer
1014 :help
"Replace the text in the *Occur* buffer with the results of rerunning occur"))
1015 (bindings--define-key map
[clone-buffer
]
1016 '(menu-item "Clone Occur Buffer" clone-buffer
1017 :help
"Create and return a twin copy of the current *Occur* buffer"))
1018 (bindings--define-key map
[occur-rename-buffer
]
1019 '(menu-item "Rename Occur Buffer" occur-rename-buffer
1020 :help
"Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
1021 (bindings--define-key map
[occur-edit-buffer
]
1022 '(menu-item "Edit Occur Buffer" occur-edit-mode
1023 :help
"Edit the *Occur* buffer and apply changes to the original buffers."))
1024 (bindings--define-key map
[separator-2
] menu-bar-separator
)
1025 (bindings--define-key map
[occur-mode-goto-occurrence-other-window
]
1026 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
1027 :help
"Go to the occurrence the current line describes, in another window"))
1028 (bindings--define-key map
[occur-mode-goto-occurrence
]
1029 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
1030 :help
"Go to the occurrence the current line describes"))
1031 (bindings--define-key map
[occur-mode-display-occurrence
]
1032 '(menu-item "Display Occurrence" occur-mode-display-occurrence
1033 :help
"Display in another window the occurrence the current line describes"))
1034 (bindings--define-key map
[occur-next
]
1035 '(menu-item "Move to Next Match" occur-next
1036 :help
"Move to the Nth (default 1) next match in an Occur mode buffer"))
1037 (bindings--define-key map
[occur-prev
]
1038 '(menu-item "Move to Previous Match" occur-prev
1039 :help
"Move to the Nth (default 1) previous match in an Occur mode buffer"))
1041 "Menu keymap for `occur-mode'.")
1043 (defvar occur-mode-map
1044 (let ((map (make-sparse-keymap)))
1045 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
1046 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
1047 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
1048 (define-key map
"e" 'occur-edit-mode
)
1049 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
1050 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
1051 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
1052 (define-key map
"\M-n" 'occur-next
)
1053 (define-key map
"\M-p" 'occur-prev
)
1054 (define-key map
"r" 'occur-rename-buffer
)
1055 (define-key map
"c" 'clone-buffer
)
1056 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
1057 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
1059 "Keymap for `occur-mode'.")
1061 (defvar occur-revert-arguments nil
1062 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
1063 See `occur-revert-function'.")
1064 (make-variable-buffer-local 'occur-revert-arguments
)
1065 (put 'occur-revert-arguments
'permanent-local t
)
1067 (defcustom occur-mode-hook
'(turn-on-font-lock)
1068 "Hook run when entering Occur mode."
1072 (defcustom occur-hook nil
1073 "Hook run by Occur when there are any matches."
1077 (defcustom occur-mode-find-occurrence-hook nil
1078 "Hook run by Occur after locating an occurrence.
1079 This will be called with the cursor position at the occurrence. An application
1080 for this is to reveal context in an outline-mode when the occurrence is hidden."
1084 (put 'occur-mode
'mode-class
'special
)
1085 (define-derived-mode occur-mode special-mode
"Occur"
1086 "Major mode for output from \\[occur].
1087 \\<occur-mode-map>Move point to one of the items in this buffer, then use
1088 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
1089 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
1092 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
1093 (setq next-error-function
'occur-next-error
))
1098 (defvar occur-edit-mode-map
1099 (let ((map (make-sparse-keymap)))
1100 (set-keymap-parent map text-mode-map
)
1101 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
1102 (define-key map
"\C-c\C-c" 'occur-cease-edit
)
1103 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
1104 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
1105 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
1107 "Keymap for `occur-edit-mode'.")
1109 (define-derived-mode occur-edit-mode occur-mode
"Occur-Edit"
1110 "Major mode for editing *Occur* buffers.
1111 In this mode, changes to the *Occur* buffer are also applied to
1112 the originating buffer.
1114 To return to ordinary Occur mode, use \\[occur-cease-edit]."
1115 (setq buffer-read-only nil
)
1116 (add-hook 'after-change-functions
'occur-after-change-function nil t
)
1117 (message (substitute-command-keys
1118 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
1120 (defun occur-cease-edit ()
1121 "Switch from Occur Edit mode to Occur mode."
1123 (when (derived-mode-p 'occur-edit-mode
)
1125 (message "Switching to Occur mode.")))
1127 (defun occur-after-change-function (beg end length
)
1130 (let* ((line-beg (line-beginning-position))
1131 (m (get-text-property line-beg
'occur-target
))
1132 (buf (marker-buffer m
))
1134 (when (and (get-text-property line-beg
'occur-prefix
)
1135 (not (get-text-property end
'occur-prefix
)))
1137 ;; Apply occur-target property to inserted (e.g. yanked) text.
1138 (put-text-property beg end
'occur-target m
)
1139 ;; Did we insert a newline? Occur Edit mode can't create new
1140 ;; Occur entries; just discard everything after the newline.
1142 (and (search-forward "\n" end t
)
1143 (delete-region (1- (point)) end
))))
1144 (let* ((line (- (line-number-at-pos)
1145 (line-number-at-pos (window-start))))
1146 (readonly (with-current-buffer buf buffer-read-only
))
1147 (win (or (get-buffer-window buf
)
1149 '(nil (inhibit-same-window . t
)
1150 (inhibit-switch-frame . t
)))))
1151 (line-end (line-end-position))
1152 (text (save-excursion
1153 (goto-char (next-single-property-change
1154 line-beg
'occur-prefix nil
1156 (setq col
(- (point) line-beg
))
1157 (buffer-substring-no-properties (point) line-end
))))
1158 (with-selected-window win
1162 (message "Buffer `%s' is read only." buf
)
1163 (delete-region (line-beginning-position) (line-end-position))
1165 (move-to-column col
)))))))
1168 (defun occur-revert-function (_ignore1 _ignore2
)
1169 "Handle `revert-buffer' for Occur mode buffers."
1170 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
1172 (defun occur-mode-find-occurrence ()
1173 (let ((pos (get-text-property (point) 'occur-target
)))
1175 (error "No occurrence on this line"))
1176 (unless (buffer-live-p (marker-buffer pos
))
1177 (error "Buffer for this occurrence was killed"))
1180 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
1181 (defun occur-mode-goto-occurrence (&optional event
)
1182 "Go to the occurrence on the current line."
1183 (interactive (list last-nonmenu-event
))
1186 ;; Actually `event-end' works correctly with a nil argument as
1187 ;; well, so we could dispense with this test, but let's not
1188 ;; rely on this undocumented behavior.
1189 (occur-mode-find-occurrence)
1190 (with-current-buffer (window-buffer (posn-window (event-end event
)))
1192 (goto-char (posn-point (event-end event
)))
1193 (occur-mode-find-occurrence))))))
1194 (pop-to-buffer (marker-buffer pos
))
1196 (run-hooks 'occur-mode-find-occurrence-hook
)))
1198 (defun occur-mode-goto-occurrence-other-window ()
1199 "Go to the occurrence the current line describes, in another window."
1201 (let ((pos (occur-mode-find-occurrence)))
1202 (switch-to-buffer-other-window (marker-buffer pos
))
1204 (run-hooks 'occur-mode-find-occurrence-hook
)))
1206 (defun occur-mode-display-occurrence ()
1207 "Display in another window the occurrence the current line describes."
1209 (let ((pos (occur-mode-find-occurrence))
1211 (setq window
(display-buffer (marker-buffer pos
) t
))
1212 ;; This is the way to set point in the proper window.
1213 (save-selected-window
1214 (select-window window
)
1216 (run-hooks 'occur-mode-find-occurrence-hook
))))
1218 (defun occur-find-match (n search message
)
1219 (if (not n
) (setq n
1))
1222 (setq r
(funcall search
(point) 'occur-match
))
1224 (get-text-property r
'occur-match
)
1225 (setq r
(funcall search r
'occur-match
)))
1231 (defun occur-next (&optional n
)
1232 "Move to the Nth (default 1) next match in an Occur mode buffer."
1234 (occur-find-match n
#'next-single-property-change
"No more matches"))
1236 (defun occur-prev (&optional n
)
1237 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1239 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
1241 (defun occur-next-error (&optional argp reset
)
1242 "Move to the Nth (default 1) next match in an Occur mode buffer.
1243 Compatibility function for \\[next-error] invocations."
1245 ;; we need to run occur-find-match from within the Occur buffer
1246 (with-current-buffer
1247 ;; Choose the buffer and make it current.
1248 (if (next-error-buffer-p (current-buffer))
1250 (next-error-find-buffer nil nil
1252 (eq major-mode
'occur-mode
))))
1254 (goto-char (cond (reset (point-min))
1255 ((< argp
0) (line-beginning-position))
1256 ((> argp
0) (line-end-position))
1261 #'previous-single-property-change
1262 #'next-single-property-change
)
1264 ;; In case the *Occur* buffer is visible in a nonselected window.
1265 (let ((win (get-buffer-window (current-buffer) t
)))
1266 (if win
(set-window-point win
(point))))
1267 (occur-mode-goto-occurrence)))
1270 '((((class color
) (min-colors 88) (background light
))
1271 :background
"yellow1")
1272 (((class color
) (min-colors 88) (background dark
))
1273 :background
"RoyalBlue3")
1274 (((class color
) (min-colors 8) (background light
))
1275 :background
"yellow" :foreground
"black")
1276 (((class color
) (min-colors 8) (background dark
))
1277 :background
"blue" :foreground
"white")
1278 (((type tty
) (class mono
))
1280 (t :background
"gray"))
1281 "Face used to highlight matches permanently."
1286 (defcustom list-matching-lines-default-context-lines
0
1287 "Default number of context lines included around `list-matching-lines' matches.
1288 A negative number means to include that many lines before the match.
1289 A positive number means to include that many lines both before and after."
1293 (defalias 'list-matching-lines
'occur
)
1295 (defcustom list-matching-lines-face
'match
1296 "Face used by \\[list-matching-lines] to show the text that matches.
1297 If the value is nil, don't highlight the matching portions specially."
1301 (defcustom list-matching-lines-buffer-name-face
'underline
1302 "Face used by \\[list-matching-lines] to show the names of buffers.
1303 If the value is nil, don't highlight the buffer names specially."
1307 (defcustom list-matching-lines-prefix-face
'shadow
1308 "Face used by \\[list-matching-lines] to show the prefix column.
1309 If the face doesn't differ from the default face,
1310 don't highlight the prefix with line numbers specially."
1315 (defcustom occur-excluded-properties
1316 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1317 yank-handler follow-link
)
1318 "Text properties to discard when copying lines to the *Occur* buffer.
1319 The value should be a list of text properties to discard or t,
1320 which means to discard all text properties."
1321 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
1325 (defun occur-read-primary-args ()
1326 (let* ((perform-collect (consp current-prefix-arg
))
1327 (regexp (read-regexp (if perform-collect
1328 "Collect strings matching regexp"
1329 "List lines matching regexp")
1330 'regexp-history-last
)))
1333 ;; Perform collect operation
1334 (if (zerop (regexp-opt-depth regexp
))
1335 ;; No subexpression so collect the entire match.
1337 ;; Get the regexp for collection pattern.
1338 (let ((default (car occur-collect-regexp-history
)))
1340 (format "Regexp to collect (default %s): " default
)
1341 default
'occur-collect-regexp-history
)))
1342 ;; Otherwise normal occur takes numerical prefix argument.
1343 (when current-prefix-arg
1344 (prefix-numeric-value current-prefix-arg
))))))
1346 (defun occur-rename-buffer (&optional unique-p interactive-p
)
1347 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1348 Here `original-buffer-name' is the buffer name where Occur was originally run.
1349 When given the prefix argument, or called non-interactively, the renaming
1350 will not clobber the existing buffer(s) of that name, but use
1351 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1352 if you always want a separate *Occur* buffer for each buffer where you
1354 (interactive "P\np")
1355 (with-current-buffer
1356 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
1357 (rename-buffer (concat "*Occur: "
1358 (mapconcat #'buffer-name
1359 (car (cddr occur-revert-arguments
)) "/")
1361 (or unique-p
(not interactive-p
)))))
1363 (defun occur (regexp &optional nlines
)
1364 "Show all lines in the current buffer containing a match for REGEXP.
1365 If a match spreads across multiple lines, all those lines are shown.
1367 Each line is displayed with NLINES lines before and after, or -NLINES
1368 before if NLINES is negative.
1369 NLINES defaults to `list-matching-lines-default-context-lines'.
1370 Interactively it is the prefix arg.
1372 The lines are shown in a buffer named `*Occur*'.
1373 It serves as a menu to find any of the occurrences in this buffer.
1374 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1376 If REGEXP contains upper case characters (excluding those preceded by `\\')
1377 and `search-upper-case' is non-nil, the matching is case-sensitive.
1379 When NLINES is a string or when the function is called
1380 interactively with prefix argument without a number (`C-u' alone
1381 as prefix) the matching strings are collected into the `*Occur*'
1382 buffer by using NLINES as a replacement regexp. NLINES may
1383 contain \\& and \\N which convention follows `replace-match'.
1384 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1385 \"\\1\" for NLINES collects all the function names in a lisp
1386 program. When there is no parenthesized subexpressions in REGEXP
1387 the entire match is collected. In any case the searched buffer
1389 (interactive (occur-read-primary-args))
1390 (occur-1 regexp nlines
(list (current-buffer))))
1392 (defvar ido-ignore-item-temp-list
)
1394 (defun multi-occur (bufs regexp
&optional nlines
)
1395 "Show all lines in buffers BUFS containing a match for REGEXP.
1396 This function acts on multiple buffers; otherwise, it is exactly like
1397 `occur'. When you invoke this command interactively, you must specify
1398 the buffer names that you want, one by one.
1399 See also `multi-occur-in-matching-buffers'."
1402 (let* ((bufs (list (read-buffer "First buffer to search: "
1403 (current-buffer) t
)))
1405 (ido-ignore-item-temp-list bufs
))
1406 (while (not (string-equal
1407 (setq buf
(read-buffer
1408 (if (eq read-buffer-function
#'ido-read-buffer
)
1409 "Next buffer to search (C-j to end): "
1410 "Next buffer to search (RET to end): ")
1413 (cl-pushnew buf bufs
)
1414 (setq ido-ignore-item-temp-list bufs
))
1415 (nreverse (mapcar #'get-buffer bufs
)))
1416 (occur-read-primary-args)))
1417 (occur-1 regexp nlines bufs
))
1419 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1420 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1421 Normally BUFREGEXP matches against each buffer's visited file name,
1422 but if you specify a prefix argument, it matches against the buffer name.
1423 See also `multi-occur'."
1426 (let* ((default (car regexp-history
))
1429 (if current-prefix-arg
1430 "List lines in buffers whose names match regexp: "
1431 "List lines in buffers whose filenames match regexp: "))))
1432 (if (equal input
"")
1435 (occur-read-primary-args)))
1439 (mapcar (lambda (buf)
1441 (string-match bufregexp
1443 (and (buffer-file-name buf
)
1444 (string-match bufregexp
1445 (buffer-file-name buf
))))
1449 (defun occur-regexp-descr (regexp)
1450 (format " for %s\"%s\""
1451 (or (get-text-property 0 'isearch-regexp-function-descr regexp
)
1453 (if (get-text-property 0 'isearch-string regexp
)
1455 (query-replace-descr
1456 (get-text-property 0 'isearch-string regexp
))
1458 (query-replace-descr regexp
))))
1460 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1461 (unless (and regexp
(not (equal regexp
"")))
1462 (error "Occur doesn't work with the empty regexp"))
1464 (setq buf-name
"*Occur*"))
1466 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1467 (when (buffer-live-p buf
) buf
))
1469 ;; Handle the case where one of the buffers we're searching is the
1470 ;; output buffer. Just rename it.
1471 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1472 (with-current-buffer (get-buffer buf-name
)
1475 ;; Now find or create the output buffer.
1476 ;; If we just renamed that buffer, we will make a new one here.
1477 (setq occur-buf
(get-buffer-create buf-name
))
1479 (with-current-buffer occur-buf
1480 (if (stringp nlines
)
1481 (fundamental-mode) ;; This is for collect operation.
1483 (let ((inhibit-read-only t
)
1484 ;; Don't generate undo entries for creation of the initial contents.
1485 (buffer-undo-list t
))
1488 (if (stringp nlines
)
1489 ;; Treat nlines as a regexp to collect.
1490 (let ((bufs active-bufs
)
1493 (with-current-buffer (car bufs
)
1495 (goto-char (point-min))
1496 (while (re-search-forward regexp nil t
)
1497 ;; Insert the replacement regexp.
1498 (let ((str (match-substitute-replacement nlines
)))
1500 (with-current-buffer occur-buf
1502 (setq count
(1+ count
))
1503 (or (zerop (current-column))
1504 (insert "\n"))))))))
1505 (setq bufs
(cdr bufs
)))
1507 ;; Perform normal occur.
1509 regexp active-bufs occur-buf
1510 (or nlines list-matching-lines-default-context-lines
)
1511 (if (and case-fold-search search-upper-case
)
1512 (isearch-no-upper-case-p regexp t
)
1514 list-matching-lines-buffer-name-face
1515 (if (face-differs-from-default-p list-matching-lines-prefix-face
)
1516 list-matching-lines-prefix-face
)
1517 list-matching-lines-face
1518 (not (eq occur-excluded-properties t
))))))
1519 (let* ((bufcount (length active-bufs
))
1520 (diff (- (length bufs
) bufcount
)))
1521 (message "Searched %d buffer%s%s; %s match%s%s"
1522 bufcount
(if (= bufcount
1) "" "s")
1523 (if (zerop diff
) "" (format " (%d killed)" diff
))
1524 (if (zerop count
) "no" (format "%d" count
))
1525 (if (= count
1) "" "es")
1526 ;; Don't display regexp if with remaining text
1527 ;; it is longer than window-width.
1528 (if (> (+ (length (or (get-text-property 0 'isearch-string regexp
)
1532 "" (occur-regexp-descr regexp
))))
1533 (setq occur-revert-arguments
(list regexp nlines bufs
))
1535 (kill-buffer occur-buf
)
1536 (display-buffer occur-buf
)
1537 (setq next-error-last-buffer occur-buf
)
1538 (setq buffer-read-only t
)
1539 (set-buffer-modified-p nil
)
1540 (run-hooks 'occur-hook
)))))))
1542 (defun occur-engine (regexp buffers out-buf nlines case-fold
1543 title-face prefix-face match-face keep-props
)
1544 (with-current-buffer out-buf
1545 (let ((global-lines 0) ;; total count of matching lines
1546 (global-matches 0) ;; total count of matches
1548 (case-fold-search case-fold
))
1549 ;; Map over all the buffers
1550 (dolist (buf buffers
)
1551 (when (buffer-live-p buf
)
1552 (let ((lines 0) ;; count of matching lines
1553 (matches 0) ;; count of matches
1554 (curr-line 1) ;; line count
1555 (prev-line nil
) ;; line number of prev match endpt
1556 (prev-after-lines nil
) ;; context lines of prev match
1564 (inhibit-field-text-motion t
)
1565 (headerpt (with-current-buffer out-buf
(point))))
1566 (with-current-buffer buf
1568 ;; Set CODING only if the current buffer locally
1569 ;; binds buffer-file-coding-system.
1570 (not (local-variable-p 'buffer-file-coding-system
))
1571 (setq coding buffer-file-coding-system
))
1573 (goto-char (point-min)) ;; begin searching in the buffer
1575 (setq origpt
(point))
1576 (when (setq endpt
(re-search-forward regexp nil t
))
1577 (setq lines
(1+ lines
)) ;; increment matching lines count
1578 (setq matchbeg
(match-beginning 0))
1579 ;; Get beginning of first match line and end of the last.
1581 (goto-char matchbeg
)
1582 (setq begpt
(line-beginning-position))
1584 (setq endpt
(line-end-position)))
1585 ;; Sum line numbers up to the first match line.
1586 (setq curr-line
(+ curr-line
(count-lines origpt begpt
)))
1587 (setq marker
(make-marker))
1588 (set-marker marker matchbeg
)
1589 (setq curstring
(occur-engine-line begpt endpt keep-props
))
1590 ;; Highlight the matches
1591 (let ((len (length curstring
))
1593 ;; Count empty lines that don't use next loop (Bug#22062).
1595 (setq matches
(1+ matches
)))
1596 (while (and (< start len
)
1597 (string-match regexp curstring start
))
1598 (setq matches
(1+ matches
))
1599 (add-text-properties
1600 (match-beginning 0) (match-end 0)
1601 '(occur-match t
) curstring
)
1603 ;; Add `match-face' to faces copied from the buffer.
1604 (add-face-text-property
1605 (match-beginning 0) (match-end 0)
1606 match-face nil curstring
))
1607 ;; Avoid infloop (Bug#7593).
1608 (let ((end (match-end 0)))
1609 (setq start
(if (= start end
) (1+ start
) end
)))))
1610 ;; Generate the string to insert for this match
1611 (let* ((match-prefix
1612 ;; Using 7 digits aligns tabs properly.
1613 (apply #'propertize
(format "%7d:" curr-line
)
1616 `(font-lock-face ,prefix-face
))
1617 `(occur-prefix t mouse-face
(highlight)
1618 ;; Allow insertion of text at
1619 ;; the end of the prefix (for
1620 ;; Occur Edit mode).
1621 front-sticky t rear-nonsticky t
1622 occur-target
,marker follow-link t
1623 help-echo
"mouse-2: go to this occurrence"))))
1625 ;; We don't put `mouse-face' on the newline,
1626 ;; because that loses. And don't put it
1627 ;; on context lines to reduce flicker.
1628 (propertize curstring
'mouse-face
(list 'highlight
)
1629 'occur-target marker
1632 "mouse-2: go to this occurrence"))
1636 ;; Add non-numeric prefix to all non-first lines
1637 ;; of multi-line matches.
1638 (replace-regexp-in-string
1641 (propertize "\n :" 'font-lock-face prefix-face
)
1644 ;; Add marker at eol, but no mouse props.
1645 (propertize "\n" 'occur-target marker
)))
1648 ;; The simple display style
1650 ;; The complex multi-line display style.
1651 (setq ret
(occur-context-lines
1652 out-line nlines keep-props begpt endpt
1653 curr-line prev-line prev-after-lines
1655 ;; Set first elem of the returned list to `data',
1656 ;; and the second elem to `prev-after-lines'.
1657 (setq prev-after-lines
(nth 1 ret
))
1659 ;; Actually insert the match display data
1660 (with-current-buffer out-buf
1665 ;; Sum line numbers between first and last match lines.
1666 (setq curr-line
(+ curr-line
(count-lines begpt endpt
)
1667 ;; Add 1 for empty last match line since
1668 ;; count-lines returns 1 line less.
1669 (if (and (bolp) (eolp)) 1 0)))
1670 ;; On to the next match...
1672 (goto-char (point-max)))
1673 (setq prev-line
(1- curr-line
)))
1674 ;; Flush remaining context after-lines.
1675 (when prev-after-lines
1676 (with-current-buffer out-buf
1677 (insert (apply #'concat
(occur-engine-add-prefix
1678 prev-after-lines prefix-face
)))))))
1679 (when (not (zerop lines
)) ;; is the count zero?
1680 (setq global-lines
(+ global-lines lines
)
1681 global-matches
(+ global-matches matches
))
1682 (with-current-buffer out-buf
1683 (goto-char headerpt
)
1687 (format "%d match%s%s%s in buffer: %s\n"
1688 matches
(if (= matches
1) "" "es")
1689 ;; Don't display the same number of lines
1690 ;; and matches in case of 1 match per line.
1691 (if (= lines matches
)
1692 "" (format " in %d line%s"
1693 lines
(if (= lines
1) "" "s")))
1694 ;; Don't display regexp for multi-buffer.
1695 (if (> (length buffers
) 1)
1696 "" (occur-regexp-descr regexp
))
1700 (add-text-properties beg end
`(occur-title ,buf
))
1702 (add-face-text-property beg end title-face
)))
1703 (goto-char (point-min)))))))
1704 ;; Display total match count and regexp for multi-buffer.
1705 (when (and (not (zerop global-lines
)) (> (length buffers
) 1))
1706 (goto-char (point-min))
1709 (insert (format "%d match%s%s total%s:\n"
1710 global-matches
(if (= global-matches
1) "" "es")
1711 ;; Don't display the same number of lines
1712 ;; and matches in case of 1 match per line.
1713 (if (= global-lines global-matches
)
1714 "" (format " in %d line%s"
1715 global-lines
(if (= global-lines
1) "" "s")))
1716 (occur-regexp-descr regexp
)))
1719 (add-face-text-property beg end title-face
)))
1720 (goto-char (point-min)))
1722 ;; CODING is buffer-file-coding-system of the first buffer
1723 ;; that locally binds it. Let's use it also for the output
1725 (set-buffer-file-coding-system coding
))
1726 ;; Return the number of matches
1729 (defun occur-engine-line (beg end
&optional keep-props
)
1730 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
1731 (text-property-not-all beg end
'fontified t
))
1732 (if (fboundp 'jit-lock-fontify-now
)
1733 (jit-lock-fontify-now beg end
)))
1734 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1735 (let ((str (buffer-substring beg end
)))
1736 (remove-list-of-text-properties
1737 0 (length str
) occur-excluded-properties str
)
1739 (buffer-substring-no-properties beg end
)))
1741 (defun occur-engine-add-prefix (lines &optional prefix-face
)
1744 (concat (if prefix-face
1745 (propertize " :" 'font-lock-face prefix-face
)
1750 (defun occur-accumulate-lines (count &optional keep-props pt
)
1754 (let ((forwardp (> count
0))
1755 result beg end moved
)
1756 (while (not (or (zerop count
)
1759 (and (bobp) (not moved
)))))
1760 (setq count
(+ count
(if forwardp -
1 1)))
1761 (setq beg
(line-beginning-position)
1762 end
(line-end-position))
1763 (push (occur-engine-line beg end keep-props
) result
)
1764 (setq moved
(= 0 (forward-line (if forwardp
1 -
1)))))
1765 (nreverse result
))))
1767 ;; Generate context display for occur.
1768 ;; OUT-LINE is the line where the match is.
1769 ;; NLINES and KEEP-PROPS are args to occur-engine.
1770 ;; CURR-LINE is line count of the current match,
1771 ;; PREV-LINE is line count of the previous match,
1772 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1773 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1774 ;; then concatenate them all together.
1775 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1776 curr-line prev-line prev-after-lines
1777 &optional prefix-face
)
1778 ;; Find after- and before-context lines of the current match.
1780 (nreverse (cdr (occur-accumulate-lines
1781 (- (1+ (abs nlines
))) keep-props begpt
))))
1783 (cdr (occur-accumulate-lines
1784 (1+ nlines
) keep-props endpt
)))
1787 ;; Combine after-lines of the previous match
1788 ;; with before-lines of the current match.
1790 (when prev-after-lines
1791 ;; Don't overlap prev after-lines with current before-lines.
1792 (if (>= (+ prev-line
(length prev-after-lines
))
1793 (- curr-line
(length before-lines
)))
1794 (setq prev-after-lines
1795 (butlast prev-after-lines
1796 (- (length prev-after-lines
)
1797 (- curr-line prev-line
(length before-lines
) 1))))
1798 ;; Separate non-overlapping context lines with a dashed line.
1799 (setq separator
"-------\n")))
1802 ;; Don't overlap current before-lines with previous match line.
1803 (if (<= (- curr-line
(length before-lines
))
1806 (nthcdr (- (length before-lines
)
1807 (- curr-line prev-line
1))
1809 ;; Separate non-overlapping before-context lines.
1810 (unless (> nlines
0)
1811 (setq separator
"-------\n"))))
1814 ;; Return a list where the first element is the output line.
1817 (if prev-after-lines
1818 (occur-engine-add-prefix prev-after-lines prefix-face
))
1820 (list (if prefix-face
1821 (propertize separator
'font-lock-face prefix-face
)
1823 (occur-engine-add-prefix before-lines prefix-face
)
1825 ;; And the second element is the list of context after-lines.
1826 (if (> nlines
0) after-lines
))))
1829 ;; It would be nice to use \\[...], but there is no reasonable way
1830 ;; to make that display both SPC and Y.
1831 (defconst query-replace-help
1832 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1833 RET or `q' to exit, Period to replace one match and exit,
1834 Comma to replace but not move point immediately,
1835 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1836 C-w to delete match and recursive edit,
1837 C-l to clear the screen, redisplay, and offer same replacement again,
1838 ! to replace all remaining matches in this buffer with no more questions,
1839 ^ to move point back to previous match,
1840 u to undo previous replacement,
1841 U to undo all replacements,
1842 E to edit the replacement string.
1843 In multi-buffer replacements type `Y' to replace all remaining
1844 matches in all remaining buffers with no more questions,
1845 `N' to skip to the next buffer without replacing remaining matches
1846 in the current buffer."
1847 "Help message while in `query-replace'.")
1849 (defvar query-replace-map
1850 (let ((map (make-sparse-keymap)))
1851 (define-key map
" " 'act
)
1852 (define-key map
"\d" 'skip
)
1853 (define-key map
[delete] 'skip)
1854 (define-key map [backspace] 'skip)
1855 (define-key map "y" 'act)
1856 (define-key map "n" 'skip)
1857 (define-key map "Y" 'act)
1858 (define-key map "N" 'skip)
1859 (define-key map "e" 'edit-replacement)
1860 (define-key map "E" 'edit-replacement)
1861 (define-key map "," 'act-and-show)
1862 (define-key map "q" 'exit)
1863 (define-key map "\r" 'exit)
1864 (define-key map [return] 'exit)
1865 (define-key map "." 'act-and-exit)
1866 (define-key map "\C-r" 'edit)
1867 (define-key map "\C-w" 'delete-and-edit)
1868 (define-key map "\C-l" 'recenter)
1869 (define-key map "!" 'automatic)
1870 (define-key map "^" 'backup)
1871 (define-key map "u" 'undo)
1872 (define-key map "U" 'undo-all)
1873 (define-key map "\C-h" 'help)
1874 (define-key map [f1] 'help)
1875 (define-key map [help] 'help)
1876 (define-key map "?" 'help)
1877 (define-key map "\C-g" 'quit)
1878 (define-key map "\C-]" 'quit)
1879 (define-key map "\C-v" 'scroll-up)
1880 (define-key map "\M-v" 'scroll-down)
1881 (define-key map [next] 'scroll-up)
1882 (define-key map [prior] 'scroll-down)
1883 (define-key map [?\C-\M-v] 'scroll-other-window)
1884 (define-key map [M-next] 'scroll-other-window)
1885 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1886 (define-key map [M-prior] 'scroll-other-window-down)
1887 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1888 ;; should check for ESC specially.
1889 ;; (define-key map "\e" 'exit-prefix)
1890 (define-key map [escape] 'exit-prefix)
1892 "Keymap of responses to questions posed by commands like `query-replace'.
1893 The \"bindings\" in this map are not commands; they are answers.
1894 The valid answers include `act', `skip', `act-and-show',
1895 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1896 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1897 `edit', `edit-replacement', `delete-and-edit', `automatic',
1898 `backup', `undo', `undo-all', `quit', and `help'.
1900 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1902 (defvar multi-query-replace-map
1903 (let ((map (make-sparse-keymap)))
1904 (set-keymap-parent map query-replace-map)
1905 (define-key map "Y" 'automatic-all)
1906 (define-key map "N" 'exit-current)
1908 "Keymap that defines additional bindings for multi-buffer replacements.
1909 It extends its parent map `query-replace-map' with new bindings to
1910 operate on a set of buffers/files. The difference with its parent map
1911 is the additional answers `automatic-all' to replace all remaining
1912 matches in all remaining buffers with no more questions, and
1913 `exit-current' to skip remaining matches in the current buffer
1914 and to continue with the next buffer in the sequence.")
1916 (defun replace-match-string-symbols (n)
1917 "Process a list (and any sub-lists), expanding certain symbols.
1919 N (match-string N) (where N is a string of digits)
1920 #N (string-to-number (match-string N))
1922 #& (string-to-number (match-string 0))
1925 Note that these symbols must be preceded by a backslash in order to
1926 type them using Lisp syntax."
1930 (replace-match-string-symbols (car n))) ;Process sub-list
1932 (let ((name (symbol-name (car n))))
1934 ((string-match "^[0-9]+$" name)
1935 (setcar n (list 'match-string (string-to-number name))))
1936 ((string-match "^#[0-9]+$" name)
1937 (setcar n (list 'string-to-number
1939 (string-to-number (substring name 1))))))
1941 (setcar n '(match-string 0)))
1942 ((string= "#&" name)
1943 (setcar n '(string-to-number (match-string 0))))
1945 (setcar n 'replace-count))))))
1948 (defun replace-eval-replacement (expression count)
1949 (let* ((replace-count count)
1954 (error "Error evaluating replacement expression: %S" err)))))
1955 (if (stringp replacement)
1957 (prin1-to-string replacement t))))
1959 (defun replace-quote (replacement)
1960 "Quote a replacement string.
1961 This just doubles all backslashes in REPLACEMENT and
1962 returns the resulting string. If REPLACEMENT is not
1963 a string, it is first passed through `prin1-to-string'
1964 with the `noescape' argument set.
1966 `match-data' is preserved across the call."
1968 (replace-regexp-in-string "\\\\" "\\\\"
1969 (if (stringp replacement)
1971 (prin1-to-string replacement t))
1974 (defun replace-loop-through-replacements (data count)
1975 ;; DATA is a vector containing the following values:
1976 ;; 0 next-rotate-count
1978 ;; 2 next-replacement
1980 (if (= (aref data 0) count)
1982 (aset data 0 (+ count (aref data 1)))
1983 (let ((next (cdr (aref data 2))))
1984 (aset data 2 (if (consp next) next (aref data 3))))))
1985 (car (aref data 2)))
1987 (defun replace-match-data (integers reuse &optional new)
1988 "Like `match-data', but markers in REUSE get invalidated.
1989 If NEW is non-nil, it is set and returned instead of fresh data,
1990 but coerced to the correct value of INTEGERS."
1993 (set-match-data new)
1995 (eq (null integers) (markerp (car reuse)))
1997 (match-data integers reuse t)))
1999 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data
2001 "Make a replacement with `replace-match', editing `\\?'.
2002 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
2003 After possibly editing it (if `\\?' is present), NEWTEXT is also
2004 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
2005 is made (to save time).
2006 MATCH-DATA is used for the replacement, and is a data structure
2007 as returned from the `match-data' function.
2008 In case editing is done, it is changed to use markers. BACKWARD is
2009 used to reverse the replacement direction.
2011 The return value is non-nil if there has been no `\\?' or NOEDIT was
2012 passed in. If LITERAL is set, no checking is done, anyway."
2013 (unless (or literal noedit)
2015 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
2018 (read-string "Edit replacement string: "
2021 (replace-match "" t t newtext 3)
2022 (1+ (match-beginning 3)))
2025 nil match-data match-data))))
2027 (set-match-data match-data)
2028 (replace-match newtext fixedcase literal)
2029 ;; `replace-match' leaves point at the end of the replacement text,
2030 ;; so move point to the beginning when replacing backward.
2031 (when backward (goto-char (nth 0 match-data)))
2034 (defvar replace-update-post-hook nil
2035 "Function(s) to call after query-replace has found a match in the buffer.")
2037 (defvar replace-search-function nil
2038 "Function to use when searching for strings to replace.
2039 It is used by `query-replace' and `replace-string', and is called
2040 with three arguments, as if it were `search-forward'.")
2042 (defvar replace-re-search-function nil
2043 "Function to use when searching for regexps to replace.
2044 It is used by `query-replace-regexp', `replace-regexp',
2045 `query-replace-regexp-eval', and `map-query-replace-regexp'.
2046 It is called with three arguments, as if it were
2047 `re-search-forward'.")
2049 (defun replace-search (search-string limit regexp-flag delimited-flag
2050 case-fold &optional backward)
2051 "Search for the next occurrence of SEARCH-STRING to replace."
2052 ;; Let-bind global isearch-* variables to values used
2053 ;; to search the next replacement. These let-bindings
2054 ;; should be effective both at the time of calling
2055 ;; `isearch-search-fun-default' and also at the
2056 ;; time of funcalling `search-function'.
2057 ;; These isearch-* bindings can't be placed higher
2058 ;; outside of this function because then another I-search
2059 ;; used after `recursive-edit' might override them.
2060 (let* ((isearch-regexp regexp-flag)
2061 (isearch-regexp-function (or delimited-flag
2062 (and replace-char-fold
2064 #'char-fold-to-regexp)))
2065 (isearch-lax-whitespace
2066 replace-lax-whitespace)
2067 (isearch-regexp-lax-whitespace
2068 replace-regexp-lax-whitespace)
2069 (isearch-case-fold-search case-fold)
2070 (isearch-adjusted nil)
2071 (isearch-nonincremental t) ; don't use lax word mode
2072 (isearch-forward (not backward))
2075 replace-re-search-function
2076 replace-search-function)
2077 (isearch-search-fun-default))))
2078 (funcall search-function search-string limit t)))
2080 (defvar replace-overlay nil)
2082 (defun replace-highlight (match-beg match-end range-beg range-end
2083 search-string regexp-flag delimited-flag
2084 case-fold &optional backward)
2085 (if query-replace-highlight
2087 (move-overlay replace-overlay match-beg match-end (current-buffer))
2088 (setq replace-overlay (make-overlay match-beg match-end))
2089 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2090 (overlay-put replace-overlay 'face 'query-replace)))
2091 (if query-replace-lazy-highlight
2092 (let ((isearch-string search-string)
2093 (isearch-regexp regexp-flag)
2094 (isearch-regexp-function delimited-flag)
2095 (isearch-lax-whitespace
2096 replace-lax-whitespace)
2097 (isearch-regexp-lax-whitespace
2098 replace-regexp-lax-whitespace)
2099 (isearch-case-fold-search case-fold)
2100 (isearch-forward (not backward))
2101 (isearch-other-end match-beg)
2102 (isearch-error nil))
2103 (isearch-lazy-highlight-new-loop range-beg range-end))))
2105 (defun replace-dehighlight ()
2106 (when replace-overlay
2107 (delete-overlay replace-overlay))
2108 (when query-replace-lazy-highlight
2109 (lazy-highlight-cleanup lazy-highlight-cleanup)
2110 (setq isearch-lazy-highlight-last-string nil))
2111 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2112 (isearch-clean-overlays))
2114 (defun perform-replace (from-string replacements
2115 query-flag regexp-flag delimited-flag
2116 &optional repeat-count map start end backward region-noncontiguous-p)
2117 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2118 Don't use this in your own program unless you want to query and set the mark
2119 just as `query-replace' does. Instead, write a simple loop like this:
2121 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2122 (replace-match \"foobar\" nil nil))
2124 which will run faster and probably do exactly what you want. Please
2125 see the documentation of `replace-match' to find out how to simulate
2128 This function returns nil if and only if there were no matches to
2129 make, or the user didn't cancel the call.
2131 REPLACEMENTS is either a string, a list of strings, or a cons cell
2132 containing a function and its first argument. The function is
2133 called to generate each replacement like this:
2134 (funcall (car replacements) (cdr replacements) replace-count)
2135 It must return a string."
2136 (or map (setq map query-replace-map))
2137 (and query-flag minibuffer-auto-raise
2138 (raise-frame (window-frame (minibuffer-window))))
2139 (let* ((case-fold-search
2140 (if (and case-fold-search search-upper-case)
2141 (isearch-no-upper-case-p from-string regexp-flag)
2143 (nocasify (not (and case-replace case-fold-search)))
2144 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2145 (search-string from-string)
2146 (real-match-data nil) ; The match data for the current match.
2147 (next-replacement nil)
2148 ;; This is non-nil if we know there is nothing for the user
2149 ;; to edit in the replacement.
2153 (search-string-replaced nil) ; last string matching `from-string'
2154 (next-replacement-replaced nil) ; replacement string
2155 ; (substituted regexp)
2158 (skip-read-only-count 0)
2159 (skip-filtered-count 0)
2160 (skip-invisible-count 0)
2161 (nonempty-match nil)
2163 (recenter-last-op nil) ; Start cycling order with initial position.
2165 ;; If non-nil, it is marker saying where in the buffer to stop.
2167 ;; Use local binding in add-function below.
2168 (isearch-filter-predicate isearch-filter-predicate)
2171 ;; Data for the next match. If a cons, it has the same format as
2172 ;; (match-data); otherwise it is t if a match is possible at point.
2178 (substitute-command-keys
2179 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2180 minibuffer-prompt-properties))))
2182 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
2183 (when region-noncontiguous-p
2185 (mapcar (lambda (position)
2186 (cons (copy-marker (car position))
2187 (copy-marker (cdr position))))
2188 (funcall region-extract-function 'bounds)))
2189 (add-function :after-while isearch-filter-predicate
2194 (>= start (car bounds))
2195 (<= start (cdr bounds))
2196 (>= end (car bounds))
2197 (<= end (cdr bounds))))
2200 ;; If region is active, in Transient Mark mode, operate on region.
2203 (setq limit (copy-marker (min start end)))
2204 (goto-char (max start end))
2207 (setq limit (copy-marker (max start end)))
2208 (goto-char (min start end))
2211 ;; If last typed key in previous call of multi-buffer perform-replace
2212 ;; was `automatic-all', don't ask more questions in next files
2213 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2214 (setq query-flag nil multi-buffer t))
2217 ((stringp replacements)
2218 (setq next-replacement replacements
2220 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2221 (or repeat-count (setq repeat-count 1))
2222 (setq replacements (cons 'replace-loop-through-replacements
2223 (vector repeat-count repeat-count
2224 replacements replacements)))))
2226 (when query-replace-lazy-highlight
2227 (setq isearch-lazy-highlight-last-string nil))
2232 ;; Loop finding occurrences that perhaps should be replaced.
2233 (while (and keep-going
2235 (not (or (bobp) (and limit (<= (point) limit))))
2236 (not (or (eobp) (and limit (>= (point) limit)))))
2237 ;; Use the next match if it is already known;
2238 ;; otherwise, search for a match after moving forward
2239 ;; one char if progress is required.
2240 (setq real-match-data
2241 (cond ((consp match-again)
2242 (goto-char (if backward
2244 (nth 1 match-again)))
2246 t real-match-data match-again))
2247 ;; MATCH-AGAIN non-nil means accept an
2251 (replace-search search-string limit
2252 regexp-flag delimited-flag
2253 case-fold-search backward)
2254 ;; For speed, use only integers and
2255 ;; reuse the list used last time.
2256 (replace-match-data t real-match-data)))
2258 (> (1- (point)) (point-min))
2259 (< (1+ (point)) (point-max)))
2262 (> (1- (point)) limit)
2263 (< (1+ (point)) limit))))
2264 ;; If not accepting adjacent matches,
2265 ;; move one char to the right before
2266 ;; searching again. Undo the motion
2267 ;; if the search fails.
2268 (let ((opoint (point)))
2269 (forward-char (if backward -1 1))
2270 (if (replace-search search-string limit
2271 regexp-flag delimited-flag
2272 case-fold-search backward)
2278 ;; Record whether the match is nonempty, to avoid an infinite loop
2279 ;; repeatedly matching the same empty string.
2280 (setq nonempty-match
2281 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2283 ;; If the match is empty, record that the next one can't be
2286 ;; Otherwise, if matching a regular expression, do the next
2287 ;; match now, since the replacement for this match may
2288 ;; affect whether the next match is adjacent to this one.
2289 ;; If that match is empty, don't use it.
2292 (or (not regexp-flag)
2294 (looking-back search-string nil)
2295 (looking-at search-string))
2296 (let ((match (match-data)))
2297 (and (/= (nth 0 match) (nth 1 match))
2301 ;; Optionally ignore matches that have a read-only property.
2302 ((not (or (not query-replace-skip-read-only)
2303 (not (text-property-not-all
2304 (nth 0 real-match-data) (nth 1 real-match-data)
2306 (setq skip-read-only-count (1+ skip-read-only-count)))
2307 ;; Optionally filter out matches.
2308 ((not (funcall isearch-filter-predicate
2309 (nth 0 real-match-data) (nth 1 real-match-data)))
2310 (setq skip-filtered-count (1+ skip-filtered-count)))
2311 ;; Optionally ignore invisible matches.
2312 ((not (or (eq search-invisible t)
2313 ;; Don't open overlays for automatic replacements.
2314 (and (not query-flag) search-invisible)
2315 ;; Open hidden overlays for interactive replacements.
2316 (not (isearch-range-invisible
2317 (nth 0 real-match-data) (nth 1 real-match-data)))))
2318 (setq skip-invisible-count (1+ skip-invisible-count)))
2320 ;; Calculate the replacement string, if necessary.
2322 (set-match-data real-match-data)
2323 (setq next-replacement
2324 (funcall (car replacements) (cdr replacements)
2326 (if (not query-flag)
2328 (unless (or literal noedit)
2330 (nth 0 real-match-data) (nth 1 real-match-data)
2331 start end search-string
2332 regexp-flag delimited-flag case-fold-search backward))
2334 (replace-match-maybe-edit
2335 next-replacement nocasify literal
2336 noedit real-match-data backward)
2337 replace-count (1+ replace-count)))
2339 (let (done replaced key def)
2340 ;; Loop reading commands until one of them sets done,
2341 ;; which means it has finished handling this
2342 ;; occurrence. Any command that sets `done' should
2343 ;; leave behind proper match data for the stack.
2344 ;; Commands not setting `done' need to adjust
2345 ;; `real-match-data'.
2347 (set-match-data real-match-data)
2348 (run-hooks 'replace-update-post-hook) ; Before `replace-highlight'.
2350 (match-beginning 0) (match-end 0)
2351 start end search-string
2352 regexp-flag delimited-flag case-fold-search backward)
2353 ;; Obtain the matched groups: needed only when
2354 ;; regexp-flag non nil.
2355 (when (and last-was-undo regexp-flag)
2356 (setq last-was-undo nil
2359 (goto-char (match-beginning 0))
2360 (looking-at search-string)
2361 (match-data t real-match-data))))
2362 ;; Matched string and next-replacement-replaced
2364 (setq search-string-replaced (buffer-substring-no-properties
2367 next-replacement-replaced
2368 (query-replace-descr
2370 (set-match-data real-match-data)
2371 (match-substitute-replacement
2372 next-replacement nocasify literal))))
2373 ;; Bind message-log-max so we don't fill up the
2374 ;; message log with a bunch of identical messages.
2375 (let ((message-log-max nil)
2376 (replacement-presentation
2377 (if query-replace-show-replacement
2379 (set-match-data real-match-data)
2380 (match-substitute-replacement next-replacement
2384 (query-replace-descr from-string)
2385 (query-replace-descr replacement-presentation)))
2386 (setq key (read-event))
2387 ;; Necessary in case something happens during
2388 ;; read-event that clobbers the match data.
2389 (set-match-data real-match-data)
2390 (setq key (vector key))
2391 (setq def (lookup-key map key))
2392 ;; Restore the match data while we process the command.
2393 (cond ((eq def 'help)
2394 (with-output-to-temp-buffer "*Help*"
2396 (concat "Query replacing "
2398 (or (and (symbolp delimited-flag)
2400 'isearch-message-prefix))
2402 (if regexp-flag "regexp " "")
2403 (if backward "backward " "")
2404 from-string " with "
2405 next-replacement ".\n\n"
2406 (substitute-command-keys
2407 query-replace-help)))
2408 (with-current-buffer standard-output
2411 (setq keep-going nil)
2413 ((eq def 'exit-current)
2414 (setq multi-buffer t keep-going nil done t))
2417 (let ((elt (pop stack)))
2418 (goto-char (nth 0 elt))
2419 (setq replaced (nth 1 elt)
2424 (message "No previous match")
2425 (ding 'no-terminate)
2427 ((or (eq def 'undo) (eq def 'undo-all))
2430 (message "Nothing to undo")
2431 (ding 'no-terminate)
2434 (stack-len (length stack))
2435 (num-replacements 0)
2438 (while (and (< stack-idx stack-len)
2441 (let* ((elt (nth stack-idx stack)))
2443 stack-idx (1+ stack-idx)
2444 replaced (nth 1 elt)
2445 ;; Bind swapped values
2446 ;; (search-string <--> replacement)
2447 search-string (nth (if replaced 4 3) elt)
2448 next-replacement (nth (if replaced 3 4) elt)
2449 search-string-replaced search-string
2450 next-replacement-replaced next-replacement)
2452 (when (and (= stack-idx stack-len)
2454 (zerop num-replacements))
2455 (message "Nothing to undo")
2456 (ding 'no-terminate)
2460 (setq stack (nthcdr stack-idx stack))
2461 (goto-char (nth 0 elt))
2462 (set-match-data (nth 2 elt))
2463 (setq real-match-data
2465 (goto-char (match-beginning 0))
2466 (looking-at search-string)
2467 (match-data t (nth 2 elt)))
2469 (replace-match-maybe-edit
2470 next-replacement nocasify literal
2471 noedit real-match-data backward)
2472 replace-count (1- replace-count)
2475 (goto-char (match-beginning 0))
2476 (looking-at next-replacement)
2477 (match-data t (nth 2 elt))))
2478 ;; Set replaced nil to keep in loop
2479 (when (eq def 'undo-all)
2481 stack-len (- stack-len stack-idx)
2484 (1+ num-replacements))))))
2485 (when (and (eq def 'undo-all)
2486 (null (zerop num-replacements)))
2487 (message "Undid %d %s" num-replacements
2488 (if (= num-replacements 1)
2491 (ding 'no-terminate)
2493 (setq replaced nil last-was-undo t)))
2497 (replace-match-maybe-edit
2498 next-replacement nocasify literal
2499 noedit real-match-data backward)
2500 replace-count (1+ replace-count)))
2501 (setq done t replaced t))
2502 ((eq def 'act-and-exit)
2505 (replace-match-maybe-edit
2506 next-replacement nocasify literal
2507 noedit real-match-data backward)
2508 replace-count (1+ replace-count)))
2509 (setq keep-going nil)
2510 (setq done t replaced t))
2511 ((eq def 'act-and-show)
2514 (replace-match-maybe-edit
2515 next-replacement nocasify literal
2516 noedit real-match-data backward)
2517 replace-count (1+ replace-count)
2518 real-match-data (replace-match-data
2521 ((or (eq def 'automatic) (eq def 'automatic-all))
2524 (replace-match-maybe-edit
2525 next-replacement nocasify literal
2526 noedit real-match-data backward)
2527 replace-count (1+ replace-count)))
2528 (setq done t query-flag nil replaced t)
2529 (if (eq def 'automatic-all) (setq multi-buffer t)))
2533 ;; `this-command' has the value `query-replace',
2534 ;; so we need to bind it to `recenter-top-bottom'
2535 ;; to allow it to detect a sequence of `C-l'.
2536 (let ((this-command 'recenter-top-bottom)
2537 (last-command 'recenter-top-bottom))
2538 (recenter-top-bottom)))
2540 (let ((opos (point-marker)))
2541 (setq real-match-data (replace-match-data
2544 (goto-char (match-beginning 0))
2546 (save-window-excursion
2549 (set-marker opos nil))
2550 ;; Before we make the replacement,
2551 ;; decide whether the search string
2552 ;; can match again just after this match.
2553 (if (and regexp-flag nonempty-match)
2554 (setq match-again (and (looking-at search-string)
2556 ;; Edit replacement.
2557 ((eq def 'edit-replacement)
2558 (setq real-match-data (replace-match-data
2562 (read-string "Edit replacement string: "
2566 (set-match-data real-match-data)
2568 (replace-match-maybe-edit
2569 next-replacement nocasify literal noedit
2570 real-match-data backward)
2574 ((eq def 'delete-and-edit)
2575 (replace-match "" t t)
2576 (setq real-match-data (replace-match-data
2577 nil real-match-data))
2578 (replace-dehighlight)
2579 (save-excursion (recursive-edit))
2581 ;; Note: we do not need to treat `exit-prefix'
2582 ;; specially here, since we reread
2583 ;; any unrecognized character.
2585 (setq this-command 'mode-exited)
2586 (setq keep-going nil)
2587 (setq unread-command-events
2588 (append (listify-key-sequence key)
2589 unread-command-events))
2591 (when query-replace-lazy-highlight
2592 ;; Force lazy rehighlighting only after replacements.
2593 (if (not (memq def '(skip backup)))
2594 (setq isearch-lazy-highlight-last-string nil)))
2595 (unless (eq def 'recenter)
2596 ;; Reset recenter cycling order to initial position.
2597 (setq recenter-last-op nil)))
2598 ;; Record previous position for ^ when we move on.
2599 ;; Change markers to numbers in the match data
2600 ;; since lots of markers slow down editing.
2601 (push (list (point) replaced
2602 ;;; If the replacement has already happened, all we need is the
2603 ;;; current match start and end. We could get this with a trivial
2605 ;;; (save-excursion (goto-char (match-beginning 0))
2606 ;;; (search-forward (match-string 0))
2608 ;;; if we really wanted to avoid manually constructing match data.
2609 ;;; Adding current-buffer is necessary so that match-data calls can
2610 ;;; return markers which are appropriate for editing.
2617 search-string-replaced
2618 next-replacement-replaced)
2620 (setq next-replacement-replaced nil
2621 search-string-replaced nil))))))
2622 (replace-dehighlight))
2623 (or unread-command-events
2624 (message "Replaced %d occurrence%s%s"
2626 (if (= replace-count 1) "" "s")
2627 (if (> (+ skip-read-only-count
2629 skip-invisible-count) 0)
2630 (format " (skipped %s)"
2634 (if (> skip-read-only-count 0)
2635 (format "%s read-only"
2636 skip-read-only-count))
2637 (if (> skip-invisible-count 0)
2638 (format "%s invisible"
2639 skip-invisible-count))
2640 (if (> skip-filtered-count 0)
2641 (format "%s filtered out"
2642 skip-filtered-count))))
2645 (or (and keep-going stack) multi-buffer)))
2649 ;;; replace.el ends here