1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2015 Free
4 ;; Software Foundation, Inc.
6 ;; Maintainer: emacs-devel@gnu.org
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; This package supplies the string and regular-expression replace functions
27 ;; documented in the Emacs user's manual.
31 (defcustom case-replace t
32 "Non-nil means `query-replace' should preserve case in replacements."
36 (defcustom replace-character-fold t
37 "Non-nil means `query-replace' should do character folding in matches.
38 This means, for instance, that ' will match a large variety of
44 (defcustom replace-lax-whitespace nil
45 "Non-nil means `query-replace' matches a sequence of whitespace chars.
46 When you enter a space or spaces in the strings to be replaced,
47 it will match any sequence matched by the regexp `search-whitespace-regexp'."
52 (defcustom replace-regexp-lax-whitespace nil
53 "Non-nil means `query-replace-regexp' matches a sequence of whitespace chars.
54 When you enter a space or spaces in the regexps to be replaced,
55 it will match any sequence matched by the regexp `search-whitespace-regexp'."
60 (defvar query-replace-history nil
61 "Default history list for query-replace commands.
62 See `query-replace-from-history-variable' and
63 `query-replace-to-history-variable'.")
65 (defvar query-replace-defaults nil
66 "Default values of FROM-STRING and TO-STRING for `query-replace'.
67 This is a list of cons cells (FROM-STRING . TO-STRING), or nil
68 if there are no default values.")
70 (defvar query-replace-interactive nil
71 "Non-nil means `query-replace' uses the last search string.
72 That becomes the \"string to replace\".")
73 (make-obsolete-variable 'query-replace-interactive
74 "use `M-n' to pull the last incremental search string
75 to the minibuffer that reads the string to replace, or invoke replacements
76 from Isearch by using a key sequence like `C-s C-s M-%'." "24.3")
78 (defcustom query-replace-from-to-separator
79 (propertize (if (char-displayable-p ?
\u2192) " \u2192 " " -> ")
80 'face
'minibuffer-prompt
)
81 "String that separates FROM and TO in the history of replacement pairs."
82 ;; Avoids error when attempt to autoload char-displayable-p fails
83 ;; while preparing to dump, also stops customize-rogue listing this.
84 :initialize
'custom-initialize-delay
89 (defcustom query-replace-from-history-variable
'query-replace-history
90 "History list to use for the FROM argument of `query-replace' commands.
91 The value of this variable should be a symbol; that symbol
92 is used as a variable to hold a history list for the strings
93 or patterns to be replaced."
98 (defcustom query-replace-to-history-variable
'query-replace-history
99 "History list to use for the TO argument of `query-replace' commands.
100 The value of this variable should be a symbol; that symbol
101 is used as a variable to hold a history list for replacement
102 strings or patterns."
107 (defcustom query-replace-skip-read-only nil
108 "Non-nil means `query-replace' and friends ignore read-only matches."
113 (defcustom query-replace-show-replacement t
114 "Non-nil means to show what actual replacement text will be."
119 (defcustom query-replace-highlight t
120 "Non-nil means to highlight matches during query replacement."
124 (defcustom query-replace-lazy-highlight t
125 "Controls the lazy-highlighting during query replacements.
126 When non-nil, all text in the buffer matching the current match
127 is highlighted lazily using isearch lazy highlighting (see
128 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
130 :group
'lazy-highlight
134 (defface query-replace
135 '((t (:inherit isearch
)))
136 "Face for highlighting query replacement matches."
140 (defvar replace-count
0
141 "Number of replacements done so far.
142 See `replace-regexp' and `query-replace-regexp-eval'.")
144 (defun query-replace-descr (string)
145 (mapconcat 'isearch-text-char-description string
""))
147 (defun query-replace--split-string (string)
148 "Split string STRING at a character with property `separator'"
149 (let* ((length (length string
))
150 (split-pos (text-property-any 0 length
'separator t string
)))
152 (substring-no-properties string
)
153 (cl-assert (not (text-property-any (1+ split-pos
) length
'separator t string
)))
154 (cons (substring-no-properties string
0 split-pos
)
155 (substring-no-properties string
(1+ split-pos
) length
)))))
157 (defun query-replace-read-from (prompt regexp-flag
)
158 "Query and return the `from' argument of a query-replace operation.
159 The return value can also be a pair (FROM . TO) indicating that the user
160 wants to replace FROM with TO."
161 (if query-replace-interactive
162 (car (if regexp-flag regexp-search-ring search-ring
))
163 ;; Reevaluating will check char-displayable-p that is
164 ;; unavailable while preparing to dump.
165 (custom-reevaluate-setting 'query-replace-from-to-separator
)
166 (let* ((history-add-new-input nil
)
167 (text-property-default-nonsticky
168 (cons '(separator . t
) text-property-default-nonsticky
))
170 (when query-replace-from-to-separator
172 'display query-replace-from-to-separator
174 (query-replace-from-to-history
177 (mapcar (lambda (from-to)
178 (concat (query-replace-descr (car from-to
))
180 (query-replace-descr (cdr from-to
))))
181 query-replace-defaults
))
182 (symbol-value query-replace-from-history-variable
)))
183 (minibuffer-allow-text-properties t
) ; separator uses text-properties
185 (if (and query-replace-defaults separator
)
186 (format "%s (default %s): " prompt
(car query-replace-from-to-history
))
187 (format "%s: " prompt
)))
189 ;; The save-excursion here is in case the user marks and copies
190 ;; a region in order to specify the minibuffer input.
191 ;; That should not clobber the region for the query-replace itself.
194 (read-regexp prompt nil
'query-replace-from-to-history
)
195 (read-from-minibuffer
196 prompt nil nil nil
'query-replace-from-to-history
197 (car (if regexp-flag regexp-search-ring search-ring
)) t
))))
199 (if (and (zerop (length from
)) query-replace-defaults
)
200 (cons (caar query-replace-defaults
)
201 (query-replace-compile-replacement
202 (cdar query-replace-defaults
) regexp-flag
))
203 (setq from
(query-replace--split-string from
))
204 (when (consp from
) (setq to
(cdr from
) from
(car from
)))
205 (add-to-history query-replace-from-history-variable from nil t
)
206 ;; Warn if user types \n or \t, but don't reject the input.
208 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
209 (let ((match (match-string 3 from
)))
211 ((string= match
"\\n")
212 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
213 ((string= match
"\\t")
214 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
218 (add-to-history query-replace-to-history-variable to nil t
)
219 (add-to-history 'query-replace-defaults
(cons from to
) nil t
)
220 (cons from
(query-replace-compile-replacement to regexp-flag
)))))))
222 (defun query-replace-compile-replacement (to regexp-flag
)
223 "Maybe convert a regexp replacement TO to Lisp.
224 Returns a list suitable for `perform-replace' if necessary,
225 the original string if not."
227 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
))
231 (setq pos
(match-end 0))
232 (push (substring to
0 (- pos
2)) list
)
233 (setq char
(aref to
(1- pos
))
234 to
(substring to pos
))
236 (push '(number-to-string replace-count
) list
))
238 (setq pos
(read-from-string to
))
239 (push `(replace-quote ,(car pos
)) list
)
241 ;; Swallow a space after a symbol
242 ;; if there is a space.
243 (if (and (or (symbolp (car pos
))
244 ;; Swallow a space after 'foo
245 ;; but not after (quote foo).
246 (and (eq (car-safe (car pos
)) 'quote
)
247 (not (= ?\
( (aref to
0)))))
248 (eq (string-match " " to
(cdr pos
))
252 (setq to
(substring to end
)))))
253 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
)))
254 (setq to
(nreverse (delete "" (cons to list
))))
255 (replace-match-string-symbols to
)
256 (cons 'replace-eval-replacement
263 (defun query-replace-read-to (from prompt regexp-flag
)
264 "Query and return the `to' argument of a query-replace operation."
265 (query-replace-compile-replacement
267 (let* ((history-add-new-input nil
)
268 (to (read-from-minibuffer
269 (format "%s %s with: " prompt
(query-replace-descr from
))
271 query-replace-to-history-variable from t
)))
272 (add-to-history query-replace-to-history-variable to nil t
)
273 (add-to-history 'query-replace-defaults
(cons from to
) nil t
)
277 (defun query-replace-read-args (prompt regexp-flag
&optional noerror
)
279 (barf-if-buffer-read-only))
280 (let* ((from (query-replace-read-from prompt regexp-flag
))
281 (to (if (consp from
) (prog1 (cdr from
) (setq from
(car from
)))
282 (query-replace-read-to from prompt regexp-flag
))))
284 (and current-prefix-arg
(not (eq current-prefix-arg
'-
)))
285 (and current-prefix-arg
(eq current-prefix-arg
'-
)))))
287 (defun query-replace (from-string to-string
&optional delimited start end backward
)
288 "Replace some occurrences of FROM-STRING with TO-STRING.
289 As each match is found, the user must type a character saying
290 what to do with it. For directions, type \\[help-command] at that time.
292 In Transient Mark mode, if the mark is active, operate on the contents
293 of the region. Otherwise, operate from point to the end of the buffer.
295 Use \\<minibuffer-local-map>\\[next-history-element] \
296 to pull the last incremental search string to the minibuffer
297 that reads FROM-STRING, or invoke replacements from
298 incremental search with a key sequence like `C-s C-s M-%'
299 to use its current search string as the string to replace.
301 Matching is independent of case if `case-fold-search' is non-nil and
302 FROM-STRING has no uppercase letters. Replacement transfers the case
303 pattern of the old text to the new text, if `case-replace' and
304 `case-fold-search' are non-nil and FROM-STRING has no uppercase
305 letters. (Transferring the case pattern means that if the old text
306 matched is all caps, or capitalized, then its replacement is upcased
309 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
310 ignore hidden matches if `search-invisible' is nil, and ignore more
311 matches using `isearch-filter-predicate'.
313 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
314 to be replaced will match a sequence of whitespace chars defined by the
315 regexp in `search-whitespace-regexp'.
317 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
318 only matches surrounded by word boundaries. A negative prefix arg means
321 Fourth and fifth arg START and END specify the region to operate on.
323 To customize possible responses, change the bindings in `query-replace-map'."
326 (query-replace-read-args
327 (concat "Query replace"
328 (if current-prefix-arg
329 (if (eq current-prefix-arg
'-
) " backward" " word")
331 (if (and transient-mark-mode mark-active
) " in region" ""))
333 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
334 ;; These are done separately here
335 ;; so that command-history will record these expressions
336 ;; rather than the values they had this time.
337 (if (and transient-mark-mode mark-active
)
339 (if (and transient-mark-mode mark-active
)
342 (perform-replace from-string to-string t nil delimited nil nil start end backward
))
344 (define-key esc-map
"%" 'query-replace
)
346 (defun query-replace-regexp (regexp to-string
&optional delimited start end backward
)
347 "Replace some things after point matching REGEXP with TO-STRING.
348 As each match is found, the user must type a character saying
349 what to do with it. For directions, type \\[help-command] at that time.
351 In Transient Mark mode, if the mark is active, operate on the contents
352 of the region. Otherwise, operate from point to the end of the buffer.
354 Use \\<minibuffer-local-map>\\[next-history-element] \
355 to pull the last incremental search regexp to the minibuffer
356 that reads REGEXP, or invoke replacements from
357 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
358 to use its current search regexp as the regexp to replace.
360 Matching is independent of case if `case-fold-search' is non-nil and
361 REGEXP has no uppercase letters. Replacement transfers the case
362 pattern of the old text to the new text, if `case-replace' and
363 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
364 \(Transferring the case pattern means that if the old text matched is
365 all caps, or capitalized, then its replacement is upcased or
368 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
369 ignore hidden matches if `search-invisible' is nil, and ignore more
370 matches using `isearch-filter-predicate'.
372 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
373 to be replaced will match a sequence of whitespace chars defined by the
374 regexp in `search-whitespace-regexp'.
376 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
377 only matches surrounded by word boundaries. A negative prefix arg means
380 Fourth and fifth arg START and END specify the region to operate on.
382 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
383 and `\\=\\N' (where N is a digit) stands for
384 whatever what matched the Nth `\\(...\\)' in REGEXP.
385 `\\?' lets you edit the replacement text in the minibuffer
386 at the given position for each replacement.
388 In interactive calls, the replacement text can contain `\\,'
389 followed by a Lisp expression. Each
390 replacement evaluates that expression to compute the replacement
391 string. Inside of that expression, `\\&' is a string denoting the
392 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
393 for the whole or a partial match converted to a number with
394 `string-to-number', and `\\#' itself for the number of replacements
395 done so far (starting with zero).
397 If the replacement expression is a symbol, write a space after it
398 to terminate it. One space there, if any, will be discarded.
400 When using those Lisp features interactively in the replacement
401 text, TO-STRING is actually made a list instead of a string.
402 Use \\[repeat-complex-command] after this command for details."
405 (query-replace-read-args
406 (concat "Query replace"
407 (if current-prefix-arg
408 (if (eq current-prefix-arg
'-
) " backward" " word")
411 (if (and transient-mark-mode mark-active
) " in region" ""))
413 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
414 ;; These are done separately here
415 ;; so that command-history will record these expressions
416 ;; rather than the values they had this time.
417 (if (and transient-mark-mode mark-active
)
419 (if (and transient-mark-mode mark-active
)
422 (perform-replace regexp to-string t t delimited nil nil start end backward
))
424 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
426 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
427 "Replace some things after point matching REGEXP with the result of TO-EXPR.
429 Interactive use of this function is deprecated in favor of the
430 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
431 using `search-forward-regexp' and `replace-match' is preferred.
433 As each match is found, the user must type a character saying
434 what to do with it. For directions, type \\[help-command] at that time.
436 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
437 reference `replace-count' to get the number of replacements already made.
438 If the result of TO-EXPR is not a string, it is converted to one using
439 `prin1-to-string' with the NOESCAPE argument (which see).
441 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
442 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
443 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
444 Use `\\#&' or `\\#N' if you want a number instead of a string.
445 In interactive use, `\\#' in itself stands for `replace-count'.
447 In Transient Mark mode, if the mark is active, operate on the contents
448 of the region. Otherwise, operate from point to the end of the buffer.
450 Use \\<minibuffer-local-map>\\[next-history-element] \
451 to pull the last incremental search regexp to the minibuffer
454 Preserves case in each replacement if `case-replace' and `case-fold-search'
455 are non-nil and REGEXP has no uppercase letters.
457 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
458 ignore hidden matches if `search-invisible' is nil, and ignore more
459 matches using `isearch-filter-predicate'.
461 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
462 to be replaced will match a sequence of whitespace chars defined by the
463 regexp in `search-whitespace-regexp'.
465 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
466 only matches that are surrounded by word boundaries.
467 Fourth and fifth arg START and END specify the region to operate on."
468 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
469 for interactive calls, and `search-forward-regexp'/`replace-match'
470 for Lisp calls." "22.1"))
473 (barf-if-buffer-read-only)
475 ;; Let-bind the history var to disable the "foo -> bar"
476 ;; default. Maybe we shouldn't disable this default, but
477 ;; for now I'll leave it off. --Stef
478 (let ((query-replace-defaults nil
))
479 (query-replace-read-from "Query replace regexp" t
)))
480 (to (list (read-from-minibuffer
481 (format "Query replace regexp %s with eval: "
482 (query-replace-descr from
))
483 nil nil t query-replace-to-history-variable from t
))))
484 ;; We make TO a list because replace-match-string-symbols requires one,
485 ;; and the user might enter a single token.
486 (replace-match-string-symbols to
)
487 (list from
(car to
) current-prefix-arg
488 (if (and transient-mark-mode mark-active
)
490 (if (and transient-mark-mode mark-active
)
492 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
493 t
'literal delimited nil nil start end
))
495 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
496 "Replace some matches for REGEXP with various strings, in rotation.
497 The second argument TO-STRINGS contains the replacement strings, separated
498 by spaces. This command works like `query-replace-regexp' except that
499 each successive replacement uses the next successive replacement string,
500 wrapping around from the last such string to the first.
502 In Transient Mark mode, if the mark is active, operate on the contents
503 of the region. Otherwise, operate from point to the end of the buffer.
505 Non-interactively, TO-STRINGS may be a list of replacement strings.
507 Interactively, reads the regexp using `read-regexp'.
508 Use \\<minibuffer-local-map>\\[next-history-element] \
509 to pull the last incremental search regexp to the minibuffer
512 A prefix argument N says to use each replacement string N times
513 before rotating to the next.
514 Fourth and fifth arg START and END specify the region to operate on."
516 (let* ((from (read-regexp "Map query replace (regexp): " nil
517 query-replace-from-history-variable
))
518 (to (read-from-minibuffer
519 (format "Query replace %s with (space-separated strings): "
520 (query-replace-descr from
))
522 query-replace-to-history-variable from t
)))
524 (and current-prefix-arg
525 (prefix-numeric-value current-prefix-arg
))
526 (if (and transient-mark-mode mark-active
)
528 (if (and transient-mark-mode mark-active
)
531 (if (listp to-strings
)
532 (setq replacements to-strings
)
533 (while (/= (length to-strings
) 0)
534 (if (string-match " " to-strings
)
537 (list (substring to-strings
0
538 (string-match " " to-strings
))))
539 to-strings
(substring to-strings
540 (1+ (string-match " " to-strings
))))
541 (setq replacements
(append replacements
(list to-strings
))
543 (perform-replace regexp replacements t t nil n nil start end
)))
545 (defun replace-string (from-string to-string
&optional delimited start end backward
)
546 "Replace occurrences of FROM-STRING with TO-STRING.
547 Preserve case in each match if `case-replace' and `case-fold-search'
548 are non-nil and FROM-STRING has no uppercase letters.
549 \(Preserving case means that if the string matched is all caps, or capitalized,
550 then its replacement is upcased or capitalized.)
552 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
553 ignore hidden matches if `search-invisible' is nil, and ignore more
554 matches using `isearch-filter-predicate'.
556 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
557 to be replaced will match a sequence of whitespace chars defined by the
558 regexp in `search-whitespace-regexp'.
560 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
561 only matches surrounded by word boundaries. A negative prefix arg means
564 Operates on the region between START and END (if both are nil, from point
565 to the end of the buffer). Interactively, if Transient Mark mode is
566 enabled and the mark is active, operates on the contents of the region;
567 otherwise from point to the end of the buffer.
569 Use \\<minibuffer-local-map>\\[next-history-element] \
570 to pull the last incremental search string to the minibuffer
571 that reads FROM-STRING.
573 This function is usually the wrong thing to use in a Lisp program.
574 What you probably want is a loop like this:
575 (while (search-forward FROM-STRING nil t)
576 (replace-match TO-STRING nil t))
577 which will run faster and will not set the mark or print anything.
578 \(You may need a more complex loop if FROM-STRING can match the null string
579 and TO-STRING is also null.)"
580 (declare (interactive-only
581 "use `search-forward' and `replace-match' instead."))
584 (query-replace-read-args
586 (if current-prefix-arg
587 (if (eq current-prefix-arg
'-
) " backward" " word")
590 (if (and transient-mark-mode mark-active
) " in region" ""))
592 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
593 (if (and transient-mark-mode mark-active
)
595 (if (and transient-mark-mode mark-active
)
598 (perform-replace from-string to-string nil nil delimited nil nil start end backward
))
600 (defun replace-regexp (regexp to-string
&optional delimited start end backward
)
601 "Replace things after point matching REGEXP with TO-STRING.
602 Preserve case in each match if `case-replace' and `case-fold-search'
603 are non-nil and REGEXP has no uppercase letters.
605 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
606 ignore hidden matches if `search-invisible' is nil, and ignore more
607 matches using `isearch-filter-predicate'.
609 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
610 to be replaced will match a sequence of whitespace chars defined by the
611 regexp in `search-whitespace-regexp'.
613 In Transient Mark mode, if the mark is active, operate on the contents
614 of the region. Otherwise, operate from point to the end of the buffer.
616 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
617 only matches surrounded by word boundaries. A negative prefix arg means
620 Fourth and fifth arg START and END specify the region to operate on.
622 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
623 and `\\=\\N' (where N is a digit) stands for
624 whatever what matched the Nth `\\(...\\)' in REGEXP.
625 `\\?' lets you edit the replacement text in the minibuffer
626 at the given position for each replacement.
628 In interactive calls, the replacement text may contain `\\,'
629 followed by a Lisp expression used as part of the replacement
630 text. Inside of that expression, `\\&' is a string denoting the
631 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
632 numeric values from `string-to-number', and `\\#' itself for
633 `replace-count', the number of replacements occurred so far.
635 If your Lisp expression is an identifier and the next letter in
636 the replacement string would be interpreted as part of it, you
637 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
638 for this particular case you may also enter `\\#' in the
639 replacement text directly.
641 When using those Lisp features interactively in the replacement
642 text, TO-STRING is actually made a list instead of a string.
643 Use \\[repeat-complex-command] after this command for details.
645 Use \\<minibuffer-local-map>\\[next-history-element] \
646 to pull the last incremental search regexp to the minibuffer
649 This function is usually the wrong thing to use in a Lisp program.
650 What you probably want is a loop like this:
651 (while (re-search-forward REGEXP nil t)
652 (replace-match TO-STRING nil nil))
653 which will run faster and will not set the mark or print anything."
654 (declare (interactive-only
655 "use `re-search-forward' and `replace-match' instead."))
658 (query-replace-read-args
660 (if current-prefix-arg
661 (if (eq current-prefix-arg
'-
) " backward" " word")
664 (if (and transient-mark-mode mark-active
) " in region" ""))
666 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
667 (if (and transient-mark-mode mark-active
)
669 (if (and transient-mark-mode mark-active
)
672 (perform-replace regexp to-string nil t delimited nil nil start end backward
))
675 (defvar regexp-history nil
676 "History list for some commands that read regular expressions.
678 Maximum length of the history list is determined by the value
679 of `history-length', which see.")
681 (defvar occur-collect-regexp-history
'("\\1")
682 "History of regexp for occur's collect operation")
684 (defcustom read-regexp-defaults-function nil
685 "Function that provides default regexp(s) for `read-regexp'.
686 This function should take no arguments and return one of: nil, a
687 regexp, or a list of regexps. Interactively, `read-regexp' uses
688 the return value of this function for its DEFAULT argument.
690 As an example, set this variable to `find-tag-default-as-regexp'
691 to default to the symbol at point.
693 To provide different default regexps for different commands,
694 the function that you set this to can check `this-command'."
696 (const :tag
"No default regexp reading function" nil
)
697 (const :tag
"Latest regexp history" regexp-history-last
)
698 (function-item :tag
"Tag at point"
700 (function-item :tag
"Tag at point as regexp"
701 find-tag-default-as-regexp
)
702 (function-item :tag
"Tag at point as symbol regexp"
703 find-tag-default-as-symbol-regexp
)
704 (function :tag
"Your choice of function"))
708 (defun read-regexp-suggestions ()
709 "Return a list of standard suggestions for `read-regexp'.
710 By default, the list includes the tag at point, the last isearch regexp,
711 the last isearch string, and the last replacement regexp. `read-regexp'
712 appends the list returned by this function to the end of values available
713 via \\<minibuffer-local-map>\\[next-history-element]."
715 (find-tag-default-as-regexp)
716 (find-tag-default-as-symbol-regexp)
717 (car regexp-search-ring
)
718 (regexp-quote (or (car search-ring
) ""))
719 (car (symbol-value query-replace-from-history-variable
))))
721 (defun read-regexp (prompt &optional defaults history
)
722 "Read and return a regular expression as a string.
723 Prompt with the string PROMPT. If PROMPT ends in \":\" (followed by
724 optional whitespace), use it as-is. Otherwise, add \": \" to the end,
725 possibly preceded by the default result (see below).
727 The optional argument DEFAULTS can be either: nil, a string, a list
728 of strings, or a symbol. We use DEFAULTS to construct the default
729 return value in case of empty input.
731 If DEFAULTS is a string, we use it as-is.
733 If DEFAULTS is a list of strings, the first element is the
734 default return value, but all the elements are accessible
735 using the history command \\<minibuffer-local-map>\\[next-history-element].
737 If DEFAULTS is a non-nil symbol, then if `read-regexp-defaults-function'
738 is non-nil, we use that in place of DEFAULTS in the following:
739 If DEFAULTS is the symbol `regexp-history-last', we use the first
740 element of HISTORY (if specified) or `regexp-history'.
741 If DEFAULTS is a function, we call it with no arguments and use
742 what it returns, which should be either nil, a string, or a list of strings.
744 We append the standard values from `read-regexp-suggestions' to DEFAULTS
747 If the first element of DEFAULTS is non-nil (and if PROMPT does not end
748 in \":\", followed by optional whitespace), we add it to the prompt.
750 The optional argument HISTORY is a symbol to use for the history list.
751 If nil, uses `regexp-history'."
753 (if (and defaults
(symbolp defaults
))
755 ((eq (or read-regexp-defaults-function defaults
)
756 'regexp-history-last
)
757 (car (symbol-value (or history
'regexp-history
))))
758 ((functionp (or read-regexp-defaults-function defaults
))
759 (funcall (or read-regexp-defaults-function defaults
))))
761 (default (if (consp defaults
) (car defaults
) defaults
))
762 (suggestions (if (listp defaults
) defaults
(list defaults
)))
763 (suggestions (append suggestions
(read-regexp-suggestions)))
764 (suggestions (delete-dups (delq nil
(delete "" suggestions
))))
765 ;; Do not automatically add default to the history for empty input.
766 (history-add-new-input nil
)
767 (input (read-from-minibuffer
768 (cond ((string-match-p ":[ \t]*\\'" prompt
)
770 ((and default
(> (length default
) 0))
771 (format "%s (default %s): " prompt
772 (query-replace-descr default
)))
774 (format "%s: " prompt
)))
775 nil nil nil
(or history
'regexp-history
) suggestions t
)))
777 ;; Return the default value when the user enters empty input.
778 (prog1 (or default input
)
780 (add-to-history (or history
'regexp-history
) default
)))
781 ;; Otherwise, add non-empty input to the history and return input.
783 (add-to-history (or history
'regexp-history
) input
)))))
786 (defalias 'delete-non-matching-lines
'keep-lines
)
787 (defalias 'delete-matching-lines
'flush-lines
)
788 (defalias 'count-matches
'how-many
)
791 (defun keep-lines-read-args (prompt)
792 "Read arguments for `keep-lines' and friends.
793 Prompt for a regexp with PROMPT.
794 Value is a list, (REGEXP)."
795 (list (read-regexp prompt
) nil nil t
))
797 (defun keep-lines (regexp &optional rstart rend interactive
)
798 "Delete all lines except those containing matches for REGEXP.
799 A match split across lines preserves all the lines it lies in.
800 When called from Lisp (and usually interactively as well, see below)
801 applies to all lines starting after point.
803 If REGEXP contains upper case characters (excluding those preceded by `\\')
804 and `search-upper-case' is non-nil, the matching is case-sensitive.
806 Second and third arg RSTART and REND specify the region to operate on.
807 This command operates on (the accessible part of) all lines whose
808 accessible part is entirely contained in the region determined by RSTART
809 and REND. (A newline ending a line counts as part of that line.)
811 Interactively, in Transient Mark mode when the mark is active, operate
812 on all lines whose accessible part is entirely contained in the region.
813 Otherwise, the command applies to all lines starting after point.
814 When calling this function from Lisp, you can pretend that it was
815 called interactively by passing a non-nil INTERACTIVE argument.
817 This function starts looking for the next match from the end of
818 the previous match. Hence, it ignores matches that overlap
819 a previously found match."
823 (barf-if-buffer-read-only)
824 (keep-lines-read-args "Keep lines containing match for regexp")))
827 (goto-char (min rstart rend
))
831 (goto-char (max rstart rend
))
832 (unless (or (bolp) (eobp))
835 (if (and interactive transient-mark-mode mark-active
)
836 (setq rstart
(region-beginning)
838 (goto-char (region-end))
839 (unless (or (bolp) (eobp))
843 rend
(point-max-marker)))
846 (or (bolp) (forward-line 1))
847 (let ((start (point))
849 (if (and case-fold-search search-upper-case
)
850 (isearch-no-upper-case-p regexp t
)
852 (while (< (point) rend
)
853 ;; Start is first char not preserved by previous match.
854 (if (not (re-search-forward regexp rend
'move
))
855 (delete-region start rend
)
856 (let ((end (save-excursion (goto-char (match-beginning 0))
859 ;; Now end is first char preserved by the new match.
861 (delete-region start end
))))
863 (setq start
(save-excursion (forward-line 1) (point)))
864 ;; If the match was empty, avoid matching again at same place.
865 (and (< (point) rend
)
866 (= (match-beginning 0) (match-end 0))
868 (set-marker rend nil
)
872 (defun flush-lines (regexp &optional rstart rend interactive
)
873 "Delete lines containing matches for REGEXP.
874 When called from Lisp (and usually when called interactively as
875 well, see below), applies to the part of the buffer after point.
876 The line point is in is deleted if and only if it contains a
877 match for regexp starting after point.
879 If REGEXP contains upper case characters (excluding those preceded by `\\')
880 and `search-upper-case' is non-nil, the matching is case-sensitive.
882 Second and third arg RSTART and REND specify the region to operate on.
883 Lines partially contained in this region are deleted if and only if
884 they contain a match entirely contained in it.
886 Interactively, in Transient Mark mode when the mark is active, operate
887 on the contents of the region. Otherwise, operate from point to the
888 end of (the accessible portion of) the buffer. When calling this function
889 from Lisp, you can pretend that it was called interactively by passing
890 a non-nil INTERACTIVE argument.
892 If a match is split across lines, all the lines it lies in are deleted.
893 They are deleted _before_ looking for the next match. Hence, a match
894 starting on the same line at which another match ended is ignored."
898 (barf-if-buffer-read-only)
899 (keep-lines-read-args "Flush lines containing match for regexp")))
902 (goto-char (min rstart rend
))
903 (setq rend
(copy-marker (max rstart rend
))))
904 (if (and interactive transient-mark-mode mark-active
)
905 (setq rstart
(region-beginning)
906 rend
(copy-marker (region-end)))
908 rend
(point-max-marker)))
910 (let ((case-fold-search
911 (if (and case-fold-search search-upper-case
)
912 (isearch-no-upper-case-p regexp t
)
915 (while (and (< (point) rend
)
916 (re-search-forward regexp rend t
))
917 (delete-region (save-excursion (goto-char (match-beginning 0))
920 (progn (forward-line 1) (point))))))
921 (set-marker rend nil
)
925 (defun how-many (regexp &optional rstart rend interactive
)
926 "Print and return number of matches for REGEXP following point.
927 When called from Lisp and INTERACTIVE is omitted or nil, just return
928 the number, do not print it; if INTERACTIVE is t, the function behaves
929 in all respects as if it had been called interactively.
931 If REGEXP contains upper case characters (excluding those preceded by `\\')
932 and `search-upper-case' is non-nil, the matching is case-sensitive.
934 Second and third arg RSTART and REND specify the region to operate on.
936 Interactively, in Transient Mark mode when the mark is active, operate
937 on the contents of the region. Otherwise, operate from point to the
938 end of (the accessible portion of) the buffer.
940 This function starts looking for the next match from the end of
941 the previous match. Hence, it ignores matches that overlap
942 a previously found match."
945 (keep-lines-read-args "How many matches for regexp"))
950 (goto-char (min rstart rend
))
951 (setq rend
(max rstart rend
)))
953 (setq rend
(point-max)))
954 (if (and interactive transient-mark-mode mark-active
)
955 (setq rstart
(region-beginning)
963 (if (and case-fold-search search-upper-case
)
964 (isearch-no-upper-case-p regexp t
)
966 (while (and (< (point) rend
)
967 (progn (setq opoint
(point))
968 (re-search-forward regexp rend t
)))
969 (if (= opoint
(point))
971 (setq count
(1+ count
))))
972 (when interactive
(message "%d occurrence%s"
974 (if (= count
1) "" "s")))
978 (defvar occur-menu-map
979 (let ((map (make-sparse-keymap)))
980 (bindings--define-key map
[next-error-follow-minor-mode
]
981 '(menu-item "Auto Occurrence Display"
982 next-error-follow-minor-mode
983 :help
"Display another occurrence when moving the cursor"
984 :button
(:toggle .
(and (boundp 'next-error-follow-minor-mode
)
985 next-error-follow-minor-mode
))))
986 (bindings--define-key map
[separator-1
] menu-bar-separator
)
987 (bindings--define-key map
[kill-this-buffer
]
988 '(menu-item "Kill Occur Buffer" kill-this-buffer
989 :help
"Kill the current *Occur* buffer"))
990 (bindings--define-key map
[quit-window
]
991 '(menu-item "Quit Occur Window" quit-window
992 :help
"Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
993 (bindings--define-key map
[revert-buffer
]
994 '(menu-item "Revert Occur Buffer" revert-buffer
995 :help
"Replace the text in the *Occur* buffer with the results of rerunning occur"))
996 (bindings--define-key map
[clone-buffer
]
997 '(menu-item "Clone Occur Buffer" clone-buffer
998 :help
"Create and return a twin copy of the current *Occur* buffer"))
999 (bindings--define-key map
[occur-rename-buffer
]
1000 '(menu-item "Rename Occur Buffer" occur-rename-buffer
1001 :help
"Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
1002 (bindings--define-key map
[occur-edit-buffer
]
1003 '(menu-item "Edit Occur Buffer" occur-edit-mode
1004 :help
"Edit the *Occur* buffer and apply changes to the original buffers."))
1005 (bindings--define-key map
[separator-2
] menu-bar-separator
)
1006 (bindings--define-key map
[occur-mode-goto-occurrence-other-window
]
1007 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
1008 :help
"Go to the occurrence the current line describes, in another window"))
1009 (bindings--define-key map
[occur-mode-goto-occurrence
]
1010 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
1011 :help
"Go to the occurrence the current line describes"))
1012 (bindings--define-key map
[occur-mode-display-occurrence
]
1013 '(menu-item "Display Occurrence" occur-mode-display-occurrence
1014 :help
"Display in another window the occurrence the current line describes"))
1015 (bindings--define-key map
[occur-next
]
1016 '(menu-item "Move to Next Match" occur-next
1017 :help
"Move to the Nth (default 1) next match in an Occur mode buffer"))
1018 (bindings--define-key map
[occur-prev
]
1019 '(menu-item "Move to Previous Match" occur-prev
1020 :help
"Move to the Nth (default 1) previous match in an Occur mode buffer"))
1022 "Menu keymap for `occur-mode'.")
1024 (defvar occur-mode-map
1025 (let ((map (make-sparse-keymap)))
1026 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
1027 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
1028 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
1029 (define-key map
"e" 'occur-edit-mode
)
1030 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
1031 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
1032 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
1033 (define-key map
"\M-n" 'occur-next
)
1034 (define-key map
"\M-p" 'occur-prev
)
1035 (define-key map
"r" 'occur-rename-buffer
)
1036 (define-key map
"c" 'clone-buffer
)
1037 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
1038 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
1040 "Keymap for `occur-mode'.")
1042 (defvar occur-revert-arguments nil
1043 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
1044 See `occur-revert-function'.")
1045 (make-variable-buffer-local 'occur-revert-arguments
)
1046 (put 'occur-revert-arguments
'permanent-local t
)
1048 (defcustom occur-mode-hook
'(turn-on-font-lock)
1049 "Hook run when entering Occur mode."
1053 (defcustom occur-hook nil
1054 "Hook run by Occur when there are any matches."
1058 (defcustom occur-mode-find-occurrence-hook nil
1059 "Hook run by Occur after locating an occurrence.
1060 This will be called with the cursor position at the occurrence. An application
1061 for this is to reveal context in an outline-mode when the occurrence is hidden."
1065 (put 'occur-mode
'mode-class
'special
)
1066 (define-derived-mode occur-mode special-mode
"Occur"
1067 "Major mode for output from \\[occur].
1068 \\<occur-mode-map>Move point to one of the items in this buffer, then use
1069 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
1070 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
1073 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
1074 (setq next-error-function
'occur-next-error
))
1079 (defvar occur-edit-mode-map
1080 (let ((map (make-sparse-keymap)))
1081 (set-keymap-parent map text-mode-map
)
1082 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
1083 (define-key map
"\C-c\C-c" 'occur-cease-edit
)
1084 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
1085 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
1086 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
1088 "Keymap for `occur-edit-mode'.")
1090 (define-derived-mode occur-edit-mode occur-mode
"Occur-Edit"
1091 "Major mode for editing *Occur* buffers.
1092 In this mode, changes to the *Occur* buffer are also applied to
1093 the originating buffer.
1095 To return to ordinary Occur mode, use \\[occur-cease-edit]."
1096 (setq buffer-read-only nil
)
1097 (add-hook 'after-change-functions
'occur-after-change-function nil t
)
1098 (message (substitute-command-keys
1099 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
1101 (defun occur-cease-edit ()
1102 "Switch from Occur Edit mode to Occur mode."
1104 (when (derived-mode-p 'occur-edit-mode
)
1106 (message "Switching to Occur mode.")))
1108 (defun occur-after-change-function (beg end length
)
1111 (let* ((line-beg (line-beginning-position))
1112 (m (get-text-property line-beg
'occur-target
))
1113 (buf (marker-buffer m
))
1115 (when (and (get-text-property line-beg
'occur-prefix
)
1116 (not (get-text-property end
'occur-prefix
)))
1118 ;; Apply occur-target property to inserted (e.g. yanked) text.
1119 (put-text-property beg end
'occur-target m
)
1120 ;; Did we insert a newline? Occur Edit mode can't create new
1121 ;; Occur entries; just discard everything after the newline.
1123 (and (search-forward "\n" end t
)
1124 (delete-region (1- (point)) end
))))
1125 (let* ((line (- (line-number-at-pos)
1126 (line-number-at-pos (window-start))))
1127 (readonly (with-current-buffer buf buffer-read-only
))
1128 (win (or (get-buffer-window buf
)
1130 '(nil (inhibit-same-window . t
)
1131 (inhibit-switch-frame . t
)))))
1132 (line-end (line-end-position))
1133 (text (save-excursion
1134 (goto-char (next-single-property-change
1135 line-beg
'occur-prefix nil
1137 (setq col
(- (point) line-beg
))
1138 (buffer-substring-no-properties (point) line-end
))))
1139 (with-selected-window win
1143 (message "Buffer `%s' is read only." buf
)
1144 (delete-region (line-beginning-position) (line-end-position))
1146 (move-to-column col
)))))))
1149 (defun occur-revert-function (_ignore1 _ignore2
)
1150 "Handle `revert-buffer' for Occur mode buffers."
1151 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
1153 (defun occur-mode-find-occurrence ()
1154 (let ((pos (get-text-property (point) 'occur-target
)))
1156 (error "No occurrence on this line"))
1157 (unless (buffer-live-p (marker-buffer pos
))
1158 (error "Buffer for this occurrence was killed"))
1161 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
1162 (defun occur-mode-goto-occurrence (&optional event
)
1163 "Go to the occurrence on the current line."
1164 (interactive (list last-nonmenu-event
))
1167 ;; Actually `event-end' works correctly with a nil argument as
1168 ;; well, so we could dispense with this test, but let's not
1169 ;; rely on this undocumented behavior.
1170 (occur-mode-find-occurrence)
1171 (with-current-buffer (window-buffer (posn-window (event-end event
)))
1173 (goto-char (posn-point (event-end event
)))
1174 (occur-mode-find-occurrence))))))
1175 (pop-to-buffer (marker-buffer pos
))
1177 (run-hooks 'occur-mode-find-occurrence-hook
)))
1179 (defun occur-mode-goto-occurrence-other-window ()
1180 "Go to the occurrence the current line describes, in another window."
1182 (let ((pos (occur-mode-find-occurrence)))
1183 (switch-to-buffer-other-window (marker-buffer pos
))
1185 (run-hooks 'occur-mode-find-occurrence-hook
)))
1187 (defun occur-mode-display-occurrence ()
1188 "Display in another window the occurrence the current line describes."
1190 (let ((pos (occur-mode-find-occurrence))
1192 (setq window
(display-buffer (marker-buffer pos
) t
))
1193 ;; This is the way to set point in the proper window.
1194 (save-selected-window
1195 (select-window window
)
1197 (run-hooks 'occur-mode-find-occurrence-hook
))))
1199 (defun occur-find-match (n search message
)
1200 (if (not n
) (setq n
1))
1203 (setq r
(funcall search
(point) 'occur-match
))
1205 (get-text-property r
'occur-match
)
1206 (setq r
(funcall search r
'occur-match
)))
1212 (defun occur-next (&optional n
)
1213 "Move to the Nth (default 1) next match in an Occur mode buffer."
1215 (occur-find-match n
#'next-single-property-change
"No more matches"))
1217 (defun occur-prev (&optional n
)
1218 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1220 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
1222 (defun occur-next-error (&optional argp reset
)
1223 "Move to the Nth (default 1) next match in an Occur mode buffer.
1224 Compatibility function for \\[next-error] invocations."
1226 ;; we need to run occur-find-match from within the Occur buffer
1227 (with-current-buffer
1228 ;; Choose the buffer and make it current.
1229 (if (next-error-buffer-p (current-buffer))
1231 (next-error-find-buffer nil nil
1233 (eq major-mode
'occur-mode
))))
1235 (goto-char (cond (reset (point-min))
1236 ((< argp
0) (line-beginning-position))
1237 ((> argp
0) (line-end-position))
1242 #'previous-single-property-change
1243 #'next-single-property-change
)
1245 ;; In case the *Occur* buffer is visible in a nonselected window.
1246 (let ((win (get-buffer-window (current-buffer) t
)))
1247 (if win
(set-window-point win
(point))))
1248 (occur-mode-goto-occurrence)))
1251 '((((class color
) (min-colors 88) (background light
))
1252 :background
"yellow1")
1253 (((class color
) (min-colors 88) (background dark
))
1254 :background
"RoyalBlue3")
1255 (((class color
) (min-colors 8) (background light
))
1256 :background
"yellow" :foreground
"black")
1257 (((class color
) (min-colors 8) (background dark
))
1258 :background
"blue" :foreground
"white")
1259 (((type tty
) (class mono
))
1261 (t :background
"gray"))
1262 "Face used to highlight matches permanently."
1266 (defcustom list-matching-lines-default-context-lines
0
1267 "Default number of context lines included around `list-matching-lines' matches.
1268 A negative number means to include that many lines before the match.
1269 A positive number means to include that many lines both before and after."
1273 (defalias 'list-matching-lines
'occur
)
1275 (defcustom list-matching-lines-face
'match
1276 "Face used by \\[list-matching-lines] to show the text that matches.
1277 If the value is nil, don't highlight the matching portions specially."
1281 (defcustom list-matching-lines-buffer-name-face
'underline
1282 "Face used by \\[list-matching-lines] to show the names of buffers.
1283 If the value is nil, don't highlight the buffer names specially."
1287 (defcustom list-matching-lines-prefix-face
'shadow
1288 "Face used by \\[list-matching-lines] to show the prefix column.
1289 If the face doesn't differ from the default face,
1290 don't highlight the prefix with line numbers specially."
1295 (defcustom occur-excluded-properties
1296 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1297 yank-handler follow-link
)
1298 "Text properties to discard when copying lines to the *Occur* buffer.
1299 The value should be a list of text properties to discard or t,
1300 which means to discard all text properties."
1301 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
1305 (defun occur-read-primary-args ()
1306 (let* ((perform-collect (consp current-prefix-arg
))
1307 (regexp (read-regexp (if perform-collect
1308 "Collect strings matching regexp"
1309 "List lines matching regexp")
1310 'regexp-history-last
)))
1313 ;; Perform collect operation
1314 (if (zerop (regexp-opt-depth regexp
))
1315 ;; No subexpression so collect the entire match.
1317 ;; Get the regexp for collection pattern.
1318 (let ((default (car occur-collect-regexp-history
)))
1320 (format "Regexp to collect (default %s): " default
)
1321 default
'occur-collect-regexp-history
)))
1322 ;; Otherwise normal occur takes numerical prefix argument.
1323 (when current-prefix-arg
1324 (prefix-numeric-value current-prefix-arg
))))))
1326 (defun occur-rename-buffer (&optional unique-p interactive-p
)
1327 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1328 Here `original-buffer-name' is the buffer name where Occur was originally run.
1329 When given the prefix argument, or called non-interactively, the renaming
1330 will not clobber the existing buffer(s) of that name, but use
1331 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1332 if you always want a separate *Occur* buffer for each buffer where you
1334 (interactive "P\np")
1335 (with-current-buffer
1336 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
1337 (rename-buffer (concat "*Occur: "
1338 (mapconcat #'buffer-name
1339 (car (cddr occur-revert-arguments
)) "/")
1341 (or unique-p
(not interactive-p
)))))
1343 (defun occur (regexp &optional nlines
)
1344 "Show all lines in the current buffer containing a match for REGEXP.
1345 If a match spreads across multiple lines, all those lines are shown.
1347 Each line is displayed with NLINES lines before and after, or -NLINES
1348 before if NLINES is negative.
1349 NLINES defaults to `list-matching-lines-default-context-lines'.
1350 Interactively it is the prefix arg.
1352 The lines are shown in a buffer named `*Occur*'.
1353 It serves as a menu to find any of the occurrences in this buffer.
1354 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1356 If REGEXP contains upper case characters (excluding those preceded by `\\')
1357 and `search-upper-case' is non-nil, the matching is case-sensitive.
1359 When NLINES is a string or when the function is called
1360 interactively with prefix argument without a number (`C-u' alone
1361 as prefix) the matching strings are collected into the `*Occur*'
1362 buffer by using NLINES as a replacement regexp. NLINES may
1363 contain \\& and \\N which convention follows `replace-match'.
1364 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1365 \"\\1\" for NLINES collects all the function names in a lisp
1366 program. When there is no parenthesized subexpressions in REGEXP
1367 the entire match is collected. In any case the searched buffer
1369 (interactive (occur-read-primary-args))
1370 (occur-1 regexp nlines
(list (current-buffer))))
1372 (defvar ido-ignore-item-temp-list
)
1374 (defun multi-occur (bufs regexp
&optional nlines
)
1375 "Show all lines in buffers BUFS containing a match for REGEXP.
1376 This function acts on multiple buffers; otherwise, it is exactly like
1377 `occur'. When you invoke this command interactively, you must specify
1378 the buffer names that you want, one by one.
1379 See also `multi-occur-in-matching-buffers'."
1382 (let* ((bufs (list (read-buffer "First buffer to search: "
1383 (current-buffer) t
)))
1385 (ido-ignore-item-temp-list bufs
))
1386 (while (not (string-equal
1387 (setq buf
(read-buffer
1388 (if (eq read-buffer-function
#'ido-read-buffer
)
1389 "Next buffer to search (C-j to end): "
1390 "Next buffer to search (RET to end): ")
1393 (add-to-list 'bufs buf
)
1394 (setq ido-ignore-item-temp-list bufs
))
1395 (nreverse (mapcar #'get-buffer bufs
)))
1396 (occur-read-primary-args)))
1397 (occur-1 regexp nlines bufs
))
1399 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1400 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1401 Normally BUFREGEXP matches against each buffer's visited file name,
1402 but if you specify a prefix argument, it matches against the buffer name.
1403 See also `multi-occur'."
1406 (let* ((default (car regexp-history
))
1409 (if current-prefix-arg
1410 "List lines in buffers whose names match regexp: "
1411 "List lines in buffers whose filenames match regexp: "))))
1412 (if (equal input
"")
1415 (occur-read-primary-args)))
1419 (mapcar (lambda (buf)
1421 (string-match bufregexp
1423 (and (buffer-file-name buf
)
1424 (string-match bufregexp
1425 (buffer-file-name buf
))))
1429 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1430 (unless (and regexp
(not (equal regexp
"")))
1431 (error "Occur doesn't work with the empty regexp"))
1433 (setq buf-name
"*Occur*"))
1435 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1436 (when (buffer-live-p buf
) buf
))
1438 ;; Handle the case where one of the buffers we're searching is the
1439 ;; output buffer. Just rename it.
1440 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1441 (with-current-buffer (get-buffer buf-name
)
1444 ;; Now find or create the output buffer.
1445 ;; If we just renamed that buffer, we will make a new one here.
1446 (setq occur-buf
(get-buffer-create buf-name
))
1448 (with-current-buffer occur-buf
1449 (if (stringp nlines
)
1450 (fundamental-mode) ;; This is for collect operation.
1452 (let ((inhibit-read-only t
)
1453 ;; Don't generate undo entries for creation of the initial contents.
1454 (buffer-undo-list t
))
1457 (if (stringp nlines
)
1458 ;; Treat nlines as a regexp to collect.
1459 (let ((bufs active-bufs
)
1462 (with-current-buffer (car bufs
)
1464 (goto-char (point-min))
1465 (while (re-search-forward regexp nil t
)
1466 ;; Insert the replacement regexp.
1467 (let ((str (match-substitute-replacement nlines
)))
1469 (with-current-buffer occur-buf
1471 (setq count
(1+ count
))
1472 (or (zerop (current-column))
1473 (insert "\n"))))))))
1474 (setq bufs
(cdr bufs
)))
1476 ;; Perform normal occur.
1478 regexp active-bufs occur-buf
1479 (or nlines list-matching-lines-default-context-lines
)
1480 (if (and case-fold-search search-upper-case
)
1481 (isearch-no-upper-case-p regexp t
)
1483 list-matching-lines-buffer-name-face
1484 (if (face-differs-from-default-p list-matching-lines-prefix-face
)
1485 list-matching-lines-prefix-face
)
1486 list-matching-lines-face
1487 (not (eq occur-excluded-properties t
))))))
1488 (let* ((bufcount (length active-bufs
))
1489 (diff (- (length bufs
) bufcount
)))
1490 (message "Searched %d buffer%s%s; %s match%s%s"
1491 bufcount
(if (= bufcount
1) "" "s")
1492 (if (zerop diff
) "" (format " (%d killed)" diff
))
1493 (if (zerop count
) "no" (format "%d" count
))
1494 (if (= count
1) "" "es")
1495 ;; Don't display regexp if with remaining text
1496 ;; it is longer than window-width.
1497 (if (> (+ (length regexp
) 42) (window-width))
1498 "" (format " for `%s'" (query-replace-descr regexp
)))))
1499 (setq occur-revert-arguments
(list regexp nlines bufs
))
1501 (kill-buffer occur-buf
)
1502 (display-buffer occur-buf
)
1503 (setq next-error-last-buffer occur-buf
)
1504 (setq buffer-read-only t
)
1505 (set-buffer-modified-p nil
)
1506 (run-hooks 'occur-hook
)))))))
1508 (defun occur-engine (regexp buffers out-buf nlines case-fold
1509 title-face prefix-face match-face keep-props
)
1510 (with-current-buffer out-buf
1511 (let ((global-lines 0) ;; total count of matching lines
1512 (global-matches 0) ;; total count of matches
1514 (case-fold-search case-fold
))
1515 ;; Map over all the buffers
1516 (dolist (buf buffers
)
1517 (when (buffer-live-p buf
)
1518 (let ((lines 0) ;; count of matching lines
1519 (matches 0) ;; count of matches
1520 (curr-line 1) ;; line count
1521 (prev-line nil
) ;; line number of prev match endpt
1522 (prev-after-lines nil
) ;; context lines of prev match
1530 (inhibit-field-text-motion t
)
1531 (headerpt (with-current-buffer out-buf
(point))))
1532 (with-current-buffer buf
1534 ;; Set CODING only if the current buffer locally
1535 ;; binds buffer-file-coding-system.
1536 (not (local-variable-p 'buffer-file-coding-system
))
1537 (setq coding buffer-file-coding-system
))
1539 (goto-char (point-min)) ;; begin searching in the buffer
1541 (setq origpt
(point))
1542 (when (setq endpt
(re-search-forward regexp nil t
))
1543 (setq lines
(1+ lines
)) ;; increment matching lines count
1544 (setq matchbeg
(match-beginning 0))
1545 ;; Get beginning of first match line and end of the last.
1547 (goto-char matchbeg
)
1548 (setq begpt
(line-beginning-position))
1550 (setq endpt
(line-end-position)))
1551 ;; Sum line numbers up to the first match line.
1552 (setq curr-line
(+ curr-line
(count-lines origpt begpt
)))
1553 (setq marker
(make-marker))
1554 (set-marker marker matchbeg
)
1555 (setq curstring
(occur-engine-line begpt endpt keep-props
))
1556 ;; Highlight the matches
1557 (let ((len (length curstring
))
1559 (while (and (< start len
)
1560 (string-match regexp curstring start
))
1561 (setq matches
(1+ matches
))
1562 (add-text-properties
1563 (match-beginning 0) (match-end 0)
1564 '(occur-match t
) curstring
)
1566 ;; Add `match-face' to faces copied from the buffer.
1567 (add-face-text-property
1568 (match-beginning 0) (match-end 0)
1569 match-face nil curstring
))
1570 ;; Avoid infloop (Bug#7593).
1571 (let ((end (match-end 0)))
1572 (setq start
(if (= start end
) (1+ start
) end
)))))
1573 ;; Generate the string to insert for this match
1574 (let* ((match-prefix
1575 ;; Using 7 digits aligns tabs properly.
1576 (apply #'propertize
(format "%7d:" curr-line
)
1579 `(font-lock-face ,prefix-face
))
1580 `(occur-prefix t mouse-face
(highlight)
1581 ;; Allow insertion of text at
1582 ;; the end of the prefix (for
1583 ;; Occur Edit mode).
1584 front-sticky t rear-nonsticky t
1585 occur-target
,marker follow-link t
1586 help-echo
"mouse-2: go to this occurrence"))))
1588 ;; We don't put `mouse-face' on the newline,
1589 ;; because that loses. And don't put it
1590 ;; on context lines to reduce flicker.
1591 (propertize curstring
'mouse-face
(list 'highlight
)
1592 'occur-target marker
1595 "mouse-2: go to this occurrence"))
1599 ;; Add non-numeric prefix to all non-first lines
1600 ;; of multi-line matches.
1601 (replace-regexp-in-string
1604 (propertize "\n :" 'font-lock-face prefix-face
)
1607 ;; Add marker at eol, but no mouse props.
1608 (propertize "\n" 'occur-target marker
)))
1611 ;; The simple display style
1613 ;; The complex multi-line display style.
1614 (setq ret
(occur-context-lines
1615 out-line nlines keep-props begpt endpt
1616 curr-line prev-line prev-after-lines
1618 ;; Set first elem of the returned list to `data',
1619 ;; and the second elem to `prev-after-lines'.
1620 (setq prev-after-lines
(nth 1 ret
))
1622 ;; Actually insert the match display data
1623 (with-current-buffer out-buf
1628 ;; Sum line numbers between first and last match lines.
1629 (setq curr-line
(+ curr-line
(count-lines begpt endpt
)
1630 ;; Add 1 for empty last match line since
1631 ;; count-lines returns 1 line less.
1632 (if (and (bolp) (eolp)) 1 0)))
1633 ;; On to the next match...
1635 (goto-char (point-max)))
1636 (setq prev-line
(1- curr-line
)))
1637 ;; Flush remaining context after-lines.
1638 (when prev-after-lines
1639 (with-current-buffer out-buf
1640 (insert (apply #'concat
(occur-engine-add-prefix
1641 prev-after-lines prefix-face
)))))))
1642 (when (not (zerop lines
)) ;; is the count zero?
1643 (setq global-lines
(+ global-lines lines
)
1644 global-matches
(+ global-matches matches
))
1645 (with-current-buffer out-buf
1646 (goto-char headerpt
)
1650 (format "%d match%s%s%s in buffer: %s\n"
1651 matches
(if (= matches
1) "" "es")
1652 ;; Don't display the same number of lines
1653 ;; and matches in case of 1 match per line.
1654 (if (= lines matches
)
1655 "" (format " in %d line%s"
1656 lines
(if (= lines
1) "" "s")))
1657 ;; Don't display regexp for multi-buffer.
1658 (if (> (length buffers
) 1)
1659 "" (format " for \"%s\""
1660 (query-replace-descr regexp
)))
1664 (add-text-properties beg end
`(occur-title ,buf
))
1666 (add-face-text-property beg end title-face
)))
1667 (goto-char (point-min)))))))
1668 ;; Display total match count and regexp for multi-buffer.
1669 (when (and (not (zerop global-lines
)) (> (length buffers
) 1))
1670 (goto-char (point-min))
1673 (insert (format "%d match%s%s total for \"%s\":\n"
1674 global-matches
(if (= global-matches
1) "" "es")
1675 ;; Don't display the same number of lines
1676 ;; and matches in case of 1 match per line.
1677 (if (= global-lines global-matches
)
1678 "" (format " in %d line%s"
1679 global-lines
(if (= global-lines
1) "" "s")))
1680 (query-replace-descr regexp
)))
1683 (add-face-text-property beg end title-face
)))
1684 (goto-char (point-min)))
1686 ;; CODING is buffer-file-coding-system of the first buffer
1687 ;; that locally binds it. Let's use it also for the output
1689 (set-buffer-file-coding-system coding
))
1690 ;; Return the number of matches
1693 (defun occur-engine-line (beg end
&optional keep-props
)
1694 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
1695 (text-property-not-all beg end
'fontified t
))
1696 (if (fboundp 'jit-lock-fontify-now
)
1697 (jit-lock-fontify-now beg end
)))
1698 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1699 (let ((str (buffer-substring beg end
)))
1700 (remove-list-of-text-properties
1701 0 (length str
) occur-excluded-properties str
)
1703 (buffer-substring-no-properties beg end
)))
1705 (defun occur-engine-add-prefix (lines &optional prefix-face
)
1708 (concat (if prefix-face
1709 (propertize " :" 'font-lock-face prefix-face
)
1714 (defun occur-accumulate-lines (count &optional keep-props pt
)
1718 (let ((forwardp (> count
0))
1719 result beg end moved
)
1720 (while (not (or (zerop count
)
1723 (and (bobp) (not moved
)))))
1724 (setq count
(+ count
(if forwardp -
1 1)))
1725 (setq beg
(line-beginning-position)
1726 end
(line-end-position))
1727 (push (occur-engine-line beg end keep-props
) result
)
1728 (setq moved
(= 0 (forward-line (if forwardp
1 -
1)))))
1729 (nreverse result
))))
1731 ;; Generate context display for occur.
1732 ;; OUT-LINE is the line where the match is.
1733 ;; NLINES and KEEP-PROPS are args to occur-engine.
1734 ;; CURR-LINE is line count of the current match,
1735 ;; PREV-LINE is line count of the previous match,
1736 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1737 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1738 ;; then concatenate them all together.
1739 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1740 curr-line prev-line prev-after-lines
1741 &optional prefix-face
)
1742 ;; Find after- and before-context lines of the current match.
1744 (nreverse (cdr (occur-accumulate-lines
1745 (- (1+ (abs nlines
))) keep-props begpt
))))
1747 (cdr (occur-accumulate-lines
1748 (1+ nlines
) keep-props endpt
)))
1751 ;; Combine after-lines of the previous match
1752 ;; with before-lines of the current match.
1754 (when prev-after-lines
1755 ;; Don't overlap prev after-lines with current before-lines.
1756 (if (>= (+ prev-line
(length prev-after-lines
))
1757 (- curr-line
(length before-lines
)))
1758 (setq prev-after-lines
1759 (butlast prev-after-lines
1760 (- (length prev-after-lines
)
1761 (- curr-line prev-line
(length before-lines
) 1))))
1762 ;; Separate non-overlapping context lines with a dashed line.
1763 (setq separator
"-------\n")))
1766 ;; Don't overlap current before-lines with previous match line.
1767 (if (<= (- curr-line
(length before-lines
))
1770 (nthcdr (- (length before-lines
)
1771 (- curr-line prev-line
1))
1773 ;; Separate non-overlapping before-context lines.
1774 (unless (> nlines
0)
1775 (setq separator
"-------\n"))))
1778 ;; Return a list where the first element is the output line.
1781 (if prev-after-lines
1782 (occur-engine-add-prefix prev-after-lines prefix-face
))
1784 (list (if prefix-face
1785 (propertize separator
'font-lock-face prefix-face
)
1787 (occur-engine-add-prefix before-lines prefix-face
)
1789 ;; And the second element is the list of context after-lines.
1790 (if (> nlines
0) after-lines
))))
1793 ;; It would be nice to use \\[...], but there is no reasonable way
1794 ;; to make that display both SPC and Y.
1795 (defconst query-replace-help
1796 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1797 RET or `q' to exit, Period to replace one match and exit,
1798 Comma to replace but not move point immediately,
1799 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1800 C-w to delete match and recursive edit,
1801 C-l to clear the screen, redisplay, and offer same replacement again,
1802 ! to replace all remaining matches in this buffer with no more questions,
1803 ^ to move point back to previous match,
1804 E to edit the replacement string.
1805 In multi-buffer replacements type `Y' to replace all remaining
1806 matches in all remaining buffers with no more questions,
1807 `N' to skip to the next buffer without replacing remaining matches
1808 in the current buffer."
1809 "Help message while in `query-replace'.")
1811 (defvar query-replace-map
1812 (let ((map (make-sparse-keymap)))
1813 (define-key map
" " 'act
)
1814 (define-key map
"\d" 'skip
)
1815 (define-key map
[delete] 'skip)
1816 (define-key map [backspace] 'skip)
1817 (define-key map "y" 'act)
1818 (define-key map "n" 'skip)
1819 (define-key map "Y" 'act)
1820 (define-key map "N" 'skip)
1821 (define-key map "e" 'edit-replacement)
1822 (define-key map "E" 'edit-replacement)
1823 (define-key map "," 'act-and-show)
1824 (define-key map "q" 'exit)
1825 (define-key map "\r" 'exit)
1826 (define-key map [return] 'exit)
1827 (define-key map "." 'act-and-exit)
1828 (define-key map "\C-r" 'edit)
1829 (define-key map "\C-w" 'delete-and-edit)
1830 (define-key map "\C-l" 'recenter)
1831 (define-key map "!" 'automatic)
1832 (define-key map "^" 'backup)
1833 (define-key map "\C-h" 'help)
1834 (define-key map [f1] 'help)
1835 (define-key map [help] 'help)
1836 (define-key map "?" 'help)
1837 (define-key map "\C-g" 'quit)
1838 (define-key map "\C-]" 'quit)
1839 (define-key map "\C-v" 'scroll-up)
1840 (define-key map "\M-v" 'scroll-down)
1841 (define-key map [next] 'scroll-up)
1842 (define-key map [prior] 'scroll-down)
1843 (define-key map [?\C-\M-v] 'scroll-other-window)
1844 (define-key map [M-next] 'scroll-other-window)
1845 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1846 (define-key map [M-prior] 'scroll-other-window-down)
1847 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1848 ;; should check for ESC specially.
1849 ;; (define-key map "\e" 'exit-prefix)
1850 (define-key map [escape] 'exit-prefix)
1852 "Keymap of responses to questions posed by commands like `query-replace'.
1853 The \"bindings\" in this map are not commands; they are answers.
1854 The valid answers include `act', `skip', `act-and-show',
1855 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1856 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1857 `edit', `edit-replacement', `delete-and-edit', `automatic',
1858 `backup', `quit', and `help'.
1860 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1862 (defvar multi-query-replace-map
1863 (let ((map (make-sparse-keymap)))
1864 (set-keymap-parent map query-replace-map)
1865 (define-key map "Y" 'automatic-all)
1866 (define-key map "N" 'exit-current)
1868 "Keymap that defines additional bindings for multi-buffer replacements.
1869 It extends its parent map `query-replace-map' with new bindings to
1870 operate on a set of buffers/files. The difference with its parent map
1871 is the additional answers `automatic-all' to replace all remaining
1872 matches in all remaining buffers with no more questions, and
1873 `exit-current' to skip remaining matches in the current buffer
1874 and to continue with the next buffer in the sequence.")
1876 (defun replace-match-string-symbols (n)
1877 "Process a list (and any sub-lists), expanding certain symbols.
1879 N (match-string N) (where N is a string of digits)
1880 #N (string-to-number (match-string N))
1882 #& (string-to-number (match-string 0))
1885 Note that these symbols must be preceded by a backslash in order to
1886 type them using Lisp syntax."
1890 (replace-match-string-symbols (car n))) ;Process sub-list
1892 (let ((name (symbol-name (car n))))
1894 ((string-match "^[0-9]+$" name)
1895 (setcar n (list 'match-string (string-to-number name))))
1896 ((string-match "^#[0-9]+$" name)
1897 (setcar n (list 'string-to-number
1899 (string-to-number (substring name 1))))))
1901 (setcar n '(match-string 0)))
1902 ((string= "#&" name)
1903 (setcar n '(string-to-number (match-string 0))))
1905 (setcar n 'replace-count))))))
1908 (defun replace-eval-replacement (expression count)
1909 (let* ((replace-count count)
1915 (error "Error evaluating replacement expression: %S" err)))))
1916 (if (stringp replacement)
1918 (prin1-to-string replacement t))))
1920 (defun replace-quote (replacement)
1921 "Quote a replacement string.
1922 This just doubles all backslashes in REPLACEMENT and
1923 returns the resulting string. If REPLACEMENT is not
1924 a string, it is first passed through `prin1-to-string'
1925 with the `noescape' argument set.
1927 `match-data' is preserved across the call."
1929 (replace-regexp-in-string "\\\\" "\\\\"
1930 (if (stringp replacement)
1932 (prin1-to-string replacement t))
1935 (defun replace-loop-through-replacements (data count)
1936 ;; DATA is a vector containing the following values:
1937 ;; 0 next-rotate-count
1939 ;; 2 next-replacement
1941 (if (= (aref data 0) count)
1943 (aset data 0 (+ count (aref data 1)))
1944 (let ((next (cdr (aref data 2))))
1945 (aset data 2 (if (consp next) next (aref data 3))))))
1946 (car (aref data 2)))
1948 (defun replace-match-data (integers reuse &optional new)
1949 "Like `match-data', but markers in REUSE get invalidated.
1950 If NEW is non-nil, it is set and returned instead of fresh data,
1951 but coerced to the correct value of INTEGERS."
1954 (set-match-data new)
1956 (eq (null integers) (markerp (car reuse)))
1958 (match-data integers reuse t)))
1960 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data backward)
1961 "Make a replacement with `replace-match', editing `\\?'.
1962 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
1963 After possibly editing it (if `\\?' is present), NEWTEXT is also
1964 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
1965 is made (to save time). MATCH-DATA is used for the replacement.
1966 In case editing is done, it is changed to use markers.
1968 The return value is non-nil if there has been no `\\?' or NOEDIT was
1969 passed in. If LITERAL is set, no checking is done, anyway."
1970 (unless (or literal noedit)
1972 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1975 (read-string "Edit replacement string: "
1978 (replace-match "" t t newtext 3)
1979 (1+ (match-beginning 3)))
1982 nil match-data match-data))))
1984 (set-match-data match-data)
1985 (replace-match newtext fixedcase literal)
1986 ;; `replace-match' leaves point at the end of the replacement text,
1987 ;; so move point to the beginning when replacing backward.
1988 (when backward (goto-char (nth 0 match-data)))
1991 (defvar replace-search-function nil
1992 "Function to use when searching for strings to replace.
1993 It is used by `query-replace' and `replace-string', and is called
1994 with three arguments, as if it were `search-forward'.")
1996 (defvar replace-re-search-function nil
1997 "Function to use when searching for regexps to replace.
1998 It is used by `query-replace-regexp', `replace-regexp',
1999 `query-replace-regexp-eval', and `map-query-replace-regexp'.
2000 It is called with three arguments, as if it were
2001 `re-search-forward'.")
2003 (defun replace-search (search-string limit regexp-flag delimited-flag
2004 case-fold-search backward)
2005 "Search for the next occurrence of SEARCH-STRING to replace."
2006 ;; Let-bind global isearch-* variables to values used
2007 ;; to search the next replacement. These let-bindings
2008 ;; should be effective both at the time of calling
2009 ;; `isearch-search-fun-default' and also at the
2010 ;; time of funcalling `search-function'.
2011 ;; These isearch-* bindings can't be placed higher
2012 ;; outside of this function because then another I-search
2013 ;; used after `recursive-edit' might override them.
2014 (let* ((isearch-regexp regexp-flag)
2015 (isearch-word (or delimited-flag
2016 (and replace-character-fold
2018 #'character-fold-to-regexp)))
2019 (isearch-lax-whitespace
2020 replace-lax-whitespace)
2021 (isearch-regexp-lax-whitespace
2022 replace-regexp-lax-whitespace)
2023 (isearch-case-fold-search case-fold-search)
2024 (isearch-adjusted nil)
2025 (isearch-nonincremental t) ; don't use lax word mode
2026 (isearch-forward (not backward))
2029 replace-re-search-function
2030 replace-search-function)
2031 (isearch-search-fun-default))))
2032 (funcall search-function search-string limit t)))
2034 (defvar replace-overlay nil)
2036 (defun replace-highlight (match-beg match-end range-beg range-end
2037 search-string regexp-flag delimited-flag
2038 case-fold-search backward)
2039 (if query-replace-highlight
2041 (move-overlay replace-overlay match-beg match-end (current-buffer))
2042 (setq replace-overlay (make-overlay match-beg match-end))
2043 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2044 (overlay-put replace-overlay 'face 'query-replace)))
2045 (if query-replace-lazy-highlight
2046 (let ((isearch-string search-string)
2047 (isearch-regexp regexp-flag)
2048 (isearch-word delimited-flag)
2049 (isearch-lax-whitespace
2050 replace-lax-whitespace)
2051 (isearch-regexp-lax-whitespace
2052 replace-regexp-lax-whitespace)
2053 (isearch-case-fold-search case-fold-search)
2054 (isearch-forward (not backward))
2055 (isearch-other-end match-beg)
2056 (isearch-error nil))
2057 (isearch-lazy-highlight-new-loop range-beg range-end))))
2059 (defun replace-dehighlight ()
2060 (when replace-overlay
2061 (delete-overlay replace-overlay))
2062 (when query-replace-lazy-highlight
2063 (lazy-highlight-cleanup lazy-highlight-cleanup)
2064 (setq isearch-lazy-highlight-last-string nil))
2065 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2066 (isearch-clean-overlays))
2068 (defun perform-replace (from-string replacements
2069 query-flag regexp-flag delimited-flag
2070 &optional repeat-count map start end backward)
2071 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2072 Don't use this in your own program unless you want to query and set the mark
2073 just as `query-replace' does. Instead, write a simple loop like this:
2075 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2076 (replace-match \"foobar\" nil nil))
2078 which will run faster and probably do exactly what you want. Please
2079 see the documentation of `replace-match' to find out how to simulate
2082 This function returns nil if and only if there were no matches to
2083 make, or the user didn't cancel the call."
2084 (or map (setq map query-replace-map))
2085 (and query-flag minibuffer-auto-raise
2086 (raise-frame (window-frame (minibuffer-window))))
2087 (let* ((case-fold-search
2088 (if (and case-fold-search search-upper-case)
2089 (isearch-no-upper-case-p from-string regexp-flag)
2091 (nocasify (not (and case-replace case-fold-search)))
2092 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2093 (search-string from-string)
2094 (real-match-data nil) ; The match data for the current match.
2095 (next-replacement nil)
2096 ;; This is non-nil if we know there is nothing for the user
2097 ;; to edit in the replacement.
2102 (skip-read-only-count 0)
2103 (skip-filtered-count 0)
2104 (skip-invisible-count 0)
2105 (nonempty-match nil)
2107 (recenter-last-op nil) ; Start cycling order with initial position.
2109 ;; If non-nil, it is marker saying where in the buffer to stop.
2112 ;; Data for the next match. If a cons, it has the same format as
2113 ;; (match-data); otherwise it is t if a match is possible at point.
2119 (substitute-command-keys
2120 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2121 minibuffer-prompt-properties))))
2123 ;; If region is active, in Transient Mark mode, operate on region.
2126 (setq limit (copy-marker (min start end)))
2127 (goto-char (max start end))
2130 (setq limit (copy-marker (max start end)))
2131 (goto-char (min start end))
2134 ;; If last typed key in previous call of multi-buffer perform-replace
2135 ;; was `automatic-all', don't ask more questions in next files
2136 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2137 (setq query-flag nil multi-buffer t))
2139 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
2140 ;; containing a function and its first argument. The function is
2141 ;; called to generate each replacement like this:
2142 ;; (funcall (car replacements) (cdr replacements) replace-count)
2143 ;; It must return a string.
2145 ((stringp replacements)
2146 (setq next-replacement replacements
2148 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2149 (or repeat-count (setq repeat-count 1))
2150 (setq replacements (cons 'replace-loop-through-replacements
2151 (vector repeat-count repeat-count
2152 replacements replacements)))))
2154 (when query-replace-lazy-highlight
2155 (setq isearch-lazy-highlight-last-string nil))
2160 ;; Loop finding occurrences that perhaps should be replaced.
2161 (while (and keep-going
2163 (not (or (bobp) (and limit (<= (point) limit))))
2164 (not (or (eobp) (and limit (>= (point) limit)))))
2165 ;; Use the next match if it is already known;
2166 ;; otherwise, search for a match after moving forward
2167 ;; one char if progress is required.
2168 (setq real-match-data
2169 (cond ((consp match-again)
2170 (goto-char (if backward
2172 (nth 1 match-again)))
2174 t real-match-data match-again))
2175 ;; MATCH-AGAIN non-nil means accept an
2179 (replace-search search-string limit
2180 regexp-flag delimited-flag
2181 case-fold-search backward)
2182 ;; For speed, use only integers and
2183 ;; reuse the list used last time.
2184 (replace-match-data t real-match-data)))
2186 (> (1- (point)) (point-min))
2187 (< (1+ (point)) (point-max)))
2190 (> (1- (point)) limit)
2191 (< (1+ (point)) limit))))
2192 ;; If not accepting adjacent matches,
2193 ;; move one char to the right before
2194 ;; searching again. Undo the motion
2195 ;; if the search fails.
2196 (let ((opoint (point)))
2197 (forward-char (if backward -1 1))
2198 (if (replace-search search-string limit
2199 regexp-flag delimited-flag
2200 case-fold-search backward)
2206 ;; Record whether the match is nonempty, to avoid an infinite loop
2207 ;; repeatedly matching the same empty string.
2208 (setq nonempty-match
2209 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2211 ;; If the match is empty, record that the next one can't be
2214 ;; Otherwise, if matching a regular expression, do the next
2215 ;; match now, since the replacement for this match may
2216 ;; affect whether the next match is adjacent to this one.
2217 ;; If that match is empty, don't use it.
2220 (or (not regexp-flag)
2222 (looking-back search-string)
2223 (looking-at search-string))
2224 (let ((match (match-data)))
2225 (and (/= (nth 0 match) (nth 1 match))
2229 ;; Optionally ignore matches that have a read-only property.
2230 ((not (or (not query-replace-skip-read-only)
2231 (not (text-property-not-all
2232 (nth 0 real-match-data) (nth 1 real-match-data)
2234 (setq skip-read-only-count (1+ skip-read-only-count)))
2235 ;; Optionally filter out matches.
2236 ((not (funcall isearch-filter-predicate
2237 (nth 0 real-match-data) (nth 1 real-match-data)))
2238 (setq skip-filtered-count (1+ skip-filtered-count)))
2239 ;; Optionally ignore invisible matches.
2240 ((not (or (eq search-invisible t)
2241 ;; Don't open overlays for automatic replacements.
2242 (and (not query-flag) search-invisible)
2243 ;; Open hidden overlays for interactive replacements.
2244 (not (isearch-range-invisible
2245 (nth 0 real-match-data) (nth 1 real-match-data)))))
2246 (setq skip-invisible-count (1+ skip-invisible-count)))
2248 ;; Calculate the replacement string, if necessary.
2250 (set-match-data real-match-data)
2251 (setq next-replacement
2252 (funcall (car replacements) (cdr replacements)
2254 (if (not query-flag)
2256 (unless (or literal noedit)
2258 (nth 0 real-match-data) (nth 1 real-match-data)
2259 start end search-string
2260 regexp-flag delimited-flag case-fold-search backward))
2262 (replace-match-maybe-edit
2263 next-replacement nocasify literal
2264 noedit real-match-data backward)
2265 replace-count (1+ replace-count)))
2267 (let (done replaced key def)
2268 ;; Loop reading commands until one of them sets done,
2269 ;; which means it has finished handling this
2270 ;; occurrence. Any command that sets `done' should
2271 ;; leave behind proper match data for the stack.
2272 ;; Commands not setting `done' need to adjust
2273 ;; `real-match-data'.
2275 (set-match-data real-match-data)
2277 (match-beginning 0) (match-end 0)
2278 start end search-string
2279 regexp-flag delimited-flag case-fold-search backward)
2280 ;; Bind message-log-max so we don't fill up the message log
2281 ;; with a bunch of identical messages.
2282 (let ((message-log-max nil)
2283 (replacement-presentation
2284 (if query-replace-show-replacement
2286 (set-match-data real-match-data)
2287 (match-substitute-replacement next-replacement
2291 (query-replace-descr from-string)
2292 (query-replace-descr replacement-presentation)))
2293 (setq key (read-event))
2294 ;; Necessary in case something happens during read-event
2295 ;; that clobbers the match data.
2296 (set-match-data real-match-data)
2297 (setq key (vector key))
2298 (setq def (lookup-key map key))
2299 ;; Restore the match data while we process the command.
2300 (cond ((eq def 'help)
2301 (with-output-to-temp-buffer "*Help*"
2303 (concat "Query replacing "
2305 (or (and (symbolp delimited-flag)
2306 (get delimited-flag 'isearch-message-prefix))
2308 (if regexp-flag "regexp " "")
2309 (if backward "backward " "")
2310 from-string " with "
2311 next-replacement ".\n\n"
2312 (substitute-command-keys
2313 query-replace-help)))
2314 (with-current-buffer standard-output
2317 (setq keep-going nil)
2319 ((eq def 'exit-current)
2320 (setq multi-buffer t keep-going nil done t))
2323 (let ((elt (pop stack)))
2324 (goto-char (nth 0 elt))
2325 (setq replaced (nth 1 elt)
2330 (message "No previous match")
2331 (ding 'no-terminate)
2336 (replace-match-maybe-edit
2337 next-replacement nocasify literal
2338 noedit real-match-data backward)
2339 replace-count (1+ replace-count)))
2340 (setq done t replaced t))
2341 ((eq def 'act-and-exit)
2344 (replace-match-maybe-edit
2345 next-replacement nocasify literal
2346 noedit real-match-data backward)
2347 replace-count (1+ replace-count)))
2348 (setq keep-going nil)
2349 (setq done t replaced t))
2350 ((eq def 'act-and-show)
2353 (replace-match-maybe-edit
2354 next-replacement nocasify literal
2355 noedit real-match-data backward)
2356 replace-count (1+ replace-count)
2357 real-match-data (replace-match-data
2360 ((or (eq def 'automatic) (eq def 'automatic-all))
2363 (replace-match-maybe-edit
2364 next-replacement nocasify literal
2365 noedit real-match-data backward)
2366 replace-count (1+ replace-count)))
2367 (setq done t query-flag nil replaced t)
2368 (if (eq def 'automatic-all) (setq multi-buffer t)))
2372 ;; `this-command' has the value `query-replace',
2373 ;; so we need to bind it to `recenter-top-bottom'
2374 ;; to allow it to detect a sequence of `C-l'.
2375 (let ((this-command 'recenter-top-bottom)
2376 (last-command 'recenter-top-bottom))
2377 (recenter-top-bottom)))
2379 (let ((opos (point-marker)))
2380 (setq real-match-data (replace-match-data
2383 (goto-char (match-beginning 0))
2385 (save-window-excursion
2388 (set-marker opos nil))
2389 ;; Before we make the replacement,
2390 ;; decide whether the search string
2391 ;; can match again just after this match.
2392 (if (and regexp-flag nonempty-match)
2393 (setq match-again (and (looking-at search-string)
2395 ;; Edit replacement.
2396 ((eq def 'edit-replacement)
2397 (setq real-match-data (replace-match-data
2401 (read-string "Edit replacement string: "
2405 (set-match-data real-match-data)
2407 (replace-match-maybe-edit
2408 next-replacement nocasify literal noedit
2409 real-match-data backward)
2413 ((eq def 'delete-and-edit)
2414 (replace-match "" t t)
2415 (setq real-match-data (replace-match-data
2416 nil real-match-data))
2417 (replace-dehighlight)
2418 (save-excursion (recursive-edit))
2420 ;; Note: we do not need to treat `exit-prefix'
2421 ;; specially here, since we reread
2422 ;; any unrecognized character.
2424 (setq this-command 'mode-exited)
2425 (setq keep-going nil)
2426 (setq unread-command-events
2427 (append (listify-key-sequence key)
2428 unread-command-events))
2430 (when query-replace-lazy-highlight
2431 ;; Force lazy rehighlighting only after replacements.
2432 (if (not (memq def '(skip backup)))
2433 (setq isearch-lazy-highlight-last-string nil)))
2434 (unless (eq def 'recenter)
2435 ;; Reset recenter cycling order to initial position.
2436 (setq recenter-last-op nil)))
2437 ;; Record previous position for ^ when we move on.
2438 ;; Change markers to numbers in the match data
2439 ;; since lots of markers slow down editing.
2440 (push (list (point) replaced
2441 ;;; If the replacement has already happened, all we need is the
2442 ;;; current match start and end. We could get this with a trivial
2444 ;;; (save-excursion (goto-char (match-beginning 0))
2445 ;;; (search-forward (match-string 0))
2447 ;;; if we really wanted to avoid manually constructing match data.
2448 ;;; Adding current-buffer is necessary so that match-data calls can
2449 ;;; return markers which are appropriate for editing.
2458 (replace-dehighlight))
2459 (or unread-command-events
2460 (message "Replaced %d occurrence%s%s"
2462 (if (= replace-count 1) "" "s")
2463 (if (> (+ skip-read-only-count
2465 skip-invisible-count) 0)
2466 (format " (skipped %s)"
2470 (if (> skip-read-only-count 0)
2471 (format "%s read-only"
2472 skip-read-only-count))
2473 (if (> skip-invisible-count 0)
2474 (format "%s invisible"
2475 skip-invisible-count))
2476 (if (> skip-filtered-count 0)
2477 (format "%s filtered out"
2478 skip-filtered-count))))
2481 (or (and keep-going stack) multi-buffer)))
2483 ;;; replace.el ends here