1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2016 Free
4 ;; Software Foundation, Inc.
6 ;; Maintainer: emacs-devel@gnu.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; This package supplies the string and regular-expression replace functions
27 ;; documented in the Emacs user's manual.
31 (defcustom case-replace t
32 "Non-nil means `query-replace' should preserve case in replacements."
36 (defcustom replace-character-fold nil
37 "Non-nil means replacement commands should do character folding in matches.
38 This means, for instance, that \\=' will match a large variety of
40 This variable affects `query-replace' and `replace-string', but not
46 (defcustom replace-lax-whitespace nil
47 "Non-nil means `query-replace' matches a sequence of whitespace chars.
48 When you enter a space or spaces in the strings to be replaced,
49 it will match any sequence matched by the regexp `search-whitespace-regexp'."
54 (defcustom replace-regexp-lax-whitespace nil
55 "Non-nil means `query-replace-regexp' matches a sequence of whitespace chars.
56 When you enter a space or spaces in the regexps to be replaced,
57 it will match any sequence matched by the regexp `search-whitespace-regexp'."
62 (defvar query-replace-history nil
63 "Default history list for query-replace commands.
64 See `query-replace-from-history-variable' and
65 `query-replace-to-history-variable'.")
67 (defvar query-replace-defaults nil
68 "Default values of FROM-STRING and TO-STRING for `query-replace'.
69 This is a list of cons cells (FROM-STRING . TO-STRING), or nil
70 if there are no default values.")
72 (defvar query-replace-interactive nil
73 "Non-nil means `query-replace' uses the last search string.
74 That becomes the \"string to replace\".")
75 (make-obsolete-variable 'query-replace-interactive
76 "use `M-n' to pull the last incremental search string
77 to the minibuffer that reads the string to replace, or invoke replacements
78 from Isearch by using a key sequence like `C-s C-s M-%'." "24.3")
80 (defcustom query-replace-from-to-separator
81 (propertize (if (char-displayable-p ?→
) " → " " -> ")
82 'face
'minibuffer-prompt
)
83 "String that separates FROM and TO in the history of replacement pairs."
84 ;; Avoids error when attempt to autoload char-displayable-p fails
85 ;; while preparing to dump, also stops customize-rogue listing this.
86 :initialize
'custom-initialize-delay
88 :type
'(choice string
(sexp :tag
"Display specification"))
91 (defcustom query-replace-from-history-variable
'query-replace-history
92 "History list to use for the FROM argument of `query-replace' commands.
93 The value of this variable should be a symbol; that symbol
94 is used as a variable to hold a history list for the strings
95 or patterns to be replaced."
100 (defcustom query-replace-to-history-variable
'query-replace-history
101 "History list to use for the TO argument of `query-replace' commands.
102 The value of this variable should be a symbol; that symbol
103 is used as a variable to hold a history list for replacement
104 strings or patterns."
109 (defcustom query-replace-skip-read-only nil
110 "Non-nil means `query-replace' and friends ignore read-only matches."
115 (defcustom query-replace-show-replacement t
116 "Non-nil means show substituted replacement text in the minibuffer.
117 This variable affects only `query-replace-regexp'."
122 (defcustom query-replace-highlight t
123 "Non-nil means to highlight matches during query replacement."
127 (defcustom query-replace-lazy-highlight t
128 "Controls the lazy-highlighting during query replacements.
129 When non-nil, all text in the buffer matching the current match
130 is highlighted lazily using isearch lazy highlighting (see
131 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
133 :group
'lazy-highlight
137 (defface query-replace
138 '((t (:inherit isearch
)))
139 "Face for highlighting query replacement matches."
143 (defvar replace-count
0
144 "Number of replacements done so far.
145 See `replace-regexp' and `query-replace-regexp-eval'.")
147 (defun query-replace-descr (string)
148 (mapconcat 'isearch-text-char-description string
""))
150 (defun query-replace--split-string (string)
151 "Split string STRING at a character with property `separator'"
152 (let* ((length (length string
))
153 (split-pos (text-property-any 0 length
'separator t string
)))
155 (substring-no-properties string
)
156 (cl-assert (not (text-property-any (1+ split-pos
) length
'separator t string
)))
157 (cons (substring-no-properties string
0 split-pos
)
158 (substring-no-properties string
(1+ split-pos
) length
)))))
160 (defun query-replace-read-from (prompt regexp-flag
)
161 "Query and return the `from' argument of a query-replace operation.
162 The return value can also be a pair (FROM . TO) indicating that the user
163 wants to replace FROM with TO."
164 (if query-replace-interactive
165 (car (if regexp-flag regexp-search-ring search-ring
))
166 ;; Reevaluating will check char-displayable-p that is
167 ;; unavailable while preparing to dump.
168 (custom-reevaluate-setting 'query-replace-from-to-separator
)
169 (let* ((history-add-new-input nil
)
170 (text-property-default-nonsticky
171 (cons '(separator . t
) text-property-default-nonsticky
))
173 (when query-replace-from-to-separator
175 'display query-replace-from-to-separator
177 (query-replace-from-to-history
180 (mapcar (lambda (from-to)
181 (concat (query-replace-descr (car from-to
))
183 (query-replace-descr (cdr from-to
))))
184 query-replace-defaults
))
185 (symbol-value query-replace-from-history-variable
)))
186 (minibuffer-allow-text-properties t
) ; separator uses text-properties
188 (if (and query-replace-defaults separator
)
189 (format "%s (default %s): " prompt
(car query-replace-from-to-history
))
190 (format "%s: " prompt
)))
192 ;; The save-excursion here is in case the user marks and copies
193 ;; a region in order to specify the minibuffer input.
194 ;; That should not clobber the region for the query-replace itself.
197 (read-regexp prompt nil
'query-replace-from-to-history
)
198 (read-from-minibuffer
199 prompt nil nil nil
'query-replace-from-to-history
200 (car (if regexp-flag regexp-search-ring search-ring
)) t
))))
202 (if (and (zerop (length from
)) query-replace-defaults
)
203 (cons (caar query-replace-defaults
)
204 (query-replace-compile-replacement
205 (cdar query-replace-defaults
) regexp-flag
))
206 (setq from
(query-replace--split-string from
))
207 (when (consp from
) (setq to
(cdr from
) from
(car from
)))
208 (add-to-history query-replace-from-history-variable from nil t
)
209 ;; Warn if user types \n or \t, but don't reject the input.
211 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
212 (let ((match (match-string 3 from
)))
214 ((string= match
"\\n")
215 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
216 ((string= match
"\\t")
217 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
221 (add-to-history query-replace-to-history-variable to nil t
)
222 (add-to-history 'query-replace-defaults
(cons from to
) nil t
)
223 (cons from
(query-replace-compile-replacement to regexp-flag
)))))))
225 (defun query-replace-compile-replacement (to regexp-flag
)
226 "Maybe convert a regexp replacement TO to Lisp.
227 Returns a list suitable for `perform-replace' if necessary,
228 the original string if not."
230 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
))
234 (setq pos
(match-end 0))
235 (push (substring to
0 (- pos
2)) list
)
236 (setq char
(aref to
(1- pos
))
237 to
(substring to pos
))
239 (push '(number-to-string replace-count
) list
))
241 (setq pos
(read-from-string to
))
242 (push `(replace-quote ,(car pos
)) list
)
244 ;; Swallow a space after a symbol
245 ;; if there is a space.
246 (if (and (or (symbolp (car pos
))
247 ;; Swallow a space after 'foo
248 ;; but not after (quote foo).
249 (and (eq (car-safe (car pos
)) 'quote
)
250 (not (= ?\
( (aref to
0)))))
251 (eq (string-match " " to
(cdr pos
))
255 (setq to
(substring to end
)))))
256 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
)))
257 (setq to
(nreverse (delete "" (cons to list
))))
258 (replace-match-string-symbols to
)
259 (cons 'replace-eval-replacement
266 (defun query-replace-read-to (from prompt regexp-flag
)
267 "Query and return the `to' argument of a query-replace operation."
268 (query-replace-compile-replacement
270 (let* ((history-add-new-input nil
)
271 (to (read-from-minibuffer
272 (format "%s %s with: " prompt
(query-replace-descr from
))
274 query-replace-to-history-variable from t
)))
275 (add-to-history query-replace-to-history-variable to nil t
)
276 (add-to-history 'query-replace-defaults
(cons from to
) nil t
)
280 (defun query-replace-read-args (prompt regexp-flag
&optional noerror
)
282 (barf-if-buffer-read-only))
283 (let* ((from (query-replace-read-from prompt regexp-flag
))
284 (to (if (consp from
) (prog1 (cdr from
) (setq from
(car from
)))
285 (query-replace-read-to from prompt regexp-flag
))))
287 (and current-prefix-arg
(not (eq current-prefix-arg
'-
)))
288 (and current-prefix-arg
(eq current-prefix-arg
'-
)))))
290 (defun query-replace (from-string to-string
&optional delimited start end backward region-noncontiguous-p
)
291 "Replace some occurrences of FROM-STRING with TO-STRING.
292 As each match is found, the user must type a character saying
293 what to do with it. For directions, type \\[help-command] at that time.
295 In Transient Mark mode, if the mark is active, operate on the contents
296 of the region. Otherwise, operate from point to the end of the buffer.
298 Use \\<minibuffer-local-map>\\[next-history-element] \
299 to pull the last incremental search string to the minibuffer
300 that reads FROM-STRING, or invoke replacements from
301 incremental search with a key sequence like `C-s C-s M-%'
302 to use its current search string as the string to replace.
304 Matching is independent of case if `case-fold-search' is non-nil and
305 FROM-STRING has no uppercase letters. Replacement transfers the case
306 pattern of the old text to the new text, if `case-replace' and
307 `case-fold-search' are non-nil and FROM-STRING has no uppercase
308 letters. (Transferring the case pattern means that if the old text
309 matched is all caps, or capitalized, then its replacement is upcased
312 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
313 ignore hidden matches if `search-invisible' is nil, and ignore more
314 matches using `isearch-filter-predicate'.
316 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
317 to be replaced will match a sequence of whitespace chars defined by the
318 regexp in `search-whitespace-regexp'.
320 If `replace-character-fold' is non-nil, matching uses character folding,
321 i.e. it ignores diacritics and other differences between equivalent
324 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
325 only matches surrounded by word boundaries. A negative prefix arg means
328 Fourth and fifth arg START and END specify the region to operate on.
330 To customize possible responses, change the bindings in `query-replace-map'."
333 (query-replace-read-args
334 (concat "Query replace"
335 (if current-prefix-arg
336 (if (eq current-prefix-arg
'-
) " backward" " word")
338 (if (use-region-p) " in region" ""))
340 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
341 ;; These are done separately here
342 ;; so that command-history will record these expressions
343 ;; rather than the values they had this time.
344 (if (use-region-p) (region-beginning))
345 (if (use-region-p) (region-end))
347 (if (use-region-p) (region-noncontiguous-p)))))
348 (perform-replace from-string to-string t nil delimited nil nil start end backward region-noncontiguous-p
))
350 (define-key esc-map
"%" 'query-replace
)
352 (defun query-replace-regexp (regexp to-string
&optional delimited start end backward region-noncontiguous-p
)
353 "Replace some things after point matching REGEXP with TO-STRING.
354 As each match is found, the user must type a character saying
355 what to do with it. For directions, type \\[help-command] at that time.
357 In Transient Mark mode, if the mark is active, operate on the contents
358 of the region. Otherwise, operate from point to the end of the buffer.
360 Use \\<minibuffer-local-map>\\[next-history-element] \
361 to pull the last incremental search regexp to the minibuffer
362 that reads REGEXP, or invoke replacements from
363 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
364 to use its current search regexp as the regexp to replace.
366 Matching is independent of case if `case-fold-search' is non-nil and
367 REGEXP has no uppercase letters. Replacement transfers the case
368 pattern of the old text to the new text, if `case-replace' and
369 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
370 \(Transferring the case pattern means that if the old text matched is
371 all caps, or capitalized, then its replacement is upcased or
374 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
375 ignore hidden matches if `search-invisible' is nil, and ignore more
376 matches using `isearch-filter-predicate'.
378 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
379 to be replaced will match a sequence of whitespace chars defined by the
380 regexp in `search-whitespace-regexp'.
382 This function is not affected by `replace-character-fold'.
384 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
385 only matches surrounded by word boundaries. A negative prefix arg means
388 Fourth and fifth arg START and END specify the region to operate on.
390 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
391 and `\\=\\N' (where N is a digit) stands for
392 whatever what matched the Nth `\\(...\\)' in REGEXP.
393 `\\?' lets you edit the replacement text in the minibuffer
394 at the given position for each replacement.
396 In interactive calls, the replacement text can contain `\\,'
397 followed by a Lisp expression. Each
398 replacement evaluates that expression to compute the replacement
399 string. Inside of that expression, `\\&' is a string denoting the
400 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
401 for the whole or a partial match converted to a number with
402 `string-to-number', and `\\#' itself for the number of replacements
403 done so far (starting with zero).
405 If the replacement expression is a symbol, write a space after it
406 to terminate it. One space there, if any, will be discarded.
408 When using those Lisp features interactively in the replacement
409 text, TO-STRING is actually made a list instead of a string.
410 Use \\[repeat-complex-command] after this command for details."
413 (query-replace-read-args
414 (concat "Query replace"
415 (if current-prefix-arg
416 (if (eq current-prefix-arg
'-
) " backward" " word")
419 (if (use-region-p) " in region" ""))
421 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
422 ;; These are done separately here
423 ;; so that command-history will record these expressions
424 ;; rather than the values they had this time.
425 (if (use-region-p) (region-beginning))
426 (if (use-region-p) (region-end))
428 (if (use-region-p) (region-noncontiguous-p)))))
429 (perform-replace regexp to-string t t delimited nil nil start end backward region-noncontiguous-p
))
431 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
433 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
434 "Replace some things after point matching REGEXP with the result of TO-EXPR.
436 Interactive use of this function is deprecated in favor of the
437 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
438 using `search-forward-regexp' and `replace-match' is preferred.
440 As each match is found, the user must type a character saying
441 what to do with it. For directions, type \\[help-command] at that time.
443 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
444 reference `replace-count' to get the number of replacements already made.
445 If the result of TO-EXPR is not a string, it is converted to one using
446 `prin1-to-string' with the NOESCAPE argument (which see).
448 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
449 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
450 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
451 Use `\\#&' or `\\#N' if you want a number instead of a string.
452 In interactive use, `\\#' in itself stands for `replace-count'.
454 In Transient Mark mode, if the mark is active, operate on the contents
455 of the region. Otherwise, operate from point to the end of the buffer.
457 Use \\<minibuffer-local-map>\\[next-history-element] \
458 to pull the last incremental search regexp to the minibuffer
461 Preserves case in each replacement if `case-replace' and `case-fold-search'
462 are non-nil and REGEXP has no uppercase letters.
464 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
465 ignore hidden matches if `search-invisible' is nil, and ignore more
466 matches using `isearch-filter-predicate'.
468 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
469 to be replaced will match a sequence of whitespace chars defined by the
470 regexp in `search-whitespace-regexp'.
472 This function is not affected by `replace-character-fold'.
474 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
475 only matches that are surrounded by word boundaries.
476 Fourth and fifth arg START and END specify the region to operate on."
477 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
478 for interactive calls, and `search-forward-regexp'/`replace-match'
479 for Lisp calls." "22.1"))
482 (barf-if-buffer-read-only)
484 ;; Let-bind the history var to disable the "foo -> bar"
485 ;; default. Maybe we shouldn't disable this default, but
486 ;; for now I'll leave it off. --Stef
487 (let ((query-replace-defaults nil
))
488 (query-replace-read-from "Query replace regexp" t
)))
489 (to (list (read-from-minibuffer
490 (format "Query replace regexp %s with eval: "
491 (query-replace-descr from
))
492 nil nil t query-replace-to-history-variable from t
))))
493 ;; We make TO a list because replace-match-string-symbols requires one,
494 ;; and the user might enter a single token.
495 (replace-match-string-symbols to
)
496 (list from
(car to
) current-prefix-arg
497 (if (use-region-p) (region-beginning))
498 (if (use-region-p) (region-end))))))
499 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
500 t
'literal delimited nil nil start end
))
502 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
503 "Replace some matches for REGEXP with various strings, in rotation.
504 The second argument TO-STRINGS contains the replacement strings, separated
505 by spaces. This command works like `query-replace-regexp' except that
506 each successive replacement uses the next successive replacement string,
507 wrapping around from the last such string to the first.
509 In Transient Mark mode, if the mark is active, operate on the contents
510 of the region. Otherwise, operate from point to the end of the buffer.
512 Non-interactively, TO-STRINGS may be a list of replacement strings.
514 Interactively, reads the regexp using `read-regexp'.
515 Use \\<minibuffer-local-map>\\[next-history-element] \
516 to pull the last incremental search regexp to the minibuffer
519 A prefix argument N says to use each replacement string N times
520 before rotating to the next.
521 Fourth and fifth arg START and END specify the region to operate on."
523 (let* ((from (read-regexp "Map query replace (regexp): " nil
524 query-replace-from-history-variable
))
525 (to (read-from-minibuffer
526 (format "Query replace %s with (space-separated strings): "
527 (query-replace-descr from
))
529 query-replace-to-history-variable from t
)))
531 (and current-prefix-arg
532 (prefix-numeric-value current-prefix-arg
))
533 (if (use-region-p) (region-beginning))
534 (if (use-region-p) (region-end)))))
536 (if (listp to-strings
)
537 (setq replacements to-strings
)
538 (while (/= (length to-strings
) 0)
539 (if (string-match " " to-strings
)
542 (list (substring to-strings
0
543 (string-match " " to-strings
))))
544 to-strings
(substring to-strings
545 (1+ (string-match " " to-strings
))))
546 (setq replacements
(append replacements
(list to-strings
))
548 (perform-replace regexp replacements t t nil n nil start end
)))
550 (defun replace-string (from-string to-string
&optional delimited start end backward
)
551 "Replace occurrences of FROM-STRING with TO-STRING.
552 Preserve case in each match if `case-replace' and `case-fold-search'
553 are non-nil and FROM-STRING has no uppercase letters.
554 \(Preserving case means that if the string matched is all caps, or capitalized,
555 then its replacement is upcased or capitalized.)
557 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
558 ignore hidden matches if `search-invisible' is nil, and ignore more
559 matches using `isearch-filter-predicate'.
561 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
562 to be replaced will match a sequence of whitespace chars defined by the
563 regexp in `search-whitespace-regexp'.
565 If `replace-character-fold' is non-nil, matching uses character folding,
566 i.e. it ignores diacritics and other differences between equivalent
569 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
570 only matches surrounded by word boundaries. A negative prefix arg means
573 Operates on the region between START and END (if both are nil, from point
574 to the end of the buffer). Interactively, if Transient Mark mode is
575 enabled and the mark is active, operates on the contents of the region;
576 otherwise from point to the end of the buffer.
578 Use \\<minibuffer-local-map>\\[next-history-element] \
579 to pull the last incremental search string to the minibuffer
580 that reads FROM-STRING.
582 This function is usually the wrong thing to use in a Lisp program.
583 What you probably want is a loop like this:
584 (while (search-forward FROM-STRING nil t)
585 (replace-match TO-STRING nil t))
586 which will run faster and will not set the mark or print anything.
587 \(You may need a more complex loop if FROM-STRING can match the null string
588 and TO-STRING is also null.)"
589 (declare (interactive-only
590 "use `search-forward' and `replace-match' instead."))
593 (query-replace-read-args
595 (if current-prefix-arg
596 (if (eq current-prefix-arg
'-
) " backward" " word")
599 (if (use-region-p) " in region" ""))
601 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
602 (if (use-region-p) (region-beginning))
603 (if (use-region-p) (region-end))
605 (perform-replace from-string to-string nil nil delimited nil nil start end backward
))
607 (defun replace-regexp (regexp to-string
&optional delimited start end backward
)
608 "Replace things after point matching REGEXP with TO-STRING.
609 Preserve case in each match if `case-replace' and `case-fold-search'
610 are non-nil and REGEXP has no uppercase letters.
612 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
613 ignore hidden matches if `search-invisible' is nil, and ignore more
614 matches using `isearch-filter-predicate'.
616 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
617 to be replaced will match a sequence of whitespace chars defined by the
618 regexp in `search-whitespace-regexp'.
620 This function is not affected by `replace-character-fold'
622 In Transient Mark mode, if the mark is active, operate on the contents
623 of the region. Otherwise, operate from point to the end of the buffer.
625 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
626 only matches surrounded by word boundaries. A negative prefix arg means
629 Fourth and fifth arg START and END specify the region to operate on.
631 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
632 and `\\=\\N' (where N is a digit) stands for
633 whatever what matched the Nth `\\(...\\)' in REGEXP.
634 `\\?' lets you edit the replacement text in the minibuffer
635 at the given position for each replacement.
637 In interactive calls, the replacement text may contain `\\,'
638 followed by a Lisp expression used as part of the replacement
639 text. Inside of that expression, `\\&' is a string denoting the
640 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
641 numeric values from `string-to-number', and `\\#' itself for
642 `replace-count', the number of replacements occurred so far.
644 If your Lisp expression is an identifier and the next letter in
645 the replacement string would be interpreted as part of it, you
646 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
647 for this particular case you may also enter `\\#' in the
648 replacement text directly.
650 When using those Lisp features interactively in the replacement
651 text, TO-STRING is actually made a list instead of a string.
652 Use \\[repeat-complex-command] after this command for details.
654 Use \\<minibuffer-local-map>\\[next-history-element] \
655 to pull the last incremental search regexp to the minibuffer
658 This function is usually the wrong thing to use in a Lisp program.
659 What you probably want is a loop like this:
660 (while (re-search-forward REGEXP nil t)
661 (replace-match TO-STRING nil nil))
662 which will run faster and will not set the mark or print anything."
663 (declare (interactive-only
664 "use `re-search-forward' and `replace-match' instead."))
667 (query-replace-read-args
669 (if current-prefix-arg
670 (if (eq current-prefix-arg
'-
) " backward" " word")
673 (if (use-region-p) " in region" ""))
675 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
676 (if (use-region-p) (region-beginning))
677 (if (use-region-p) (region-end))
679 (perform-replace regexp to-string nil t delimited nil nil start end backward
))
682 (defvar regexp-history nil
683 "History list for some commands that read regular expressions.
685 Maximum length of the history list is determined by the value
686 of `history-length', which see.")
688 (defvar occur-collect-regexp-history
'("\\1")
689 "History of regexp for occur's collect operation")
691 (defcustom read-regexp-defaults-function nil
692 "Function that provides default regexp(s) for `read-regexp'.
693 This function should take no arguments and return one of: nil, a
694 regexp, or a list of regexps. Interactively, `read-regexp' uses
695 the return value of this function for its DEFAULT argument.
697 As an example, set this variable to `find-tag-default-as-regexp'
698 to default to the symbol at point.
700 To provide different default regexps for different commands,
701 the function that you set this to can check `this-command'."
703 (const :tag
"No default regexp reading function" nil
)
704 (const :tag
"Latest regexp history" regexp-history-last
)
705 (function-item :tag
"Tag at point"
707 (function-item :tag
"Tag at point as regexp"
708 find-tag-default-as-regexp
)
709 (function-item :tag
"Tag at point as symbol regexp"
710 find-tag-default-as-symbol-regexp
)
711 (function :tag
"Your choice of function"))
715 (defun read-regexp-suggestions ()
716 "Return a list of standard suggestions for `read-regexp'.
717 By default, the list includes the tag at point, the last isearch regexp,
718 the last isearch string, and the last replacement regexp. `read-regexp'
719 appends the list returned by this function to the end of values available
720 via \\<minibuffer-local-map>\\[next-history-element]."
722 (find-tag-default-as-regexp)
723 (find-tag-default-as-symbol-regexp)
724 (car regexp-search-ring
)
725 (regexp-quote (or (car search-ring
) ""))
726 (car (symbol-value query-replace-from-history-variable
))))
728 (defun read-regexp (prompt &optional defaults history
)
729 "Read and return a regular expression as a string.
730 Prompt with the string PROMPT. If PROMPT ends in \":\" (followed by
731 optional whitespace), use it as-is. Otherwise, add \": \" to the end,
732 possibly preceded by the default result (see below).
734 The optional argument DEFAULTS can be either: nil, a string, a list
735 of strings, or a symbol. We use DEFAULTS to construct the default
736 return value in case of empty input.
738 If DEFAULTS is a string, we use it as-is.
740 If DEFAULTS is a list of strings, the first element is the
741 default return value, but all the elements are accessible
742 using the history command \\<minibuffer-local-map>\\[next-history-element].
744 If DEFAULTS is a non-nil symbol, then if `read-regexp-defaults-function'
745 is non-nil, we use that in place of DEFAULTS in the following:
746 If DEFAULTS is the symbol `regexp-history-last', we use the first
747 element of HISTORY (if specified) or `regexp-history'.
748 If DEFAULTS is a function, we call it with no arguments and use
749 what it returns, which should be either nil, a string, or a list of strings.
751 We append the standard values from `read-regexp-suggestions' to DEFAULTS
754 If the first element of DEFAULTS is non-nil (and if PROMPT does not end
755 in \":\", followed by optional whitespace), we add it to the prompt.
757 The optional argument HISTORY is a symbol to use for the history list.
758 If nil, uses `regexp-history'."
760 (if (and defaults
(symbolp defaults
))
762 ((eq (or read-regexp-defaults-function defaults
)
763 'regexp-history-last
)
764 (car (symbol-value (or history
'regexp-history
))))
765 ((functionp (or read-regexp-defaults-function defaults
))
766 (funcall (or read-regexp-defaults-function defaults
))))
768 (default (if (consp defaults
) (car defaults
) defaults
))
769 (suggestions (if (listp defaults
) defaults
(list defaults
)))
770 (suggestions (append suggestions
(read-regexp-suggestions)))
771 (suggestions (delete-dups (delq nil
(delete "" suggestions
))))
772 ;; Do not automatically add default to the history for empty input.
773 (history-add-new-input nil
)
774 (input (read-from-minibuffer
775 (cond ((string-match-p ":[ \t]*\\'" prompt
)
777 ((and default
(> (length default
) 0))
778 (format "%s (default %s): " prompt
779 (query-replace-descr default
)))
781 (format "%s: " prompt
)))
782 nil nil nil
(or history
'regexp-history
) suggestions t
)))
784 ;; Return the default value when the user enters empty input.
785 (prog1 (or default input
)
787 (add-to-history (or history
'regexp-history
) default
)))
788 ;; Otherwise, add non-empty input to the history and return input.
790 (add-to-history (or history
'regexp-history
) input
)))))
793 (defalias 'delete-non-matching-lines
'keep-lines
)
794 (defalias 'delete-matching-lines
'flush-lines
)
795 (defalias 'count-matches
'how-many
)
798 (defun keep-lines-read-args (prompt)
799 "Read arguments for `keep-lines' and friends.
800 Prompt for a regexp with PROMPT.
801 Value is a list, (REGEXP)."
802 (list (read-regexp prompt
) nil nil t
))
804 (defun keep-lines (regexp &optional rstart rend interactive
)
805 "Delete all lines except those containing matches for REGEXP.
806 A match split across lines preserves all the lines it lies in.
807 When called from Lisp (and usually interactively as well, see below)
808 applies to all lines starting after point.
810 If REGEXP contains upper case characters (excluding those preceded by `\\')
811 and `search-upper-case' is non-nil, the matching is case-sensitive.
813 Second and third arg RSTART and REND specify the region to operate on.
814 This command operates on (the accessible part of) all lines whose
815 accessible part is entirely contained in the region determined by RSTART
816 and REND. (A newline ending a line counts as part of that line.)
818 Interactively, in Transient Mark mode when the mark is active, operate
819 on all lines whose accessible part is entirely contained in the region.
820 Otherwise, the command applies to all lines starting after point.
821 When calling this function from Lisp, you can pretend that it was
822 called interactively by passing a non-nil INTERACTIVE argument.
824 This function starts looking for the next match from the end of
825 the previous match. Hence, it ignores matches that overlap
826 a previously found match."
830 (barf-if-buffer-read-only)
831 (keep-lines-read-args "Keep lines containing match for regexp")))
834 (goto-char (min rstart rend
))
838 (goto-char (max rstart rend
))
839 (unless (or (bolp) (eobp))
842 (if (and interactive
(use-region-p))
843 (setq rstart
(region-beginning)
845 (goto-char (region-end))
846 (unless (or (bolp) (eobp))
850 rend
(point-max-marker)))
853 (or (bolp) (forward-line 1))
854 (let ((start (point))
856 (if (and case-fold-search search-upper-case
)
857 (isearch-no-upper-case-p regexp t
)
859 (while (< (point) rend
)
860 ;; Start is first char not preserved by previous match.
861 (if (not (re-search-forward regexp rend
'move
))
862 (delete-region start rend
)
863 (let ((end (save-excursion (goto-char (match-beginning 0))
866 ;; Now end is first char preserved by the new match.
868 (delete-region start end
))))
870 (setq start
(save-excursion (forward-line 1) (point)))
871 ;; If the match was empty, avoid matching again at same place.
872 (and (< (point) rend
)
873 (= (match-beginning 0) (match-end 0))
875 (set-marker rend nil
)
879 (defun flush-lines (regexp &optional rstart rend interactive
)
880 "Delete lines containing matches for REGEXP.
881 When called from Lisp (and usually when called interactively as
882 well, see below), applies to the part of the buffer after point.
883 The line point is in is deleted if and only if it contains a
884 match for regexp starting after point.
886 If REGEXP contains upper case characters (excluding those preceded by `\\')
887 and `search-upper-case' is non-nil, the matching is case-sensitive.
889 Second and third arg RSTART and REND specify the region to operate on.
890 Lines partially contained in this region are deleted if and only if
891 they contain a match entirely contained in it.
893 Interactively, in Transient Mark mode when the mark is active, operate
894 on the contents of the region. Otherwise, operate from point to the
895 end of (the accessible portion of) the buffer. When calling this function
896 from Lisp, you can pretend that it was called interactively by passing
897 a non-nil INTERACTIVE argument.
899 If a match is split across lines, all the lines it lies in are deleted.
900 They are deleted _before_ looking for the next match. Hence, a match
901 starting on the same line at which another match ended is ignored."
905 (barf-if-buffer-read-only)
906 (keep-lines-read-args "Flush lines containing match for regexp")))
909 (goto-char (min rstart rend
))
910 (setq rend
(copy-marker (max rstart rend
))))
911 (if (and interactive
(use-region-p))
912 (setq rstart
(region-beginning)
913 rend
(copy-marker (region-end)))
915 rend
(point-max-marker)))
917 (let ((case-fold-search
918 (if (and case-fold-search search-upper-case
)
919 (isearch-no-upper-case-p regexp t
)
922 (while (and (< (point) rend
)
923 (re-search-forward regexp rend t
))
924 (delete-region (save-excursion (goto-char (match-beginning 0))
927 (progn (forward-line 1) (point))))))
928 (set-marker rend nil
)
932 (defun how-many (regexp &optional rstart rend interactive
)
933 "Print and return number of matches for REGEXP following point.
934 When called from Lisp and INTERACTIVE is omitted or nil, just return
935 the number, do not print it; if INTERACTIVE is t, the function behaves
936 in all respects as if it had been called interactively.
938 If REGEXP contains upper case characters (excluding those preceded by `\\')
939 and `search-upper-case' is non-nil, the matching is case-sensitive.
941 Second and third arg RSTART and REND specify the region to operate on.
943 Interactively, in Transient Mark mode when the mark is active, operate
944 on the contents of the region. Otherwise, operate from point to the
945 end of (the accessible portion of) the buffer.
947 This function starts looking for the next match from the end of
948 the previous match. Hence, it ignores matches that overlap
949 a previously found match."
952 (keep-lines-read-args "How many matches for regexp"))
957 (goto-char (min rstart rend
))
958 (setq rend
(max rstart rend
)))
960 (setq rend
(point-max)))
961 (if (and interactive
(use-region-p))
962 (setq rstart
(region-beginning)
970 (if (and case-fold-search search-upper-case
)
971 (isearch-no-upper-case-p regexp t
)
973 (while (and (< (point) rend
)
974 (progn (setq opoint
(point))
975 (re-search-forward regexp rend t
)))
976 (if (= opoint
(point))
978 (setq count
(1+ count
))))
979 (when interactive
(message "%d occurrence%s"
981 (if (= count
1) "" "s")))
985 (defvar occur-menu-map
986 (let ((map (make-sparse-keymap)))
987 (bindings--define-key map
[next-error-follow-minor-mode
]
988 '(menu-item "Auto Occurrence Display"
989 next-error-follow-minor-mode
990 :help
"Display another occurrence when moving the cursor"
991 :button
(:toggle .
(and (boundp 'next-error-follow-minor-mode
)
992 next-error-follow-minor-mode
))))
993 (bindings--define-key map
[separator-1
] menu-bar-separator
)
994 (bindings--define-key map
[kill-this-buffer
]
995 '(menu-item "Kill Occur Buffer" kill-this-buffer
996 :help
"Kill the current *Occur* buffer"))
997 (bindings--define-key map
[quit-window
]
998 '(menu-item "Quit Occur Window" quit-window
999 :help
"Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
1000 (bindings--define-key map
[revert-buffer
]
1001 '(menu-item "Revert Occur Buffer" revert-buffer
1002 :help
"Replace the text in the *Occur* buffer with the results of rerunning occur"))
1003 (bindings--define-key map
[clone-buffer
]
1004 '(menu-item "Clone Occur Buffer" clone-buffer
1005 :help
"Create and return a twin copy of the current *Occur* buffer"))
1006 (bindings--define-key map
[occur-rename-buffer
]
1007 '(menu-item "Rename Occur Buffer" occur-rename-buffer
1008 :help
"Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
1009 (bindings--define-key map
[occur-edit-buffer
]
1010 '(menu-item "Edit Occur Buffer" occur-edit-mode
1011 :help
"Edit the *Occur* buffer and apply changes to the original buffers."))
1012 (bindings--define-key map
[separator-2
] menu-bar-separator
)
1013 (bindings--define-key map
[occur-mode-goto-occurrence-other-window
]
1014 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
1015 :help
"Go to the occurrence the current line describes, in another window"))
1016 (bindings--define-key map
[occur-mode-goto-occurrence
]
1017 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
1018 :help
"Go to the occurrence the current line describes"))
1019 (bindings--define-key map
[occur-mode-display-occurrence
]
1020 '(menu-item "Display Occurrence" occur-mode-display-occurrence
1021 :help
"Display in another window the occurrence the current line describes"))
1022 (bindings--define-key map
[occur-next
]
1023 '(menu-item "Move to Next Match" occur-next
1024 :help
"Move to the Nth (default 1) next match in an Occur mode buffer"))
1025 (bindings--define-key map
[occur-prev
]
1026 '(menu-item "Move to Previous Match" occur-prev
1027 :help
"Move to the Nth (default 1) previous match in an Occur mode buffer"))
1029 "Menu keymap for `occur-mode'.")
1031 (defvar occur-mode-map
1032 (let ((map (make-sparse-keymap)))
1033 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
1034 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
1035 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
1036 (define-key map
"e" 'occur-edit-mode
)
1037 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
1038 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
1039 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
1040 (define-key map
"\M-n" 'occur-next
)
1041 (define-key map
"\M-p" 'occur-prev
)
1042 (define-key map
"r" 'occur-rename-buffer
)
1043 (define-key map
"c" 'clone-buffer
)
1044 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
1045 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
1047 "Keymap for `occur-mode'.")
1049 (defvar occur-revert-arguments nil
1050 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
1051 See `occur-revert-function'.")
1052 (make-variable-buffer-local 'occur-revert-arguments
)
1053 (put 'occur-revert-arguments
'permanent-local t
)
1055 (defcustom occur-mode-hook
'(turn-on-font-lock)
1056 "Hook run when entering Occur mode."
1060 (defcustom occur-hook nil
1061 "Hook run by Occur when there are any matches."
1065 (defcustom occur-mode-find-occurrence-hook nil
1066 "Hook run by Occur after locating an occurrence.
1067 This will be called with the cursor position at the occurrence. An application
1068 for this is to reveal context in an outline-mode when the occurrence is hidden."
1072 (put 'occur-mode
'mode-class
'special
)
1073 (define-derived-mode occur-mode special-mode
"Occur"
1074 "Major mode for output from \\[occur].
1075 \\<occur-mode-map>Move point to one of the items in this buffer, then use
1076 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
1077 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
1080 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
1081 (setq next-error-function
'occur-next-error
))
1086 (defvar occur-edit-mode-map
1087 (let ((map (make-sparse-keymap)))
1088 (set-keymap-parent map text-mode-map
)
1089 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
1090 (define-key map
"\C-c\C-c" 'occur-cease-edit
)
1091 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
1092 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
1093 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
1095 "Keymap for `occur-edit-mode'.")
1097 (define-derived-mode occur-edit-mode occur-mode
"Occur-Edit"
1098 "Major mode for editing *Occur* buffers.
1099 In this mode, changes to the *Occur* buffer are also applied to
1100 the originating buffer.
1102 To return to ordinary Occur mode, use \\[occur-cease-edit]."
1103 (setq buffer-read-only nil
)
1104 (add-hook 'after-change-functions
'occur-after-change-function nil t
)
1105 (message (substitute-command-keys
1106 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
1108 (defun occur-cease-edit ()
1109 "Switch from Occur Edit mode to Occur mode."
1111 (when (derived-mode-p 'occur-edit-mode
)
1113 (message "Switching to Occur mode.")))
1115 (defun occur-after-change-function (beg end length
)
1118 (let* ((line-beg (line-beginning-position))
1119 (m (get-text-property line-beg
'occur-target
))
1120 (buf (marker-buffer m
))
1122 (when (and (get-text-property line-beg
'occur-prefix
)
1123 (not (get-text-property end
'occur-prefix
)))
1125 ;; Apply occur-target property to inserted (e.g. yanked) text.
1126 (put-text-property beg end
'occur-target m
)
1127 ;; Did we insert a newline? Occur Edit mode can't create new
1128 ;; Occur entries; just discard everything after the newline.
1130 (and (search-forward "\n" end t
)
1131 (delete-region (1- (point)) end
))))
1132 (let* ((line (- (line-number-at-pos)
1133 (line-number-at-pos (window-start))))
1134 (readonly (with-current-buffer buf buffer-read-only
))
1135 (win (or (get-buffer-window buf
)
1137 '(nil (inhibit-same-window . t
)
1138 (inhibit-switch-frame . t
)))))
1139 (line-end (line-end-position))
1140 (text (save-excursion
1141 (goto-char (next-single-property-change
1142 line-beg
'occur-prefix nil
1144 (setq col
(- (point) line-beg
))
1145 (buffer-substring-no-properties (point) line-end
))))
1146 (with-selected-window win
1150 (message "Buffer `%s' is read only." buf
)
1151 (delete-region (line-beginning-position) (line-end-position))
1153 (move-to-column col
)))))))
1156 (defun occur-revert-function (_ignore1 _ignore2
)
1157 "Handle `revert-buffer' for Occur mode buffers."
1158 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
1160 (defun occur-mode-find-occurrence ()
1161 (let ((pos (get-text-property (point) 'occur-target
)))
1163 (error "No occurrence on this line"))
1164 (unless (buffer-live-p (marker-buffer pos
))
1165 (error "Buffer for this occurrence was killed"))
1168 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
1169 (defun occur-mode-goto-occurrence (&optional event
)
1170 "Go to the occurrence on the current line."
1171 (interactive (list last-nonmenu-event
))
1174 ;; Actually `event-end' works correctly with a nil argument as
1175 ;; well, so we could dispense with this test, but let's not
1176 ;; rely on this undocumented behavior.
1177 (occur-mode-find-occurrence)
1178 (with-current-buffer (window-buffer (posn-window (event-end event
)))
1180 (goto-char (posn-point (event-end event
)))
1181 (occur-mode-find-occurrence))))))
1182 (pop-to-buffer (marker-buffer pos
))
1184 (run-hooks 'occur-mode-find-occurrence-hook
)))
1186 (defun occur-mode-goto-occurrence-other-window ()
1187 "Go to the occurrence the current line describes, in another window."
1189 (let ((pos (occur-mode-find-occurrence)))
1190 (switch-to-buffer-other-window (marker-buffer pos
))
1192 (run-hooks 'occur-mode-find-occurrence-hook
)))
1194 (defun occur-mode-display-occurrence ()
1195 "Display in another window the occurrence the current line describes."
1197 (let ((pos (occur-mode-find-occurrence))
1199 (setq window
(display-buffer (marker-buffer pos
) t
))
1200 ;; This is the way to set point in the proper window.
1201 (save-selected-window
1202 (select-window window
)
1204 (run-hooks 'occur-mode-find-occurrence-hook
))))
1206 (defun occur-find-match (n search message
)
1207 (if (not n
) (setq n
1))
1210 (setq r
(funcall search
(point) 'occur-match
))
1212 (get-text-property r
'occur-match
)
1213 (setq r
(funcall search r
'occur-match
)))
1219 (defun occur-next (&optional n
)
1220 "Move to the Nth (default 1) next match in an Occur mode buffer."
1222 (occur-find-match n
#'next-single-property-change
"No more matches"))
1224 (defun occur-prev (&optional n
)
1225 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1227 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
1229 (defun occur-next-error (&optional argp reset
)
1230 "Move to the Nth (default 1) next match in an Occur mode buffer.
1231 Compatibility function for \\[next-error] invocations."
1233 ;; we need to run occur-find-match from within the Occur buffer
1234 (with-current-buffer
1235 ;; Choose the buffer and make it current.
1236 (if (next-error-buffer-p (current-buffer))
1238 (next-error-find-buffer nil nil
1240 (eq major-mode
'occur-mode
))))
1242 (goto-char (cond (reset (point-min))
1243 ((< argp
0) (line-beginning-position))
1244 ((> argp
0) (line-end-position))
1249 #'previous-single-property-change
1250 #'next-single-property-change
)
1252 ;; In case the *Occur* buffer is visible in a nonselected window.
1253 (let ((win (get-buffer-window (current-buffer) t
)))
1254 (if win
(set-window-point win
(point))))
1255 (occur-mode-goto-occurrence)))
1258 '((((class color
) (min-colors 88) (background light
))
1259 :background
"yellow1")
1260 (((class color
) (min-colors 88) (background dark
))
1261 :background
"RoyalBlue3")
1262 (((class color
) (min-colors 8) (background light
))
1263 :background
"yellow" :foreground
"black")
1264 (((class color
) (min-colors 8) (background dark
))
1265 :background
"blue" :foreground
"white")
1266 (((type tty
) (class mono
))
1268 (t :background
"gray"))
1269 "Face used to highlight matches permanently."
1274 (defcustom list-matching-lines-default-context-lines
0
1275 "Default number of context lines included around `list-matching-lines' matches.
1276 A negative number means to include that many lines before the match.
1277 A positive number means to include that many lines both before and after."
1281 (defalias 'list-matching-lines
'occur
)
1283 (defcustom list-matching-lines-face
'match
1284 "Face used by \\[list-matching-lines] to show the text that matches.
1285 If the value is nil, don't highlight the matching portions specially."
1289 (defcustom list-matching-lines-buffer-name-face
'underline
1290 "Face used by \\[list-matching-lines] to show the names of buffers.
1291 If the value is nil, don't highlight the buffer names specially."
1295 (defcustom list-matching-lines-prefix-face
'shadow
1296 "Face used by \\[list-matching-lines] to show the prefix column.
1297 If the face doesn't differ from the default face,
1298 don't highlight the prefix with line numbers specially."
1303 (defcustom occur-excluded-properties
1304 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1305 yank-handler follow-link
)
1306 "Text properties to discard when copying lines to the *Occur* buffer.
1307 The value should be a list of text properties to discard or t,
1308 which means to discard all text properties."
1309 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
1313 (defun occur-read-primary-args ()
1314 (let* ((perform-collect (consp current-prefix-arg
))
1315 (regexp (read-regexp (if perform-collect
1316 "Collect strings matching regexp"
1317 "List lines matching regexp")
1318 'regexp-history-last
)))
1321 ;; Perform collect operation
1322 (if (zerop (regexp-opt-depth regexp
))
1323 ;; No subexpression so collect the entire match.
1325 ;; Get the regexp for collection pattern.
1326 (let ((default (car occur-collect-regexp-history
)))
1328 (format "Regexp to collect (default %s): " default
)
1329 default
'occur-collect-regexp-history
)))
1330 ;; Otherwise normal occur takes numerical prefix argument.
1331 (when current-prefix-arg
1332 (prefix-numeric-value current-prefix-arg
))))))
1334 (defun occur-rename-buffer (&optional unique-p interactive-p
)
1335 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1336 Here `original-buffer-name' is the buffer name where Occur was originally run.
1337 When given the prefix argument, or called non-interactively, the renaming
1338 will not clobber the existing buffer(s) of that name, but use
1339 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1340 if you always want a separate *Occur* buffer for each buffer where you
1342 (interactive "P\np")
1343 (with-current-buffer
1344 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
1345 (rename-buffer (concat "*Occur: "
1346 (mapconcat #'buffer-name
1347 (car (cddr occur-revert-arguments
)) "/")
1349 (or unique-p
(not interactive-p
)))))
1351 (defun occur (regexp &optional nlines
)
1352 "Show all lines in the current buffer containing a match for REGEXP.
1353 If a match spreads across multiple lines, all those lines are shown.
1355 Each line is displayed with NLINES lines before and after, or -NLINES
1356 before if NLINES is negative.
1357 NLINES defaults to `list-matching-lines-default-context-lines'.
1358 Interactively it is the prefix arg.
1360 The lines are shown in a buffer named `*Occur*'.
1361 It serves as a menu to find any of the occurrences in this buffer.
1362 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1364 If REGEXP contains upper case characters (excluding those preceded by `\\')
1365 and `search-upper-case' is non-nil, the matching is case-sensitive.
1367 When NLINES is a string or when the function is called
1368 interactively with prefix argument without a number (`C-u' alone
1369 as prefix) the matching strings are collected into the `*Occur*'
1370 buffer by using NLINES as a replacement regexp. NLINES may
1371 contain \\& and \\N which convention follows `replace-match'.
1372 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1373 \"\\1\" for NLINES collects all the function names in a lisp
1374 program. When there is no parenthesized subexpressions in REGEXP
1375 the entire match is collected. In any case the searched buffer
1377 (interactive (occur-read-primary-args))
1378 (occur-1 regexp nlines
(list (current-buffer))))
1380 (defvar ido-ignore-item-temp-list
)
1382 (defun multi-occur (bufs regexp
&optional nlines
)
1383 "Show all lines in buffers BUFS containing a match for REGEXP.
1384 This function acts on multiple buffers; otherwise, it is exactly like
1385 `occur'. When you invoke this command interactively, you must specify
1386 the buffer names that you want, one by one.
1387 See also `multi-occur-in-matching-buffers'."
1390 (let* ((bufs (list (read-buffer "First buffer to search: "
1391 (current-buffer) t
)))
1393 (ido-ignore-item-temp-list bufs
))
1394 (while (not (string-equal
1395 (setq buf
(read-buffer
1396 (if (eq read-buffer-function
#'ido-read-buffer
)
1397 "Next buffer to search (C-j to end): "
1398 "Next buffer to search (RET to end): ")
1401 (add-to-list 'bufs buf
)
1402 (setq ido-ignore-item-temp-list bufs
))
1403 (nreverse (mapcar #'get-buffer bufs
)))
1404 (occur-read-primary-args)))
1405 (occur-1 regexp nlines bufs
))
1407 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1408 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1409 Normally BUFREGEXP matches against each buffer's visited file name,
1410 but if you specify a prefix argument, it matches against the buffer name.
1411 See also `multi-occur'."
1414 (let* ((default (car regexp-history
))
1417 (if current-prefix-arg
1418 "List lines in buffers whose names match regexp: "
1419 "List lines in buffers whose filenames match regexp: "))))
1420 (if (equal input
"")
1423 (occur-read-primary-args)))
1427 (mapcar (lambda (buf)
1429 (string-match bufregexp
1431 (and (buffer-file-name buf
)
1432 (string-match bufregexp
1433 (buffer-file-name buf
))))
1437 (defun occur-regexp-descr (regexp)
1438 (format " for %s\"%s\""
1439 (or (get-text-property 0 'isearch-regexp-function-descr regexp
)
1441 (if (get-text-property 0 'isearch-string regexp
)
1443 (query-replace-descr
1444 (get-text-property 0 'isearch-string regexp
))
1446 (query-replace-descr regexp
))))
1448 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1449 (unless (and regexp
(not (equal regexp
"")))
1450 (error "Occur doesn't work with the empty regexp"))
1452 (setq buf-name
"*Occur*"))
1454 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1455 (when (buffer-live-p buf
) buf
))
1457 ;; Handle the case where one of the buffers we're searching is the
1458 ;; output buffer. Just rename it.
1459 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1460 (with-current-buffer (get-buffer buf-name
)
1463 ;; Now find or create the output buffer.
1464 ;; If we just renamed that buffer, we will make a new one here.
1465 (setq occur-buf
(get-buffer-create buf-name
))
1467 (with-current-buffer occur-buf
1468 (if (stringp nlines
)
1469 (fundamental-mode) ;; This is for collect operation.
1471 (let ((inhibit-read-only t
)
1472 ;; Don't generate undo entries for creation of the initial contents.
1473 (buffer-undo-list t
))
1476 (if (stringp nlines
)
1477 ;; Treat nlines as a regexp to collect.
1478 (let ((bufs active-bufs
)
1481 (with-current-buffer (car bufs
)
1483 (goto-char (point-min))
1484 (while (re-search-forward regexp nil t
)
1485 ;; Insert the replacement regexp.
1486 (let ((str (match-substitute-replacement nlines
)))
1488 (with-current-buffer occur-buf
1490 (setq count
(1+ count
))
1491 (or (zerop (current-column))
1492 (insert "\n"))))))))
1493 (setq bufs
(cdr bufs
)))
1495 ;; Perform normal occur.
1497 regexp active-bufs occur-buf
1498 (or nlines list-matching-lines-default-context-lines
)
1499 (if (and case-fold-search search-upper-case
)
1500 (isearch-no-upper-case-p regexp t
)
1502 list-matching-lines-buffer-name-face
1503 (if (face-differs-from-default-p list-matching-lines-prefix-face
)
1504 list-matching-lines-prefix-face
)
1505 list-matching-lines-face
1506 (not (eq occur-excluded-properties t
))))))
1507 (let* ((bufcount (length active-bufs
))
1508 (diff (- (length bufs
) bufcount
)))
1509 (message "Searched %d buffer%s%s; %s match%s%s"
1510 bufcount
(if (= bufcount
1) "" "s")
1511 (if (zerop diff
) "" (format " (%d killed)" diff
))
1512 (if (zerop count
) "no" (format "%d" count
))
1513 (if (= count
1) "" "es")
1514 ;; Don't display regexp if with remaining text
1515 ;; it is longer than window-width.
1516 (if (> (+ (length (or (get-text-property 0 'isearch-string regexp
)
1520 "" (occur-regexp-descr regexp
))))
1521 (setq occur-revert-arguments
(list regexp nlines bufs
))
1523 (kill-buffer occur-buf
)
1524 (display-buffer occur-buf
)
1525 (setq next-error-last-buffer occur-buf
)
1526 (setq buffer-read-only t
)
1527 (set-buffer-modified-p nil
)
1528 (run-hooks 'occur-hook
)))))))
1530 (defun occur-engine (regexp buffers out-buf nlines case-fold
1531 title-face prefix-face match-face keep-props
)
1532 (with-current-buffer out-buf
1533 (let ((global-lines 0) ;; total count of matching lines
1534 (global-matches 0) ;; total count of matches
1536 (case-fold-search case-fold
))
1537 ;; Map over all the buffers
1538 (dolist (buf buffers
)
1539 (when (buffer-live-p buf
)
1540 (let ((lines 0) ;; count of matching lines
1541 (matches 0) ;; count of matches
1542 (curr-line 1) ;; line count
1543 (prev-line nil
) ;; line number of prev match endpt
1544 (prev-after-lines nil
) ;; context lines of prev match
1552 (inhibit-field-text-motion t
)
1553 (headerpt (with-current-buffer out-buf
(point))))
1554 (with-current-buffer buf
1556 ;; Set CODING only if the current buffer locally
1557 ;; binds buffer-file-coding-system.
1558 (not (local-variable-p 'buffer-file-coding-system
))
1559 (setq coding buffer-file-coding-system
))
1561 (goto-char (point-min)) ;; begin searching in the buffer
1563 (setq origpt
(point))
1564 (when (setq endpt
(re-search-forward regexp nil t
))
1565 (setq lines
(1+ lines
)) ;; increment matching lines count
1566 (setq matchbeg
(match-beginning 0))
1567 ;; Get beginning of first match line and end of the last.
1569 (goto-char matchbeg
)
1570 (setq begpt
(line-beginning-position))
1572 (setq endpt
(line-end-position)))
1573 ;; Sum line numbers up to the first match line.
1574 (setq curr-line
(+ curr-line
(count-lines origpt begpt
)))
1575 (setq marker
(make-marker))
1576 (set-marker marker matchbeg
)
1577 (setq curstring
(occur-engine-line begpt endpt keep-props
))
1578 ;; Highlight the matches
1579 (let ((len (length curstring
))
1581 ;; Count empty lines that don't use next loop (Bug#22062).
1583 (setq matches
(1+ matches
)))
1584 (while (and (< start len
)
1585 (string-match regexp curstring start
))
1586 (setq matches
(1+ matches
))
1587 (add-text-properties
1588 (match-beginning 0) (match-end 0)
1589 '(occur-match t
) curstring
)
1591 ;; Add `match-face' to faces copied from the buffer.
1592 (add-face-text-property
1593 (match-beginning 0) (match-end 0)
1594 match-face nil curstring
))
1595 ;; Avoid infloop (Bug#7593).
1596 (let ((end (match-end 0)))
1597 (setq start
(if (= start end
) (1+ start
) end
)))))
1598 ;; Generate the string to insert for this match
1599 (let* ((match-prefix
1600 ;; Using 7 digits aligns tabs properly.
1601 (apply #'propertize
(format "%7d:" curr-line
)
1604 `(font-lock-face ,prefix-face
))
1605 `(occur-prefix t mouse-face
(highlight)
1606 ;; Allow insertion of text at
1607 ;; the end of the prefix (for
1608 ;; Occur Edit mode).
1609 front-sticky t rear-nonsticky t
1610 occur-target
,marker follow-link t
1611 help-echo
"mouse-2: go to this occurrence"))))
1613 ;; We don't put `mouse-face' on the newline,
1614 ;; because that loses. And don't put it
1615 ;; on context lines to reduce flicker.
1616 (propertize curstring
'mouse-face
(list 'highlight
)
1617 'occur-target marker
1620 "mouse-2: go to this occurrence"))
1624 ;; Add non-numeric prefix to all non-first lines
1625 ;; of multi-line matches.
1626 (replace-regexp-in-string
1629 (propertize "\n :" 'font-lock-face prefix-face
)
1632 ;; Add marker at eol, but no mouse props.
1633 (propertize "\n" 'occur-target marker
)))
1636 ;; The simple display style
1638 ;; The complex multi-line display style.
1639 (setq ret
(occur-context-lines
1640 out-line nlines keep-props begpt endpt
1641 curr-line prev-line prev-after-lines
1643 ;; Set first elem of the returned list to `data',
1644 ;; and the second elem to `prev-after-lines'.
1645 (setq prev-after-lines
(nth 1 ret
))
1647 ;; Actually insert the match display data
1648 (with-current-buffer out-buf
1653 ;; Sum line numbers between first and last match lines.
1654 (setq curr-line
(+ curr-line
(count-lines begpt endpt
)
1655 ;; Add 1 for empty last match line since
1656 ;; count-lines returns 1 line less.
1657 (if (and (bolp) (eolp)) 1 0)))
1658 ;; On to the next match...
1660 (goto-char (point-max)))
1661 (setq prev-line
(1- curr-line
)))
1662 ;; Flush remaining context after-lines.
1663 (when prev-after-lines
1664 (with-current-buffer out-buf
1665 (insert (apply #'concat
(occur-engine-add-prefix
1666 prev-after-lines prefix-face
)))))))
1667 (when (not (zerop lines
)) ;; is the count zero?
1668 (setq global-lines
(+ global-lines lines
)
1669 global-matches
(+ global-matches matches
))
1670 (with-current-buffer out-buf
1671 (goto-char headerpt
)
1675 (format "%d match%s%s%s in buffer: %s\n"
1676 matches
(if (= matches
1) "" "es")
1677 ;; Don't display the same number of lines
1678 ;; and matches in case of 1 match per line.
1679 (if (= lines matches
)
1680 "" (format " in %d line%s"
1681 lines
(if (= lines
1) "" "s")))
1682 ;; Don't display regexp for multi-buffer.
1683 (if (> (length buffers
) 1)
1684 "" (occur-regexp-descr regexp
))
1688 (add-text-properties beg end
`(occur-title ,buf
))
1690 (add-face-text-property beg end title-face
)))
1691 (goto-char (point-min)))))))
1692 ;; Display total match count and regexp for multi-buffer.
1693 (when (and (not (zerop global-lines
)) (> (length buffers
) 1))
1694 (goto-char (point-min))
1697 (insert (format "%d match%s%s total%s:\n"
1698 global-matches
(if (= global-matches
1) "" "es")
1699 ;; Don't display the same number of lines
1700 ;; and matches in case of 1 match per line.
1701 (if (= global-lines global-matches
)
1702 "" (format " in %d line%s"
1703 global-lines
(if (= global-lines
1) "" "s")))
1704 (occur-regexp-descr regexp
)))
1707 (add-face-text-property beg end title-face
)))
1708 (goto-char (point-min)))
1710 ;; CODING is buffer-file-coding-system of the first buffer
1711 ;; that locally binds it. Let's use it also for the output
1713 (set-buffer-file-coding-system coding
))
1714 ;; Return the number of matches
1717 (defun occur-engine-line (beg end
&optional keep-props
)
1718 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
1719 (text-property-not-all beg end
'fontified t
))
1720 (if (fboundp 'jit-lock-fontify-now
)
1721 (jit-lock-fontify-now beg end
)))
1722 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1723 (let ((str (buffer-substring beg end
)))
1724 (remove-list-of-text-properties
1725 0 (length str
) occur-excluded-properties str
)
1727 (buffer-substring-no-properties beg end
)))
1729 (defun occur-engine-add-prefix (lines &optional prefix-face
)
1732 (concat (if prefix-face
1733 (propertize " :" 'font-lock-face prefix-face
)
1738 (defun occur-accumulate-lines (count &optional keep-props pt
)
1742 (let ((forwardp (> count
0))
1743 result beg end moved
)
1744 (while (not (or (zerop count
)
1747 (and (bobp) (not moved
)))))
1748 (setq count
(+ count
(if forwardp -
1 1)))
1749 (setq beg
(line-beginning-position)
1750 end
(line-end-position))
1751 (push (occur-engine-line beg end keep-props
) result
)
1752 (setq moved
(= 0 (forward-line (if forwardp
1 -
1)))))
1753 (nreverse result
))))
1755 ;; Generate context display for occur.
1756 ;; OUT-LINE is the line where the match is.
1757 ;; NLINES and KEEP-PROPS are args to occur-engine.
1758 ;; CURR-LINE is line count of the current match,
1759 ;; PREV-LINE is line count of the previous match,
1760 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1761 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1762 ;; then concatenate them all together.
1763 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1764 curr-line prev-line prev-after-lines
1765 &optional prefix-face
)
1766 ;; Find after- and before-context lines of the current match.
1768 (nreverse (cdr (occur-accumulate-lines
1769 (- (1+ (abs nlines
))) keep-props begpt
))))
1771 (cdr (occur-accumulate-lines
1772 (1+ nlines
) keep-props endpt
)))
1775 ;; Combine after-lines of the previous match
1776 ;; with before-lines of the current match.
1778 (when prev-after-lines
1779 ;; Don't overlap prev after-lines with current before-lines.
1780 (if (>= (+ prev-line
(length prev-after-lines
))
1781 (- curr-line
(length before-lines
)))
1782 (setq prev-after-lines
1783 (butlast prev-after-lines
1784 (- (length prev-after-lines
)
1785 (- curr-line prev-line
(length before-lines
) 1))))
1786 ;; Separate non-overlapping context lines with a dashed line.
1787 (setq separator
"-------\n")))
1790 ;; Don't overlap current before-lines with previous match line.
1791 (if (<= (- curr-line
(length before-lines
))
1794 (nthcdr (- (length before-lines
)
1795 (- curr-line prev-line
1))
1797 ;; Separate non-overlapping before-context lines.
1798 (unless (> nlines
0)
1799 (setq separator
"-------\n"))))
1802 ;; Return a list where the first element is the output line.
1805 (if prev-after-lines
1806 (occur-engine-add-prefix prev-after-lines prefix-face
))
1808 (list (if prefix-face
1809 (propertize separator
'font-lock-face prefix-face
)
1811 (occur-engine-add-prefix before-lines prefix-face
)
1813 ;; And the second element is the list of context after-lines.
1814 (if (> nlines
0) after-lines
))))
1817 ;; It would be nice to use \\[...], but there is no reasonable way
1818 ;; to make that display both SPC and Y.
1819 (defconst query-replace-help
1820 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1821 RET or `q' to exit, Period to replace one match and exit,
1822 Comma to replace but not move point immediately,
1823 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1824 C-w to delete match and recursive edit,
1825 C-l to clear the screen, redisplay, and offer same replacement again,
1826 ! to replace all remaining matches in this buffer with no more questions,
1827 ^ to move point back to previous match,
1828 E to edit the replacement string.
1829 In multi-buffer replacements type `Y' to replace all remaining
1830 matches in all remaining buffers with no more questions,
1831 `N' to skip to the next buffer without replacing remaining matches
1832 in the current buffer."
1833 "Help message while in `query-replace'.")
1835 (defvar query-replace-map
1836 (let ((map (make-sparse-keymap)))
1837 (define-key map
" " 'act
)
1838 (define-key map
"\d" 'skip
)
1839 (define-key map
[delete] 'skip)
1840 (define-key map [backspace] 'skip)
1841 (define-key map "y" 'act)
1842 (define-key map "n" 'skip)
1843 (define-key map "Y" 'act)
1844 (define-key map "N" 'skip)
1845 (define-key map "e" 'edit-replacement)
1846 (define-key map "E" 'edit-replacement)
1847 (define-key map "," 'act-and-show)
1848 (define-key map "q" 'exit)
1849 (define-key map "\r" 'exit)
1850 (define-key map [return] 'exit)
1851 (define-key map "." 'act-and-exit)
1852 (define-key map "\C-r" 'edit)
1853 (define-key map "\C-w" 'delete-and-edit)
1854 (define-key map "\C-l" 'recenter)
1855 (define-key map "!" 'automatic)
1856 (define-key map "^" 'backup)
1857 (define-key map "\C-h" 'help)
1858 (define-key map [f1] 'help)
1859 (define-key map [help] 'help)
1860 (define-key map "?" 'help)
1861 (define-key map "\C-g" 'quit)
1862 (define-key map "\C-]" 'quit)
1863 (define-key map "\C-v" 'scroll-up)
1864 (define-key map "\M-v" 'scroll-down)
1865 (define-key map [next] 'scroll-up)
1866 (define-key map [prior] 'scroll-down)
1867 (define-key map [?\C-\M-v] 'scroll-other-window)
1868 (define-key map [M-next] 'scroll-other-window)
1869 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1870 (define-key map [M-prior] 'scroll-other-window-down)
1871 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1872 ;; should check for ESC specially.
1873 ;; (define-key map "\e" 'exit-prefix)
1874 (define-key map [escape] 'exit-prefix)
1876 "Keymap of responses to questions posed by commands like `query-replace'.
1877 The \"bindings\" in this map are not commands; they are answers.
1878 The valid answers include `act', `skip', `act-and-show',
1879 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1880 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1881 `edit', `edit-replacement', `delete-and-edit', `automatic',
1882 `backup', `quit', and `help'.
1884 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1886 (defvar multi-query-replace-map
1887 (let ((map (make-sparse-keymap)))
1888 (set-keymap-parent map query-replace-map)
1889 (define-key map "Y" 'automatic-all)
1890 (define-key map "N" 'exit-current)
1892 "Keymap that defines additional bindings for multi-buffer replacements.
1893 It extends its parent map `query-replace-map' with new bindings to
1894 operate on a set of buffers/files. The difference with its parent map
1895 is the additional answers `automatic-all' to replace all remaining
1896 matches in all remaining buffers with no more questions, and
1897 `exit-current' to skip remaining matches in the current buffer
1898 and to continue with the next buffer in the sequence.")
1900 (defun replace-match-string-symbols (n)
1901 "Process a list (and any sub-lists), expanding certain symbols.
1903 N (match-string N) (where N is a string of digits)
1904 #N (string-to-number (match-string N))
1906 #& (string-to-number (match-string 0))
1909 Note that these symbols must be preceded by a backslash in order to
1910 type them using Lisp syntax."
1914 (replace-match-string-symbols (car n))) ;Process sub-list
1916 (let ((name (symbol-name (car n))))
1918 ((string-match "^[0-9]+$" name)
1919 (setcar n (list 'match-string (string-to-number name))))
1920 ((string-match "^#[0-9]+$" name)
1921 (setcar n (list 'string-to-number
1923 (string-to-number (substring name 1))))))
1925 (setcar n '(match-string 0)))
1926 ((string= "#&" name)
1927 (setcar n '(string-to-number (match-string 0))))
1929 (setcar n 'replace-count))))))
1932 (defun replace-eval-replacement (expression count)
1933 (let* ((replace-count count)
1939 (error "Error evaluating replacement expression: %S" err)))))
1940 (if (stringp replacement)
1942 (prin1-to-string replacement t))))
1944 (defun replace-quote (replacement)
1945 "Quote a replacement string.
1946 This just doubles all backslashes in REPLACEMENT and
1947 returns the resulting string. If REPLACEMENT is not
1948 a string, it is first passed through `prin1-to-string'
1949 with the `noescape' argument set.
1951 `match-data' is preserved across the call."
1953 (replace-regexp-in-string "\\\\" "\\\\"
1954 (if (stringp replacement)
1956 (prin1-to-string replacement t))
1959 (defun replace-loop-through-replacements (data count)
1960 ;; DATA is a vector containing the following values:
1961 ;; 0 next-rotate-count
1963 ;; 2 next-replacement
1965 (if (= (aref data 0) count)
1967 (aset data 0 (+ count (aref data 1)))
1968 (let ((next (cdr (aref data 2))))
1969 (aset data 2 (if (consp next) next (aref data 3))))))
1970 (car (aref data 2)))
1972 (defun replace-match-data (integers reuse &optional new)
1973 "Like `match-data', but markers in REUSE get invalidated.
1974 If NEW is non-nil, it is set and returned instead of fresh data,
1975 but coerced to the correct value of INTEGERS."
1978 (set-match-data new)
1980 (eq (null integers) (markerp (car reuse)))
1982 (match-data integers reuse t)))
1984 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data
1986 "Make a replacement with `replace-match', editing `\\?'.
1987 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
1988 After possibly editing it (if `\\?' is present), NEWTEXT is also
1989 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
1990 is made (to save time). MATCH-DATA is used for the replacement.
1991 In case editing is done, it is changed to use markers. BACKWARD is
1992 used to reverse the replacement direction.
1994 The return value is non-nil if there has been no `\\?' or NOEDIT was
1995 passed in. If LITERAL is set, no checking is done, anyway."
1996 (unless (or literal noedit)
1998 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
2001 (read-string "Edit replacement string: "
2004 (replace-match "" t t newtext 3)
2005 (1+ (match-beginning 3)))
2008 nil match-data match-data))))
2010 (set-match-data match-data)
2011 (replace-match newtext fixedcase literal)
2012 ;; `replace-match' leaves point at the end of the replacement text,
2013 ;; so move point to the beginning when replacing backward.
2014 (when backward (goto-char (nth 0 match-data)))
2017 (defvar replace-update-post-hook nil
2018 "Function(s) to call after query-replace has found a match in the buffer.")
2020 (defvar replace-search-function nil
2021 "Function to use when searching for strings to replace.
2022 It is used by `query-replace' and `replace-string', and is called
2023 with three arguments, as if it were `search-forward'.")
2025 (defvar replace-re-search-function nil
2026 "Function to use when searching for regexps to replace.
2027 It is used by `query-replace-regexp', `replace-regexp',
2028 `query-replace-regexp-eval', and `map-query-replace-regexp'.
2029 It is called with three arguments, as if it were
2030 `re-search-forward'.")
2032 (defun replace-search (search-string limit regexp-flag delimited-flag
2033 case-fold-search &optional backward)
2034 "Search for the next occurrence of SEARCH-STRING to replace."
2035 ;; Let-bind global isearch-* variables to values used
2036 ;; to search the next replacement. These let-bindings
2037 ;; should be effective both at the time of calling
2038 ;; `isearch-search-fun-default' and also at the
2039 ;; time of funcalling `search-function'.
2040 ;; These isearch-* bindings can't be placed higher
2041 ;; outside of this function because then another I-search
2042 ;; used after `recursive-edit' might override them.
2043 (let* ((isearch-regexp regexp-flag)
2044 (isearch-regexp-function (or delimited-flag
2045 (and replace-character-fold
2047 #'character-fold-to-regexp)))
2048 (isearch-lax-whitespace
2049 replace-lax-whitespace)
2050 (isearch-regexp-lax-whitespace
2051 replace-regexp-lax-whitespace)
2052 (isearch-case-fold-search case-fold-search)
2053 (isearch-adjusted nil)
2054 (isearch-nonincremental t) ; don't use lax word mode
2055 (isearch-forward (not backward))
2058 replace-re-search-function
2059 replace-search-function)
2060 (isearch-search-fun-default))))
2061 (funcall search-function search-string limit t)))
2063 (defvar replace-overlay nil)
2065 (defun replace-highlight (match-beg match-end range-beg range-end
2066 search-string regexp-flag delimited-flag
2067 case-fold-search &optional backward)
2068 (if query-replace-highlight
2070 (move-overlay replace-overlay match-beg match-end (current-buffer))
2071 (setq replace-overlay (make-overlay match-beg match-end))
2072 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2073 (overlay-put replace-overlay 'face 'query-replace)))
2074 (if query-replace-lazy-highlight
2075 (let ((isearch-string search-string)
2076 (isearch-regexp regexp-flag)
2077 (isearch-regexp-function delimited-flag)
2078 (isearch-lax-whitespace
2079 replace-lax-whitespace)
2080 (isearch-regexp-lax-whitespace
2081 replace-regexp-lax-whitespace)
2082 (isearch-case-fold-search case-fold-search)
2083 (isearch-forward (not backward))
2084 (isearch-other-end match-beg)
2085 (isearch-error nil))
2086 (isearch-lazy-highlight-new-loop range-beg range-end))))
2088 (defun replace-dehighlight ()
2089 (when replace-overlay
2090 (delete-overlay replace-overlay))
2091 (when query-replace-lazy-highlight
2092 (lazy-highlight-cleanup lazy-highlight-cleanup)
2093 (setq isearch-lazy-highlight-last-string nil))
2094 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2095 (isearch-clean-overlays))
2097 (defun perform-replace (from-string replacements
2098 query-flag regexp-flag delimited-flag
2099 &optional repeat-count map start end backward region-noncontiguous-p)
2100 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2101 Don't use this in your own program unless you want to query and set the mark
2102 just as `query-replace' does. Instead, write a simple loop like this:
2104 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2105 (replace-match \"foobar\" nil nil))
2107 which will run faster and probably do exactly what you want. Please
2108 see the documentation of `replace-match' to find out how to simulate
2111 This function returns nil if and only if there were no matches to
2112 make, or the user didn't cancel the call.
2114 REPLACEMENTS is either a string, a list of strings, or a cons cell
2115 containing a function and its first argument. The function is
2116 called to generate each replacement like this:
2117 (funcall (car replacements) (cdr replacements) replace-count)
2118 It must return a string."
2119 (or map (setq map query-replace-map))
2120 (and query-flag minibuffer-auto-raise
2121 (raise-frame (window-frame (minibuffer-window))))
2122 (let* ((case-fold-search
2123 (if (and case-fold-search search-upper-case)
2124 (isearch-no-upper-case-p from-string regexp-flag)
2126 (nocasify (not (and case-replace case-fold-search)))
2127 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2128 (search-string from-string)
2129 (real-match-data nil) ; The match data for the current match.
2130 (next-replacement nil)
2131 ;; This is non-nil if we know there is nothing for the user
2132 ;; to edit in the replacement.
2137 (skip-read-only-count 0)
2138 (skip-filtered-count 0)
2139 (skip-invisible-count 0)
2140 (nonempty-match nil)
2142 (recenter-last-op nil) ; Start cycling order with initial position.
2144 ;; If non-nil, it is marker saying where in the buffer to stop.
2146 ;; Use local binding in add-function below.
2147 (isearch-filter-predicate isearch-filter-predicate)
2150 ;; Data for the next match. If a cons, it has the same format as
2151 ;; (match-data); otherwise it is t if a match is possible at point.
2157 (substitute-command-keys
2158 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2159 minibuffer-prompt-properties))))
2161 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
2162 (when region-noncontiguous-p
2164 (mapcar (lambda (position)
2165 (cons (copy-marker (car position))
2166 (copy-marker (cdr position))))
2167 (funcall region-extract-function 'bounds)))
2168 (add-function :after-while isearch-filter-predicate
2173 (>= start (car bounds))
2174 (<= start (cdr bounds))
2175 (>= end (car bounds))
2176 (<= end (cdr bounds))))
2179 ;; If region is active, in Transient Mark mode, operate on region.
2182 (setq limit (copy-marker (min start end)))
2183 (goto-char (max start end))
2186 (setq limit (copy-marker (max start end)))
2187 (goto-char (min start end))
2190 ;; If last typed key in previous call of multi-buffer perform-replace
2191 ;; was `automatic-all', don't ask more questions in next files
2192 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2193 (setq query-flag nil multi-buffer t))
2196 ((stringp replacements)
2197 (setq next-replacement replacements
2199 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2200 (or repeat-count (setq repeat-count 1))
2201 (setq replacements (cons 'replace-loop-through-replacements
2202 (vector repeat-count repeat-count
2203 replacements replacements)))))
2205 (when query-replace-lazy-highlight
2206 (setq isearch-lazy-highlight-last-string nil))
2211 ;; Loop finding occurrences that perhaps should be replaced.
2212 (while (and keep-going
2214 (not (or (bobp) (and limit (<= (point) limit))))
2215 (not (or (eobp) (and limit (>= (point) limit)))))
2216 ;; Use the next match if it is already known;
2217 ;; otherwise, search for a match after moving forward
2218 ;; one char if progress is required.
2219 (setq real-match-data
2220 (cond ((consp match-again)
2221 (goto-char (if backward
2223 (nth 1 match-again)))
2225 t real-match-data match-again))
2226 ;; MATCH-AGAIN non-nil means accept an
2230 (replace-search search-string limit
2231 regexp-flag delimited-flag
2232 case-fold-search backward)
2233 ;; For speed, use only integers and
2234 ;; reuse the list used last time.
2235 (replace-match-data t real-match-data)))
2237 (> (1- (point)) (point-min))
2238 (< (1+ (point)) (point-max)))
2241 (> (1- (point)) limit)
2242 (< (1+ (point)) limit))))
2243 ;; If not accepting adjacent matches,
2244 ;; move one char to the right before
2245 ;; searching again. Undo the motion
2246 ;; if the search fails.
2247 (let ((opoint (point)))
2248 (forward-char (if backward -1 1))
2249 (if (replace-search search-string limit
2250 regexp-flag delimited-flag
2251 case-fold-search backward)
2257 ;; Record whether the match is nonempty, to avoid an infinite loop
2258 ;; repeatedly matching the same empty string.
2259 (setq nonempty-match
2260 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2262 ;; If the match is empty, record that the next one can't be
2265 ;; Otherwise, if matching a regular expression, do the next
2266 ;; match now, since the replacement for this match may
2267 ;; affect whether the next match is adjacent to this one.
2268 ;; If that match is empty, don't use it.
2271 (or (not regexp-flag)
2273 (looking-back search-string nil)
2274 (looking-at search-string))
2275 (let ((match (match-data)))
2276 (and (/= (nth 0 match) (nth 1 match))
2280 ;; Optionally ignore matches that have a read-only property.
2281 ((not (or (not query-replace-skip-read-only)
2282 (not (text-property-not-all
2283 (nth 0 real-match-data) (nth 1 real-match-data)
2285 (setq skip-read-only-count (1+ skip-read-only-count)))
2286 ;; Optionally filter out matches.
2287 ((not (funcall isearch-filter-predicate
2288 (nth 0 real-match-data) (nth 1 real-match-data)))
2289 (setq skip-filtered-count (1+ skip-filtered-count)))
2290 ;; Optionally ignore invisible matches.
2291 ((not (or (eq search-invisible t)
2292 ;; Don't open overlays for automatic replacements.
2293 (and (not query-flag) search-invisible)
2294 ;; Open hidden overlays for interactive replacements.
2295 (not (isearch-range-invisible
2296 (nth 0 real-match-data) (nth 1 real-match-data)))))
2297 (setq skip-invisible-count (1+ skip-invisible-count)))
2299 ;; Calculate the replacement string, if necessary.
2301 (set-match-data real-match-data)
2302 (setq next-replacement
2303 (funcall (car replacements) (cdr replacements)
2305 (if (not query-flag)
2307 (unless (or literal noedit)
2309 (nth 0 real-match-data) (nth 1 real-match-data)
2310 start end search-string
2311 regexp-flag delimited-flag case-fold-search backward))
2313 (replace-match-maybe-edit
2314 next-replacement nocasify literal
2315 noedit real-match-data backward)
2316 replace-count (1+ replace-count)))
2318 (let (done replaced key def)
2319 ;; Loop reading commands until one of them sets done,
2320 ;; which means it has finished handling this
2321 ;; occurrence. Any command that sets `done' should
2322 ;; leave behind proper match data for the stack.
2323 ;; Commands not setting `done' need to adjust
2324 ;; `real-match-data'.
2326 (set-match-data real-match-data)
2327 (run-hooks 'replace-update-post-hook) ; Before `replace-highlight'.
2329 (match-beginning 0) (match-end 0)
2330 start end search-string
2331 regexp-flag delimited-flag case-fold-search backward)
2332 ;; Bind message-log-max so we don't fill up the message log
2333 ;; with a bunch of identical messages.
2334 (let ((message-log-max nil)
2335 (replacement-presentation
2336 (if query-replace-show-replacement
2338 (set-match-data real-match-data)
2339 (match-substitute-replacement next-replacement
2343 (query-replace-descr from-string)
2344 (query-replace-descr replacement-presentation)))
2345 (setq key (read-event))
2346 ;; Necessary in case something happens during read-event
2347 ;; that clobbers the match data.
2348 (set-match-data real-match-data)
2349 (setq key (vector key))
2350 (setq def (lookup-key map key))
2351 ;; Restore the match data while we process the command.
2352 (cond ((eq def 'help)
2353 (with-output-to-temp-buffer "*Help*"
2355 (concat "Query replacing "
2357 (or (and (symbolp delimited-flag)
2358 (get delimited-flag 'isearch-message-prefix))
2360 (if regexp-flag "regexp " "")
2361 (if backward "backward " "")
2362 from-string " with "
2363 next-replacement ".\n\n"
2364 (substitute-command-keys
2365 query-replace-help)))
2366 (with-current-buffer standard-output
2369 (setq keep-going nil)
2371 ((eq def 'exit-current)
2372 (setq multi-buffer t keep-going nil done t))
2375 (let ((elt (pop stack)))
2376 (goto-char (nth 0 elt))
2377 (setq replaced (nth 1 elt)
2382 (message "No previous match")
2383 (ding 'no-terminate)
2388 (replace-match-maybe-edit
2389 next-replacement nocasify literal
2390 noedit real-match-data backward)
2391 replace-count (1+ replace-count)))
2392 (setq done t replaced t))
2393 ((eq def 'act-and-exit)
2396 (replace-match-maybe-edit
2397 next-replacement nocasify literal
2398 noedit real-match-data backward)
2399 replace-count (1+ replace-count)))
2400 (setq keep-going nil)
2401 (setq done t replaced t))
2402 ((eq def 'act-and-show)
2405 (replace-match-maybe-edit
2406 next-replacement nocasify literal
2407 noedit real-match-data backward)
2408 replace-count (1+ replace-count)
2409 real-match-data (replace-match-data
2412 ((or (eq def 'automatic) (eq def 'automatic-all))
2415 (replace-match-maybe-edit
2416 next-replacement nocasify literal
2417 noedit real-match-data backward)
2418 replace-count (1+ replace-count)))
2419 (setq done t query-flag nil replaced t)
2420 (if (eq def 'automatic-all) (setq multi-buffer t)))
2424 ;; `this-command' has the value `query-replace',
2425 ;; so we need to bind it to `recenter-top-bottom'
2426 ;; to allow it to detect a sequence of `C-l'.
2427 (let ((this-command 'recenter-top-bottom)
2428 (last-command 'recenter-top-bottom))
2429 (recenter-top-bottom)))
2431 (let ((opos (point-marker)))
2432 (setq real-match-data (replace-match-data
2435 (goto-char (match-beginning 0))
2437 (save-window-excursion
2440 (set-marker opos nil))
2441 ;; Before we make the replacement,
2442 ;; decide whether the search string
2443 ;; can match again just after this match.
2444 (if (and regexp-flag nonempty-match)
2445 (setq match-again (and (looking-at search-string)
2447 ;; Edit replacement.
2448 ((eq def 'edit-replacement)
2449 (setq real-match-data (replace-match-data
2453 (read-string "Edit replacement string: "
2457 (set-match-data real-match-data)
2459 (replace-match-maybe-edit
2460 next-replacement nocasify literal noedit
2461 real-match-data backward)
2465 ((eq def 'delete-and-edit)
2466 (replace-match "" t t)
2467 (setq real-match-data (replace-match-data
2468 nil real-match-data))
2469 (replace-dehighlight)
2470 (save-excursion (recursive-edit))
2472 ;; Note: we do not need to treat `exit-prefix'
2473 ;; specially here, since we reread
2474 ;; any unrecognized character.
2476 (setq this-command 'mode-exited)
2477 (setq keep-going nil)
2478 (setq unread-command-events
2479 (append (listify-key-sequence key)
2480 unread-command-events))
2482 (when query-replace-lazy-highlight
2483 ;; Force lazy rehighlighting only after replacements.
2484 (if (not (memq def '(skip backup)))
2485 (setq isearch-lazy-highlight-last-string nil)))
2486 (unless (eq def 'recenter)
2487 ;; Reset recenter cycling order to initial position.
2488 (setq recenter-last-op nil)))
2489 ;; Record previous position for ^ when we move on.
2490 ;; Change markers to numbers in the match data
2491 ;; since lots of markers slow down editing.
2492 (push (list (point) replaced
2493 ;;; If the replacement has already happened, all we need is the
2494 ;;; current match start and end. We could get this with a trivial
2496 ;;; (save-excursion (goto-char (match-beginning 0))
2497 ;;; (search-forward (match-string 0))
2499 ;;; if we really wanted to avoid manually constructing match data.
2500 ;;; Adding current-buffer is necessary so that match-data calls can
2501 ;;; return markers which are appropriate for editing.
2510 (replace-dehighlight))
2511 (or unread-command-events
2512 (message "Replaced %d occurrence%s%s"
2514 (if (= replace-count 1) "" "s")
2515 (if (> (+ skip-read-only-count
2517 skip-invisible-count) 0)
2518 (format " (skipped %s)"
2522 (if (> skip-read-only-count 0)
2523 (format "%s read-only"
2524 skip-read-only-count))
2525 (if (> skip-invisible-count 0)
2526 (format "%s invisible"
2527 skip-invisible-count))
2528 (if (> skip-filtered-count 0)
2529 (format "%s filtered out"
2530 skip-filtered-count))))
2533 (or (and keep-going stack) multi-buffer)))
2535 ;;; replace.el ends here