1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2014 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-lax-whitespace nil
37 "Non-nil means `query-replace' matches a sequence of whitespace chars.
38 When you enter a space or spaces in the strings to be replaced,
39 it will match any sequence matched by the regexp `search-whitespace-regexp'."
44 (defcustom replace-regexp-lax-whitespace nil
45 "Non-nil means `query-replace-regexp' matches a sequence of whitespace chars.
46 When you enter a space or spaces in the regexps to be replaced,
47 it will match any sequence matched by the regexp `search-whitespace-regexp'."
52 (defvar query-replace-history nil
53 "Default history list for query-replace commands.
54 See `query-replace-from-history-variable' and
55 `query-replace-to-history-variable'.")
57 (defvar query-replace-defaults nil
58 "Default values of FROM-STRING and TO-STRING for `query-replace'.
59 This is a list of cons cells (FROM-STRING . TO-STRING), or nil
60 if there are no default values.")
62 (defvar query-replace-interactive nil
63 "Non-nil means `query-replace' uses the last search string.
64 That becomes the \"string to replace\".")
65 (make-obsolete-variable 'query-replace-interactive
66 "use `M-n' to pull the last incremental search string
67 to the minibuffer that reads the string to replace, or invoke replacements
68 from Isearch by using a key sequence like `C-s C-s M-%'." "24.3")
70 (defcustom query-replace-from-to-separator
73 (if (char-displayable-p ?
\u2192) " \u2192 " " -> "))
75 'face
'minibuffer-prompt
)
76 "String that separates FROM and TO in the history of replacement pairs."
81 (defcustom query-replace-from-history-variable
'query-replace-history
82 "History list to use for the FROM argument of `query-replace' commands.
83 The value of this variable should be a symbol; that symbol
84 is used as a variable to hold a history list for the strings
85 or patterns to be replaced."
90 (defcustom query-replace-to-history-variable
'query-replace-history
91 "History list to use for the TO argument of `query-replace' commands.
92 The value of this variable should be a symbol; that symbol
93 is used as a variable to hold a history list for replacement
99 (defcustom query-replace-skip-read-only nil
100 "Non-nil means `query-replace' and friends ignore read-only matches."
105 (defcustom query-replace-show-replacement t
106 "Non-nil means to show what actual replacement text will be."
111 (defcustom query-replace-highlight t
112 "Non-nil means to highlight matches during query replacement."
116 (defcustom query-replace-lazy-highlight t
117 "Controls the lazy-highlighting during query replacements.
118 When non-nil, all text in the buffer matching the current match
119 is highlighted lazily using isearch lazy highlighting (see
120 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
122 :group
'lazy-highlight
126 (defface query-replace
127 '((t (:inherit isearch
)))
128 "Face for highlighting query replacement matches."
132 (defvar replace-count
0
133 "Number of replacements done so far.
134 See `replace-regexp' and `query-replace-regexp-eval'.")
136 (defun query-replace-descr (string)
137 (mapconcat 'isearch-text-char-description string
""))
139 (defun query-replace-read-from (prompt regexp-flag
)
140 "Query and return the `from' argument of a query-replace operation.
141 The return value can also be a pair (FROM . TO) indicating that the user
142 wants to replace FROM with TO."
143 (if query-replace-interactive
144 (car (if regexp-flag regexp-search-ring search-ring
))
145 (custom-reevaluate-setting 'query-replace-from-to-separator
)
146 (let* ((history-add-new-input nil
)
148 (when query-replace-from-to-separator
150 'display query-replace-from-to-separator
152 (query-replace-from-to-history
155 (mapcar (lambda (from-to)
156 (concat (query-replace-descr (car from-to
))
158 (query-replace-descr (cdr from-to
))))
159 query-replace-defaults
))
160 (symbol-value query-replace-from-history-variable
)))
161 (minibuffer-allow-text-properties t
) ; separator uses text-properties
163 (if (and query-replace-defaults separator
)
164 (format "%s (default %s): " prompt
(car query-replace-from-to-history
))
165 (format "%s: " prompt
)))
167 ;; The save-excursion here is in case the user marks and copies
168 ;; a region in order to specify the minibuffer input.
169 ;; That should not clobber the region for the query-replace itself.
172 (read-regexp prompt nil
'query-replace-from-to-history
)
173 (read-from-minibuffer
174 prompt nil nil nil
'query-replace-from-to-history
175 (car (if regexp-flag regexp-search-ring search-ring
)) t
)))))
176 (if (and (zerop (length from
)) query-replace-defaults
)
177 (cons (caar query-replace-defaults
)
178 (query-replace-compile-replacement
179 (cdar query-replace-defaults
) regexp-flag
))
180 (let* ((to (if (and (string-match separator from
)
181 (get-text-property (match-beginning 0) 'separator from
))
182 (query-replace-compile-replacement
183 (substring-no-properties from
(match-end 0)) regexp-flag
)))
184 (from (if to
(substring-no-properties from
0 (match-beginning 0))
185 (substring-no-properties from
))))
186 (add-to-history query-replace-from-history-variable from nil t
)
187 ;; Warn if user types \n or \t, but don't reject the input.
189 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
190 (let ((match (match-string 3 from
)))
192 ((string= match
"\\n")
193 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
194 ((string= match
"\\t")
195 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
199 (add-to-history query-replace-to-history-variable to nil t
)
200 (add-to-history 'query-replace-defaults
(cons from to
) nil t
)
203 (defun query-replace-compile-replacement (to regexp-flag
)
204 "Maybe convert a regexp replacement TO to Lisp.
205 Returns a list suitable for `perform-replace' if necessary,
206 the original string if not."
208 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
))
212 (setq pos
(match-end 0))
213 (push (substring to
0 (- pos
2)) list
)
214 (setq char
(aref to
(1- pos
))
215 to
(substring to pos
))
217 (push '(number-to-string replace-count
) list
))
219 (setq pos
(read-from-string to
))
220 (push `(replace-quote ,(car pos
)) list
)
222 ;; Swallow a space after a symbol
223 ;; if there is a space.
224 (if (and (or (symbolp (car pos
))
225 ;; Swallow a space after 'foo
226 ;; but not after (quote foo).
227 (and (eq (car-safe (car pos
)) 'quote
)
228 (not (= ?\
( (aref to
0)))))
229 (eq (string-match " " to
(cdr pos
))
233 (setq to
(substring to end
)))))
234 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
)))
235 (setq to
(nreverse (delete "" (cons to list
))))
236 (replace-match-string-symbols to
)
237 (cons 'replace-eval-replacement
244 (defun query-replace-read-to (from prompt regexp-flag
)
245 "Query and return the `to' argument of a query-replace operation."
246 (query-replace-compile-replacement
248 (let* ((history-add-new-input nil
)
249 (to (read-from-minibuffer
250 (format "%s %s with: " prompt
(query-replace-descr from
))
252 query-replace-to-history-variable from t
)))
253 (add-to-history query-replace-to-history-variable to nil t
)
254 (add-to-history 'query-replace-defaults
(cons from to
) nil t
)
258 (defun query-replace-read-args (prompt regexp-flag
&optional noerror
)
260 (barf-if-buffer-read-only))
261 (let* ((from (query-replace-read-from prompt regexp-flag
))
262 (to (if (consp from
) (prog1 (cdr from
) (setq from
(car from
)))
263 (query-replace-read-to from prompt regexp-flag
))))
265 (and current-prefix-arg
(not (eq current-prefix-arg
'-
)))
266 (and current-prefix-arg
(eq current-prefix-arg
'-
)))))
268 (defun query-replace (from-string to-string
&optional delimited start end backward
)
269 "Replace some occurrences of FROM-STRING with TO-STRING.
270 As each match is found, the user must type a character saying
271 what to do with it. For directions, type \\[help-command] at that time.
273 In Transient Mark mode, if the mark is active, operate on the contents
274 of the region. Otherwise, operate from point to the end of the buffer.
276 Use \\<minibuffer-local-map>\\[next-history-element] \
277 to pull the last incremental search string to the minibuffer
278 that reads FROM-STRING, or invoke replacements from
279 incremental search with a key sequence like `C-s C-s M-%'
280 to use its current search string as the string to replace.
282 Matching is independent of case if `case-fold-search' is non-nil and
283 FROM-STRING has no uppercase letters. Replacement transfers the case
284 pattern of the old text to the new text, if `case-replace' and
285 `case-fold-search' are non-nil and FROM-STRING has no uppercase
286 letters. (Transferring the case pattern means that if the old text
287 matched is all caps, or capitalized, then its replacement is upcased
290 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
291 ignore hidden matches if `search-invisible' is nil, and ignore more
292 matches using `isearch-filter-predicate'.
294 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
295 to be replaced will match a sequence of whitespace chars defined by the
296 regexp in `search-whitespace-regexp'.
298 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
299 only matches surrounded by word boundaries. A negative prefix arg means
302 Fourth and fifth arg START and END specify the region to operate on.
304 To customize possible responses, change the bindings in `query-replace-map'."
307 (query-replace-read-args
308 (concat "Query replace"
309 (if current-prefix-arg
310 (if (eq current-prefix-arg
'-
) " backward" " word")
312 (if (and transient-mark-mode mark-active
) " in region" ""))
314 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
315 ;; These are done separately here
316 ;; so that command-history will record these expressions
317 ;; rather than the values they had this time.
318 (if (and transient-mark-mode mark-active
)
320 (if (and transient-mark-mode mark-active
)
323 (perform-replace from-string to-string t nil delimited nil nil start end backward
))
325 (define-key esc-map
"%" 'query-replace
)
327 (defun query-replace-regexp (regexp to-string
&optional delimited start end backward
)
328 "Replace some things after point matching REGEXP with TO-STRING.
329 As each match is found, the user must type a character saying
330 what to do with it. For directions, type \\[help-command] at that time.
332 In Transient Mark mode, if the mark is active, operate on the contents
333 of the region. Otherwise, operate from point to the end of the buffer.
335 Use \\<minibuffer-local-map>\\[next-history-element] \
336 to pull the last incremental search regexp to the minibuffer
337 that reads REGEXP, or invoke replacements from
338 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
339 to use its current search regexp as the regexp to replace.
341 Matching is independent of case if `case-fold-search' is non-nil and
342 REGEXP has no uppercase letters. Replacement transfers the case
343 pattern of the old text to the new text, if `case-replace' and
344 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
345 \(Transferring the case pattern means that if the old text matched is
346 all caps, or capitalized, then its replacement is upcased or
349 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
350 ignore hidden matches if `search-invisible' is nil, and ignore more
351 matches using `isearch-filter-predicate'.
353 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
354 to be replaced will match a sequence of whitespace chars defined by the
355 regexp in `search-whitespace-regexp'.
357 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
358 only matches surrounded by word boundaries. A negative prefix arg means
361 Fourth and fifth arg START and END specify the region to operate on.
363 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
364 and `\\=\\N' (where N is a digit) stands for
365 whatever what matched the Nth `\\(...\\)' in REGEXP.
366 `\\?' lets you edit the replacement text in the minibuffer
367 at the given position for each replacement.
369 In interactive calls, the replacement text can contain `\\,'
370 followed by a Lisp expression. Each
371 replacement evaluates that expression to compute the replacement
372 string. Inside of that expression, `\\&' is a string denoting the
373 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
374 for the whole or a partial match converted to a number with
375 `string-to-number', and `\\#' itself for the number of replacements
376 done so far (starting with zero).
378 If the replacement expression is a symbol, write a space after it
379 to terminate it. One space there, if any, will be discarded.
381 When using those Lisp features interactively in the replacement
382 text, TO-STRING is actually made a list instead of a string.
383 Use \\[repeat-complex-command] after this command for details."
386 (query-replace-read-args
387 (concat "Query replace"
388 (if current-prefix-arg
389 (if (eq current-prefix-arg
'-
) " backward" " word")
392 (if (and transient-mark-mode mark-active
) " in region" ""))
394 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
395 ;; These are done separately here
396 ;; so that command-history will record these expressions
397 ;; rather than the values they had this time.
398 (if (and transient-mark-mode mark-active
)
400 (if (and transient-mark-mode mark-active
)
403 (perform-replace regexp to-string t t delimited nil nil start end backward
))
405 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
407 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
408 "Replace some things after point matching REGEXP with the result of TO-EXPR.
410 Interactive use of this function is deprecated in favor of the
411 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
412 using `search-forward-regexp' and `replace-match' is preferred.
414 As each match is found, the user must type a character saying
415 what to do with it. For directions, type \\[help-command] at that time.
417 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
418 reference `replace-count' to get the number of replacements already made.
419 If the result of TO-EXPR is not a string, it is converted to one using
420 `prin1-to-string' with the NOESCAPE argument (which see).
422 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
423 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
424 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
425 Use `\\#&' or `\\#N' if you want a number instead of a string.
426 In interactive use, `\\#' in itself stands for `replace-count'.
428 In Transient Mark mode, if the mark is active, operate on the contents
429 of the region. Otherwise, operate from point to the end of the buffer.
431 Use \\<minibuffer-local-map>\\[next-history-element] \
432 to pull the last incremental search regexp to the minibuffer
435 Preserves case in each replacement if `case-replace' and `case-fold-search'
436 are non-nil and REGEXP has no uppercase letters.
438 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
439 ignore hidden matches if `search-invisible' is nil, and ignore more
440 matches using `isearch-filter-predicate'.
442 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
443 to be replaced will match a sequence of whitespace chars defined by the
444 regexp in `search-whitespace-regexp'.
446 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
447 only matches that are surrounded by word boundaries.
448 Fourth and fifth arg START and END specify the region to operate on."
449 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
450 for interactive calls, and `search-forward-regexp'/`replace-match'
451 for Lisp calls." "22.1"))
454 (barf-if-buffer-read-only)
456 ;; Let-bind the history var to disable the "foo -> bar"
457 ;; default. Maybe we shouldn't disable this default, but
458 ;; for now I'll leave it off. --Stef
459 (let ((query-replace-defaults nil
))
460 (query-replace-read-from "Query replace regexp" t
)))
461 (to (list (read-from-minibuffer
462 (format "Query replace regexp %s with eval: "
463 (query-replace-descr from
))
464 nil nil t query-replace-to-history-variable from t
))))
465 ;; We make TO a list because replace-match-string-symbols requires one,
466 ;; and the user might enter a single token.
467 (replace-match-string-symbols to
)
468 (list from
(car to
) current-prefix-arg
469 (if (and transient-mark-mode mark-active
)
471 (if (and transient-mark-mode mark-active
)
473 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
474 t
'literal delimited nil nil start end
))
476 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
477 "Replace some matches for REGEXP with various strings, in rotation.
478 The second argument TO-STRINGS contains the replacement strings, separated
479 by spaces. This command works like `query-replace-regexp' except that
480 each successive replacement uses the next successive replacement string,
481 wrapping around from the last such string to the first.
483 In Transient Mark mode, if the mark is active, operate on the contents
484 of the region. Otherwise, operate from point to the end of the buffer.
486 Non-interactively, TO-STRINGS may be a list of replacement strings.
488 Interactively, reads the regexp using `read-regexp'.
489 Use \\<minibuffer-local-map>\\[next-history-element] \
490 to pull the last incremental search regexp to the minibuffer
493 A prefix argument N says to use each replacement string N times
494 before rotating to the next.
495 Fourth and fifth arg START and END specify the region to operate on."
497 (let* ((from (read-regexp "Map query replace (regexp): " nil
498 query-replace-from-history-variable
))
499 (to (read-from-minibuffer
500 (format "Query replace %s with (space-separated strings): "
501 (query-replace-descr from
))
503 query-replace-to-history-variable from t
)))
505 (and current-prefix-arg
506 (prefix-numeric-value current-prefix-arg
))
507 (if (and transient-mark-mode mark-active
)
509 (if (and transient-mark-mode mark-active
)
512 (if (listp to-strings
)
513 (setq replacements to-strings
)
514 (while (/= (length to-strings
) 0)
515 (if (string-match " " to-strings
)
518 (list (substring to-strings
0
519 (string-match " " to-strings
))))
520 to-strings
(substring to-strings
521 (1+ (string-match " " to-strings
))))
522 (setq replacements
(append replacements
(list to-strings
))
524 (perform-replace regexp replacements t t nil n nil start end
)))
526 (defun replace-string (from-string to-string
&optional delimited start end backward
)
527 "Replace occurrences of FROM-STRING with TO-STRING.
528 Preserve case in each match if `case-replace' and `case-fold-search'
529 are non-nil and FROM-STRING has no uppercase letters.
530 \(Preserving case means that if the string matched is all caps, or capitalized,
531 then its replacement is upcased or capitalized.)
533 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
534 ignore hidden matches if `search-invisible' is nil, and ignore more
535 matches using `isearch-filter-predicate'.
537 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
538 to be replaced will match a sequence of whitespace chars defined by the
539 regexp in `search-whitespace-regexp'.
541 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
542 only matches surrounded by word boundaries. A negative prefix arg means
545 Operates on the region between START and END (if both are nil, from point
546 to the end of the buffer). Interactively, if Transient Mark mode is
547 enabled and the mark is active, operates on the contents of the region;
548 otherwise from point to the end of the buffer.
550 Use \\<minibuffer-local-map>\\[next-history-element] \
551 to pull the last incremental search string to the minibuffer
552 that reads FROM-STRING.
554 This function is usually the wrong thing to use in a Lisp program.
555 What you probably want is a loop like this:
556 (while (search-forward FROM-STRING nil t)
557 (replace-match TO-STRING nil t))
558 which will run faster and will not set the mark or print anything.
559 \(You may need a more complex loop if FROM-STRING can match the null string
560 and TO-STRING is also null.)"
561 (declare (interactive-only
562 "use `search-forward' and `replace-match' instead."))
565 (query-replace-read-args
567 (if current-prefix-arg
568 (if (eq current-prefix-arg
'-
) " backward" " word")
571 (if (and transient-mark-mode mark-active
) " in region" ""))
573 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
574 (if (and transient-mark-mode mark-active
)
576 (if (and transient-mark-mode mark-active
)
579 (perform-replace from-string to-string nil nil delimited nil nil start end backward
))
581 (defun replace-regexp (regexp to-string
&optional delimited start end backward
)
582 "Replace things after point matching REGEXP with TO-STRING.
583 Preserve case in each match if `case-replace' and `case-fold-search'
584 are non-nil and REGEXP has no uppercase letters.
586 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
587 ignore hidden matches if `search-invisible' is nil, and ignore more
588 matches using `isearch-filter-predicate'.
590 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
591 to be replaced will match a sequence of whitespace chars defined by the
592 regexp in `search-whitespace-regexp'.
594 In Transient Mark mode, if the mark is active, operate on the contents
595 of the region. Otherwise, operate from point to the end of the buffer.
597 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
598 only matches surrounded by word boundaries. A negative prefix arg means
601 Fourth and fifth arg START and END specify the region to operate on.
603 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
604 and `\\=\\N' (where N is a digit) stands for
605 whatever what matched the Nth `\\(...\\)' in REGEXP.
606 `\\?' lets you edit the replacement text in the minibuffer
607 at the given position for each replacement.
609 In interactive calls, the replacement text may contain `\\,'
610 followed by a Lisp expression used as part of the replacement
611 text. Inside of that expression, `\\&' is a string denoting the
612 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
613 numeric values from `string-to-number', and `\\#' itself for
614 `replace-count', the number of replacements occurred so far.
616 If your Lisp expression is an identifier and the next letter in
617 the replacement string would be interpreted as part of it, you
618 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
619 for this particular case you may also enter `\\#' in the
620 replacement text directly.
622 When using those Lisp features interactively in the replacement
623 text, TO-STRING is actually made a list instead of a string.
624 Use \\[repeat-complex-command] after this command for details.
626 Use \\<minibuffer-local-map>\\[next-history-element] \
627 to pull the last incremental search regexp to the minibuffer
630 This function is usually the wrong thing to use in a Lisp program.
631 What you probably want is a loop like this:
632 (while (re-search-forward REGEXP nil t)
633 (replace-match TO-STRING nil nil))
634 which will run faster and will not set the mark or print anything."
635 (declare (interactive-only
636 "use `re-search-forward' and `replace-match' instead."))
639 (query-replace-read-args
641 (if current-prefix-arg
642 (if (eq current-prefix-arg
'-
) " backward" " word")
645 (if (and transient-mark-mode mark-active
) " in region" ""))
647 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
648 (if (and transient-mark-mode mark-active
)
650 (if (and transient-mark-mode mark-active
)
653 (perform-replace regexp to-string nil t delimited nil nil start end backward
))
656 (defvar regexp-history nil
657 "History list for some commands that read regular expressions.
659 Maximum length of the history list is determined by the value
660 of `history-length', which see.")
662 (defvar occur-collect-regexp-history
'("\\1")
663 "History of regexp for occur's collect operation")
665 (defcustom read-regexp-defaults-function nil
666 "Function that provides default regexp(s) for `read-regexp'.
667 This function should take no arguments and return one of: nil, a
668 regexp, or a list of regexps. Interactively, `read-regexp' uses
669 the return value of this function for its DEFAULT argument.
671 As an example, set this variable to `find-tag-default-as-regexp'
672 to default to the symbol at point.
674 To provide different default regexps for different commands,
675 the function that you set this to can check `this-command'."
677 (const :tag
"No default regexp reading function" nil
)
678 (const :tag
"Latest regexp history" regexp-history-last
)
679 (function-item :tag
"Tag at point"
681 (function-item :tag
"Tag at point as regexp"
682 find-tag-default-as-regexp
)
683 (function-item :tag
"Tag at point as symbol regexp"
684 find-tag-default-as-symbol-regexp
)
685 (function :tag
"Your choice of function"))
689 (defun read-regexp-suggestions ()
690 "Return a list of standard suggestions for `read-regexp'.
691 By default, the list includes the tag at point, the last isearch regexp,
692 the last isearch string, and the last replacement regexp. `read-regexp'
693 appends the list returned by this function to the end of values available
694 via \\<minibuffer-local-map>\\[next-history-element]."
696 (find-tag-default-as-regexp)
697 (find-tag-default-as-symbol-regexp)
698 (car regexp-search-ring
)
699 (regexp-quote (or (car search-ring
) ""))
700 (car (symbol-value query-replace-from-history-variable
))))
702 (defun read-regexp (prompt &optional defaults history
)
703 "Read and return a regular expression as a string.
704 Prompt with the string PROMPT. If PROMPT ends in \":\" (followed by
705 optional whitespace), use it as-is. Otherwise, add \": \" to the end,
706 possibly preceded by the default result (see below).
708 The optional argument DEFAULTS can be either: nil, a string, a list
709 of strings, or a symbol. We use DEFAULTS to construct the default
710 return value in case of empty input.
712 If DEFAULTS is a string, we use it as-is.
714 If DEFAULTS is a list of strings, the first element is the
715 default return value, but all the elements are accessible
716 using the history command \\<minibuffer-local-map>\\[next-history-element].
718 If DEFAULTS is a non-nil symbol, then if `read-regexp-defaults-function'
719 is non-nil, we use that in place of DEFAULTS in the following:
720 If DEFAULTS is the symbol `regexp-history-last', we use the first
721 element of HISTORY (if specified) or `regexp-history'.
722 If DEFAULTS is a function, we call it with no arguments and use
723 what it returns, which should be either nil, a string, or a list of strings.
725 We append the standard values from `read-regexp-suggestions' to DEFAULTS
728 If the first element of DEFAULTS is non-nil (and if PROMPT does not end
729 in \":\", followed by optional whitespace), we add it to the prompt.
731 The optional argument HISTORY is a symbol to use for the history list.
732 If nil, uses `regexp-history'."
734 (if (and defaults
(symbolp defaults
))
736 ((eq (or read-regexp-defaults-function defaults
)
737 'regexp-history-last
)
738 (car (symbol-value (or history
'regexp-history
))))
739 ((functionp (or read-regexp-defaults-function defaults
))
740 (funcall (or read-regexp-defaults-function defaults
))))
742 (default (if (consp defaults
) (car defaults
) defaults
))
743 (suggestions (if (listp defaults
) defaults
(list defaults
)))
744 (suggestions (append suggestions
(read-regexp-suggestions)))
745 (suggestions (delete-dups (delq nil
(delete "" suggestions
))))
746 ;; Do not automatically add default to the history for empty input.
747 (history-add-new-input nil
)
748 (input (read-from-minibuffer
749 (cond ((string-match-p ":[ \t]*\\'" prompt
)
751 ((and default
(> (length default
) 0))
752 (format "%s (default %s): " prompt
753 (query-replace-descr default
)))
755 (format "%s: " prompt
)))
756 nil nil nil
(or history
'regexp-history
) suggestions t
)))
758 ;; Return the default value when the user enters empty input.
759 (prog1 (or default input
)
761 (add-to-history (or history
'regexp-history
) default
)))
762 ;; Otherwise, add non-empty input to the history and return input.
764 (add-to-history (or history
'regexp-history
) input
)))))
767 (defalias 'delete-non-matching-lines
'keep-lines
)
768 (defalias 'delete-matching-lines
'flush-lines
)
769 (defalias 'count-matches
'how-many
)
772 (defun keep-lines-read-args (prompt)
773 "Read arguments for `keep-lines' and friends.
774 Prompt for a regexp with PROMPT.
775 Value is a list, (REGEXP)."
776 (list (read-regexp prompt
) nil nil t
))
778 (defun keep-lines (regexp &optional rstart rend interactive
)
779 "Delete all lines except those containing matches for REGEXP.
780 A match split across lines preserves all the lines it lies in.
781 When called from Lisp (and usually interactively as well, see below)
782 applies to all lines starting after point.
784 If REGEXP contains upper case characters (excluding those preceded by `\\')
785 and `search-upper-case' is non-nil, the matching is case-sensitive.
787 Second and third arg RSTART and REND specify the region to operate on.
788 This command operates on (the accessible part of) all lines whose
789 accessible part is entirely contained in the region determined by RSTART
790 and REND. (A newline ending a line counts as part of that line.)
792 Interactively, in Transient Mark mode when the mark is active, operate
793 on all lines whose accessible part is entirely contained in the region.
794 Otherwise, the command applies to all lines starting after point.
795 When calling this function from Lisp, you can pretend that it was
796 called interactively by passing a non-nil INTERACTIVE argument.
798 This function starts looking for the next match from the end of
799 the previous match. Hence, it ignores matches that overlap
800 a previously found match."
804 (barf-if-buffer-read-only)
805 (keep-lines-read-args "Keep lines containing match for regexp")))
808 (goto-char (min rstart rend
))
812 (goto-char (max rstart rend
))
813 (unless (or (bolp) (eobp))
816 (if (and interactive transient-mark-mode mark-active
)
817 (setq rstart
(region-beginning)
819 (goto-char (region-end))
820 (unless (or (bolp) (eobp))
824 rend
(point-max-marker)))
827 (or (bolp) (forward-line 1))
828 (let ((start (point))
830 (if (and case-fold-search search-upper-case
)
831 (isearch-no-upper-case-p regexp t
)
833 (while (< (point) rend
)
834 ;; Start is first char not preserved by previous match.
835 (if (not (re-search-forward regexp rend
'move
))
836 (delete-region start rend
)
837 (let ((end (save-excursion (goto-char (match-beginning 0))
840 ;; Now end is first char preserved by the new match.
842 (delete-region start end
))))
844 (setq start
(save-excursion (forward-line 1) (point)))
845 ;; If the match was empty, avoid matching again at same place.
846 (and (< (point) rend
)
847 (= (match-beginning 0) (match-end 0))
849 (set-marker rend nil
)
853 (defun flush-lines (regexp &optional rstart rend interactive
)
854 "Delete lines containing matches for REGEXP.
855 When called from Lisp (and usually when called interactively as
856 well, see below), applies to the part of the buffer after point.
857 The line point is in is deleted if and only if it contains a
858 match for regexp starting after point.
860 If REGEXP contains upper case characters (excluding those preceded by `\\')
861 and `search-upper-case' is non-nil, the matching is case-sensitive.
863 Second and third arg RSTART and REND specify the region to operate on.
864 Lines partially contained in this region are deleted if and only if
865 they contain a match entirely contained in it.
867 Interactively, in Transient Mark mode when the mark is active, operate
868 on the contents of the region. Otherwise, operate from point to the
869 end of (the accessible portion of) the buffer. When calling this function
870 from Lisp, you can pretend that it was called interactively by passing
871 a non-nil INTERACTIVE argument.
873 If a match is split across lines, all the lines it lies in are deleted.
874 They are deleted _before_ looking for the next match. Hence, a match
875 starting on the same line at which another match ended is ignored."
879 (barf-if-buffer-read-only)
880 (keep-lines-read-args "Flush lines containing match for regexp")))
883 (goto-char (min rstart rend
))
884 (setq rend
(copy-marker (max rstart rend
))))
885 (if (and interactive transient-mark-mode mark-active
)
886 (setq rstart
(region-beginning)
887 rend
(copy-marker (region-end)))
889 rend
(point-max-marker)))
891 (let ((case-fold-search
892 (if (and case-fold-search search-upper-case
)
893 (isearch-no-upper-case-p regexp t
)
896 (while (and (< (point) rend
)
897 (re-search-forward regexp rend t
))
898 (delete-region (save-excursion (goto-char (match-beginning 0))
901 (progn (forward-line 1) (point))))))
902 (set-marker rend nil
)
906 (defun how-many (regexp &optional rstart rend interactive
)
907 "Print and return number of matches for REGEXP following point.
908 When called from Lisp and INTERACTIVE is omitted or nil, just return
909 the number, do not print it; if INTERACTIVE is t, the function behaves
910 in all respects as if it had been called interactively.
912 If REGEXP contains upper case characters (excluding those preceded by `\\')
913 and `search-upper-case' is non-nil, the matching is case-sensitive.
915 Second and third arg RSTART and REND specify the region to operate on.
917 Interactively, in Transient Mark mode when the mark is active, operate
918 on the contents of the region. Otherwise, operate from point to the
919 end of (the accessible portion of) the buffer.
921 This function starts looking for the next match from the end of
922 the previous match. Hence, it ignores matches that overlap
923 a previously found match."
926 (keep-lines-read-args "How many matches for regexp"))
931 (goto-char (min rstart rend
))
932 (setq rend
(max rstart rend
)))
934 (setq rend
(point-max)))
935 (if (and interactive transient-mark-mode mark-active
)
936 (setq rstart
(region-beginning)
944 (if (and case-fold-search search-upper-case
)
945 (isearch-no-upper-case-p regexp t
)
947 (while (and (< (point) rend
)
948 (progn (setq opoint
(point))
949 (re-search-forward regexp rend t
)))
950 (if (= opoint
(point))
952 (setq count
(1+ count
))))
953 (when interactive
(message "%d occurrence%s"
955 (if (= count
1) "" "s")))
959 (defvar occur-menu-map
960 (let ((map (make-sparse-keymap)))
961 (bindings--define-key map
[next-error-follow-minor-mode
]
962 '(menu-item "Auto Occurrence Display"
963 next-error-follow-minor-mode
964 :help
"Display another occurrence when moving the cursor"
965 :button
(:toggle .
(and (boundp 'next-error-follow-minor-mode
)
966 next-error-follow-minor-mode
))))
967 (bindings--define-key map
[separator-1
] menu-bar-separator
)
968 (bindings--define-key map
[kill-this-buffer
]
969 '(menu-item "Kill Occur Buffer" kill-this-buffer
970 :help
"Kill the current *Occur* buffer"))
971 (bindings--define-key map
[quit-window
]
972 '(menu-item "Quit Occur Window" quit-window
973 :help
"Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
974 (bindings--define-key map
[revert-buffer
]
975 '(menu-item "Revert Occur Buffer" revert-buffer
976 :help
"Replace the text in the *Occur* buffer with the results of rerunning occur"))
977 (bindings--define-key map
[clone-buffer
]
978 '(menu-item "Clone Occur Buffer" clone-buffer
979 :help
"Create and return a twin copy of the current *Occur* buffer"))
980 (bindings--define-key map
[occur-rename-buffer
]
981 '(menu-item "Rename Occur Buffer" occur-rename-buffer
982 :help
"Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
983 (bindings--define-key map
[occur-edit-buffer
]
984 '(menu-item "Edit Occur Buffer" occur-edit-mode
985 :help
"Edit the *Occur* buffer and apply changes to the original buffers."))
986 (bindings--define-key map
[separator-2
] menu-bar-separator
)
987 (bindings--define-key map
[occur-mode-goto-occurrence-other-window
]
988 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
989 :help
"Go to the occurrence the current line describes, in another window"))
990 (bindings--define-key map
[occur-mode-goto-occurrence
]
991 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
992 :help
"Go to the occurrence the current line describes"))
993 (bindings--define-key map
[occur-mode-display-occurrence
]
994 '(menu-item "Display Occurrence" occur-mode-display-occurrence
995 :help
"Display in another window the occurrence the current line describes"))
996 (bindings--define-key map
[occur-next
]
997 '(menu-item "Move to Next Match" occur-next
998 :help
"Move to the Nth (default 1) next match in an Occur mode buffer"))
999 (bindings--define-key map
[occur-prev
]
1000 '(menu-item "Move to Previous Match" occur-prev
1001 :help
"Move to the Nth (default 1) previous match in an Occur mode buffer"))
1003 "Menu keymap for `occur-mode'.")
1005 (defvar occur-mode-map
1006 (let ((map (make-sparse-keymap)))
1007 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
1008 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
1009 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
1010 (define-key map
"e" 'occur-edit-mode
)
1011 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
1012 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
1013 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
1014 (define-key map
"\M-n" 'occur-next
)
1015 (define-key map
"\M-p" 'occur-prev
)
1016 (define-key map
"r" 'occur-rename-buffer
)
1017 (define-key map
"c" 'clone-buffer
)
1018 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
1019 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
1021 "Keymap for `occur-mode'.")
1023 (defvar occur-revert-arguments nil
1024 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
1025 See `occur-revert-function'.")
1026 (make-variable-buffer-local 'occur-revert-arguments
)
1027 (put 'occur-revert-arguments
'permanent-local t
)
1029 (defcustom occur-mode-hook
'(turn-on-font-lock)
1030 "Hook run when entering Occur mode."
1034 (defcustom occur-hook nil
1035 "Hook run by Occur when there are any matches."
1039 (defcustom occur-mode-find-occurrence-hook nil
1040 "Hook run by Occur after locating an occurrence.
1041 This will be called with the cursor position at the occurrence. An application
1042 for this is to reveal context in an outline-mode when the occurrence is hidden."
1046 (put 'occur-mode
'mode-class
'special
)
1047 (define-derived-mode occur-mode special-mode
"Occur"
1048 "Major mode for output from \\[occur].
1049 \\<occur-mode-map>Move point to one of the items in this buffer, then use
1050 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
1051 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
1054 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
1055 (setq next-error-function
'occur-next-error
))
1060 (defvar occur-edit-mode-map
1061 (let ((map (make-sparse-keymap)))
1062 (set-keymap-parent map text-mode-map
)
1063 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
1064 (define-key map
"\C-c\C-c" 'occur-cease-edit
)
1065 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
1066 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
1067 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
1069 "Keymap for `occur-edit-mode'.")
1071 (define-derived-mode occur-edit-mode occur-mode
"Occur-Edit"
1072 "Major mode for editing *Occur* buffers.
1073 In this mode, changes to the *Occur* buffer are also applied to
1074 the originating buffer.
1076 To return to ordinary Occur mode, use \\[occur-cease-edit]."
1077 (setq buffer-read-only nil
)
1078 (add-hook 'after-change-functions
'occur-after-change-function nil t
)
1079 (message (substitute-command-keys
1080 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
1082 (defun occur-cease-edit ()
1083 "Switch from Occur Edit mode to Occur mode."
1085 (when (derived-mode-p 'occur-edit-mode
)
1087 (message "Switching to Occur mode.")))
1089 (defun occur-after-change-function (beg end length
)
1092 (let* ((line-beg (line-beginning-position))
1093 (m (get-text-property line-beg
'occur-target
))
1094 (buf (marker-buffer m
))
1096 (when (and (get-text-property line-beg
'occur-prefix
)
1097 (not (get-text-property end
'occur-prefix
)))
1099 ;; Apply occur-target property to inserted (e.g. yanked) text.
1100 (put-text-property beg end
'occur-target m
)
1101 ;; Did we insert a newline? Occur Edit mode can't create new
1102 ;; Occur entries; just discard everything after the newline.
1104 (and (search-forward "\n" end t
)
1105 (delete-region (1- (point)) end
))))
1106 (let* ((line (- (line-number-at-pos)
1107 (line-number-at-pos (window-start))))
1108 (readonly (with-current-buffer buf buffer-read-only
))
1109 (win (or (get-buffer-window buf
)
1111 '(nil (inhibit-same-window . t
)
1112 (inhibit-switch-frame . t
)))))
1113 (line-end (line-end-position))
1114 (text (save-excursion
1115 (goto-char (next-single-property-change
1116 line-beg
'occur-prefix nil
1118 (setq col
(- (point) line-beg
))
1119 (buffer-substring-no-properties (point) line-end
))))
1120 (with-selected-window win
1124 (message "Buffer `%s' is read only." buf
)
1125 (delete-region (line-beginning-position) (line-end-position))
1127 (move-to-column col
)))))))
1130 (defun occur-revert-function (_ignore1 _ignore2
)
1131 "Handle `revert-buffer' for Occur mode buffers."
1132 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
1134 (defun occur-mode-find-occurrence ()
1135 (let ((pos (get-text-property (point) 'occur-target
)))
1137 (error "No occurrence on this line"))
1138 (unless (buffer-live-p (marker-buffer pos
))
1139 (error "Buffer for this occurrence was killed"))
1142 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
1143 (defun occur-mode-goto-occurrence (&optional event
)
1144 "Go to the occurrence on the current line."
1145 (interactive (list last-nonmenu-event
))
1148 ;; Actually `event-end' works correctly with a nil argument as
1149 ;; well, so we could dispense with this test, but let's not
1150 ;; rely on this undocumented behavior.
1151 (occur-mode-find-occurrence)
1152 (with-current-buffer (window-buffer (posn-window (event-end event
)))
1154 (goto-char (posn-point (event-end event
)))
1155 (occur-mode-find-occurrence))))))
1156 (pop-to-buffer (marker-buffer pos
))
1158 (run-hooks 'occur-mode-find-occurrence-hook
)))
1160 (defun occur-mode-goto-occurrence-other-window ()
1161 "Go to the occurrence the current line describes, in another window."
1163 (let ((pos (occur-mode-find-occurrence)))
1164 (switch-to-buffer-other-window (marker-buffer pos
))
1166 (run-hooks 'occur-mode-find-occurrence-hook
)))
1168 (defun occur-mode-display-occurrence ()
1169 "Display in another window the occurrence the current line describes."
1171 (let ((pos (occur-mode-find-occurrence))
1173 (setq window
(display-buffer (marker-buffer pos
) t
))
1174 ;; This is the way to set point in the proper window.
1175 (save-selected-window
1176 (select-window window
)
1178 (run-hooks 'occur-mode-find-occurrence-hook
))))
1180 (defun occur-find-match (n search message
)
1181 (if (not n
) (setq n
1))
1184 (setq r
(funcall search
(point) 'occur-match
))
1186 (get-text-property r
'occur-match
)
1187 (setq r
(funcall search r
'occur-match
)))
1193 (defun occur-next (&optional n
)
1194 "Move to the Nth (default 1) next match in an Occur mode buffer."
1196 (occur-find-match n
#'next-single-property-change
"No more matches"))
1198 (defun occur-prev (&optional n
)
1199 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1201 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
1203 (defun occur-next-error (&optional argp reset
)
1204 "Move to the Nth (default 1) next match in an Occur mode buffer.
1205 Compatibility function for \\[next-error] invocations."
1207 ;; we need to run occur-find-match from within the Occur buffer
1208 (with-current-buffer
1209 ;; Choose the buffer and make it current.
1210 (if (next-error-buffer-p (current-buffer))
1212 (next-error-find-buffer nil nil
1214 (eq major-mode
'occur-mode
))))
1216 (goto-char (cond (reset (point-min))
1217 ((< argp
0) (line-beginning-position))
1218 ((> argp
0) (line-end-position))
1223 #'previous-single-property-change
1224 #'next-single-property-change
)
1226 ;; In case the *Occur* buffer is visible in a nonselected window.
1227 (let ((win (get-buffer-window (current-buffer) t
)))
1228 (if win
(set-window-point win
(point))))
1229 (occur-mode-goto-occurrence)))
1232 '((((class color
) (min-colors 88) (background light
))
1233 :background
"yellow1")
1234 (((class color
) (min-colors 88) (background dark
))
1235 :background
"RoyalBlue3")
1236 (((class color
) (min-colors 8) (background light
))
1237 :background
"yellow" :foreground
"black")
1238 (((class color
) (min-colors 8) (background dark
))
1239 :background
"blue" :foreground
"white")
1240 (((type tty
) (class mono
))
1242 (t :background
"gray"))
1243 "Face used to highlight matches permanently."
1247 (defcustom list-matching-lines-default-context-lines
0
1248 "Default number of context lines included around `list-matching-lines' matches.
1249 A negative number means to include that many lines before the match.
1250 A positive number means to include that many lines both before and after."
1254 (defalias 'list-matching-lines
'occur
)
1256 (defcustom list-matching-lines-face
'match
1257 "Face used by \\[list-matching-lines] to show the text that matches.
1258 If the value is nil, don't highlight the matching portions specially."
1262 (defcustom list-matching-lines-buffer-name-face
'underline
1263 "Face used by \\[list-matching-lines] to show the names of buffers.
1264 If the value is nil, don't highlight the buffer names specially."
1268 (defcustom list-matching-lines-prefix-face
'shadow
1269 "Face used by \\[list-matching-lines] to show the prefix column.
1270 If the face doesn't differ from the default face,
1271 don't highlight the prefix with line numbers specially."
1276 (defcustom occur-excluded-properties
1277 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1278 yank-handler follow-link
)
1279 "Text properties to discard when copying lines to the *Occur* buffer.
1280 The value should be a list of text properties to discard or t,
1281 which means to discard all text properties."
1282 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
1286 (defun occur-read-primary-args ()
1287 (let* ((perform-collect (consp current-prefix-arg
))
1288 (regexp (read-regexp (if perform-collect
1289 "Collect strings matching regexp"
1290 "List lines matching regexp")
1291 'regexp-history-last
)))
1294 ;; Perform collect operation
1295 (if (zerop (regexp-opt-depth regexp
))
1296 ;; No subexpression so collect the entire match.
1298 ;; Get the regexp for collection pattern.
1299 (let ((default (car occur-collect-regexp-history
)))
1301 (format "Regexp to collect (default %s): " default
)
1302 default
'occur-collect-regexp-history
)))
1303 ;; Otherwise normal occur takes numerical prefix argument.
1304 (when current-prefix-arg
1305 (prefix-numeric-value current-prefix-arg
))))))
1307 (defun occur-rename-buffer (&optional unique-p interactive-p
)
1308 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1309 Here `original-buffer-name' is the buffer name where Occur was originally run.
1310 When given the prefix argument, or called non-interactively, the renaming
1311 will not clobber the existing buffer(s) of that name, but use
1312 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1313 if you always want a separate *Occur* buffer for each buffer where you
1315 (interactive "P\np")
1316 (with-current-buffer
1317 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
1318 (rename-buffer (concat "*Occur: "
1319 (mapconcat #'buffer-name
1320 (car (cddr occur-revert-arguments
)) "/")
1322 (or unique-p
(not interactive-p
)))))
1324 (defun occur (regexp &optional nlines
)
1325 "Show all lines in the current buffer containing a match for REGEXP.
1326 If a match spreads across multiple lines, all those lines are shown.
1328 Each line is displayed with NLINES lines before and after, or -NLINES
1329 before if NLINES is negative.
1330 NLINES defaults to `list-matching-lines-default-context-lines'.
1331 Interactively it is the prefix arg.
1333 The lines are shown in a buffer named `*Occur*'.
1334 It serves as a menu to find any of the occurrences in this buffer.
1335 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1337 If REGEXP contains upper case characters (excluding those preceded by `\\')
1338 and `search-upper-case' is non-nil, the matching is case-sensitive.
1340 When NLINES is a string or when the function is called
1341 interactively with prefix argument without a number (`C-u' alone
1342 as prefix) the matching strings are collected into the `*Occur*'
1343 buffer by using NLINES as a replacement regexp. NLINES may
1344 contain \\& and \\N which convention follows `replace-match'.
1345 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1346 \"\\1\" for NLINES collects all the function names in a lisp
1347 program. When there is no parenthesized subexpressions in REGEXP
1348 the entire match is collected. In any case the searched buffer
1350 (interactive (occur-read-primary-args))
1351 (occur-1 regexp nlines
(list (current-buffer))))
1353 (defvar ido-ignore-item-temp-list
)
1355 (defun multi-occur (bufs regexp
&optional nlines
)
1356 "Show all lines in buffers BUFS containing a match for REGEXP.
1357 This function acts on multiple buffers; otherwise, it is exactly like
1358 `occur'. When you invoke this command interactively, you must specify
1359 the buffer names that you want, one by one.
1360 See also `multi-occur-in-matching-buffers'."
1363 (let* ((bufs (list (read-buffer "First buffer to search: "
1364 (current-buffer) t
)))
1366 (ido-ignore-item-temp-list bufs
))
1367 (while (not (string-equal
1368 (setq buf
(read-buffer
1369 (if (eq read-buffer-function
'ido-read-buffer
)
1370 "Next buffer to search (C-j to end): "
1371 "Next buffer to search (RET to end): ")
1374 (add-to-list 'bufs buf
)
1375 (setq ido-ignore-item-temp-list bufs
))
1376 (nreverse (mapcar #'get-buffer bufs
)))
1377 (occur-read-primary-args)))
1378 (occur-1 regexp nlines bufs
))
1380 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1381 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1382 Normally BUFREGEXP matches against each buffer's visited file name,
1383 but if you specify a prefix argument, it matches against the buffer name.
1384 See also `multi-occur'."
1387 (let* ((default (car regexp-history
))
1390 (if current-prefix-arg
1391 "List lines in buffers whose names match regexp: "
1392 "List lines in buffers whose filenames match regexp: "))))
1393 (if (equal input
"")
1396 (occur-read-primary-args)))
1400 (mapcar (lambda (buf)
1402 (string-match bufregexp
1404 (and (buffer-file-name buf
)
1405 (string-match bufregexp
1406 (buffer-file-name buf
))))
1410 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1411 (unless (and regexp
(not (equal regexp
"")))
1412 (error "Occur doesn't work with the empty regexp"))
1414 (setq buf-name
"*Occur*"))
1416 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1417 (when (buffer-live-p buf
) buf
))
1419 ;; Handle the case where one of the buffers we're searching is the
1420 ;; output buffer. Just rename it.
1421 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1422 (with-current-buffer (get-buffer buf-name
)
1425 ;; Now find or create the output buffer.
1426 ;; If we just renamed that buffer, we will make a new one here.
1427 (setq occur-buf
(get-buffer-create buf-name
))
1429 (with-current-buffer occur-buf
1430 (if (stringp nlines
)
1431 (fundamental-mode) ;; This is for collect operation.
1433 (let ((inhibit-read-only t
)
1434 ;; Don't generate undo entries for creation of the initial contents.
1435 (buffer-undo-list t
))
1438 (if (stringp nlines
)
1439 ;; Treat nlines as a regexp to collect.
1440 (let ((bufs active-bufs
)
1443 (with-current-buffer (car bufs
)
1445 (goto-char (point-min))
1446 (while (re-search-forward regexp nil t
)
1447 ;; Insert the replacement regexp.
1448 (let ((str (match-substitute-replacement nlines
)))
1450 (with-current-buffer occur-buf
1452 (setq count
(1+ count
))
1453 (or (zerop (current-column))
1454 (insert "\n"))))))))
1455 (setq bufs
(cdr bufs
)))
1457 ;; Perform normal occur.
1459 regexp active-bufs occur-buf
1460 (or nlines list-matching-lines-default-context-lines
)
1461 (if (and case-fold-search search-upper-case
)
1462 (isearch-no-upper-case-p regexp t
)
1464 list-matching-lines-buffer-name-face
1465 (if (face-differs-from-default-p list-matching-lines-prefix-face
)
1466 list-matching-lines-prefix-face
)
1467 list-matching-lines-face
1468 (not (eq occur-excluded-properties t
))))))
1469 (let* ((bufcount (length active-bufs
))
1470 (diff (- (length bufs
) bufcount
)))
1471 (message "Searched %d buffer%s%s; %s match%s%s"
1472 bufcount
(if (= bufcount
1) "" "s")
1473 (if (zerop diff
) "" (format " (%d killed)" diff
))
1474 (if (zerop count
) "no" (format "%d" count
))
1475 (if (= count
1) "" "es")
1476 ;; Don't display regexp if with remaining text
1477 ;; it is longer than window-width.
1478 (if (> (+ (length regexp
) 42) (window-width))
1479 "" (format " for `%s'" (query-replace-descr regexp
)))))
1480 (setq occur-revert-arguments
(list regexp nlines bufs
))
1482 (kill-buffer occur-buf
)
1483 (display-buffer occur-buf
)
1484 (setq next-error-last-buffer occur-buf
)
1485 (setq buffer-read-only t
)
1486 (set-buffer-modified-p nil
)
1487 (run-hooks 'occur-hook
)))))))
1489 (defun occur-engine (regexp buffers out-buf nlines case-fold
1490 title-face prefix-face match-face keep-props
)
1491 (with-current-buffer out-buf
1492 (let ((global-lines 0) ;; total count of matching lines
1493 (global-matches 0) ;; total count of matches
1495 (case-fold-search case-fold
))
1496 ;; Map over all the buffers
1497 (dolist (buf buffers
)
1498 (when (buffer-live-p buf
)
1499 (let ((lines 0) ;; count of matching lines
1500 (matches 0) ;; count of matches
1501 (curr-line 1) ;; line count
1502 (prev-line nil
) ;; line number of prev match endpt
1503 (prev-after-lines nil
) ;; context lines of prev match
1511 (inhibit-field-text-motion t
)
1512 (headerpt (with-current-buffer out-buf
(point))))
1513 (with-current-buffer buf
1515 ;; Set CODING only if the current buffer locally
1516 ;; binds buffer-file-coding-system.
1517 (not (local-variable-p 'buffer-file-coding-system
))
1518 (setq coding buffer-file-coding-system
))
1520 (goto-char (point-min)) ;; begin searching in the buffer
1522 (setq origpt
(point))
1523 (when (setq endpt
(re-search-forward regexp nil t
))
1524 (setq lines
(1+ lines
)) ;; increment matching lines count
1525 (setq matchbeg
(match-beginning 0))
1526 ;; Get beginning of first match line and end of the last.
1528 (goto-char matchbeg
)
1529 (setq begpt
(line-beginning-position))
1531 (setq endpt
(line-end-position)))
1532 ;; Sum line numbers up to the first match line.
1533 (setq curr-line
(+ curr-line
(count-lines origpt begpt
)))
1534 (setq marker
(make-marker))
1535 (set-marker marker matchbeg
)
1536 (setq curstring
(occur-engine-line begpt endpt keep-props
))
1537 ;; Highlight the matches
1538 (let ((len (length curstring
))
1540 (while (and (< start len
)
1541 (string-match regexp curstring start
))
1542 (setq matches
(1+ matches
))
1543 (add-text-properties
1544 (match-beginning 0) (match-end 0)
1545 '(occur-match t
) curstring
)
1547 ;; Add `match-face' to faces copied from the buffer.
1548 (add-face-text-property
1549 (match-beginning 0) (match-end 0)
1550 match-face nil curstring
))
1551 ;; Avoid infloop (Bug#7593).
1552 (let ((end (match-end 0)))
1553 (setq start
(if (= start end
) (1+ start
) end
)))))
1554 ;; Generate the string to insert for this match
1555 (let* ((match-prefix
1556 ;; Using 7 digits aligns tabs properly.
1557 (apply #'propertize
(format "%7d:" curr-line
)
1560 `(font-lock-face ,prefix-face
))
1561 `(occur-prefix t mouse-face
(highlight)
1562 ;; Allow insertion of text at
1563 ;; the end of the prefix (for
1564 ;; Occur Edit mode).
1565 front-sticky t rear-nonsticky t
1566 occur-target
,marker follow-link t
1567 help-echo
"mouse-2: go to this occurrence"))))
1569 ;; We don't put `mouse-face' on the newline,
1570 ;; because that loses. And don't put it
1571 ;; on context lines to reduce flicker.
1572 (propertize curstring
'mouse-face
(list 'highlight
)
1573 'occur-target marker
1576 "mouse-2: go to this occurrence"))
1580 ;; Add non-numeric prefix to all non-first lines
1581 ;; of multi-line matches.
1582 (replace-regexp-in-string
1585 (propertize "\n :" 'font-lock-face prefix-face
)
1588 ;; Add marker at eol, but no mouse props.
1589 (propertize "\n" 'occur-target marker
)))
1592 ;; The simple display style
1594 ;; The complex multi-line display style.
1595 (setq ret
(occur-context-lines
1596 out-line nlines keep-props begpt endpt
1597 curr-line prev-line prev-after-lines
1599 ;; Set first elem of the returned list to `data',
1600 ;; and the second elem to `prev-after-lines'.
1601 (setq prev-after-lines
(nth 1 ret
))
1603 ;; Actually insert the match display data
1604 (with-current-buffer out-buf
1609 ;; Sum line numbers between first and last match lines.
1610 (setq curr-line
(+ curr-line
(count-lines begpt endpt
)
1611 ;; Add 1 for empty last match line since
1612 ;; count-lines returns 1 line less.
1613 (if (and (bolp) (eolp)) 1 0)))
1614 ;; On to the next match...
1616 (goto-char (point-max)))
1617 (setq prev-line
(1- curr-line
)))
1618 ;; Flush remaining context after-lines.
1619 (when prev-after-lines
1620 (with-current-buffer out-buf
1621 (insert (apply #'concat
(occur-engine-add-prefix
1622 prev-after-lines prefix-face
)))))))
1623 (when (not (zerop lines
)) ;; is the count zero?
1624 (setq global-lines
(+ global-lines lines
)
1625 global-matches
(+ global-matches matches
))
1626 (with-current-buffer out-buf
1627 (goto-char headerpt
)
1631 (format "%d match%s%s%s in buffer: %s\n"
1632 matches
(if (= matches
1) "" "es")
1633 ;; Don't display the same number of lines
1634 ;; and matches in case of 1 match per line.
1635 (if (= lines matches
)
1636 "" (format " in %d line%s"
1637 lines
(if (= lines
1) "" "s")))
1638 ;; Don't display regexp for multi-buffer.
1639 (if (> (length buffers
) 1)
1640 "" (format " for \"%s\""
1641 (query-replace-descr regexp
)))
1645 (add-text-properties beg end
`(occur-title ,buf
))
1647 (add-face-text-property beg end title-face
)))
1648 (goto-char (point-min)))))))
1649 ;; Display total match count and regexp for multi-buffer.
1650 (when (and (not (zerop global-lines
)) (> (length buffers
) 1))
1651 (goto-char (point-min))
1654 (insert (format "%d match%s%s total for \"%s\":\n"
1655 global-matches
(if (= global-matches
1) "" "es")
1656 ;; Don't display the same number of lines
1657 ;; and matches in case of 1 match per line.
1658 (if (= global-lines global-matches
)
1659 "" (format " in %d line%s"
1660 global-lines
(if (= global-lines
1) "" "s")))
1661 (query-replace-descr regexp
)))
1664 (add-face-text-property beg end title-face
)))
1665 (goto-char (point-min)))
1667 ;; CODING is buffer-file-coding-system of the first buffer
1668 ;; that locally binds it. Let's use it also for the output
1670 (set-buffer-file-coding-system coding
))
1671 ;; Return the number of matches
1674 (defun occur-engine-line (beg end
&optional keep-props
)
1675 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
1676 (text-property-not-all beg end
'fontified t
))
1677 (if (fboundp 'jit-lock-fontify-now
)
1678 (jit-lock-fontify-now beg end
)))
1679 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1680 (let ((str (buffer-substring beg end
)))
1681 (remove-list-of-text-properties
1682 0 (length str
) occur-excluded-properties str
)
1684 (buffer-substring-no-properties beg end
)))
1686 (defun occur-engine-add-prefix (lines &optional prefix-face
)
1689 (concat (if prefix-face
1690 (propertize " :" 'font-lock-face prefix-face
)
1695 (defun occur-accumulate-lines (count &optional keep-props pt
)
1699 (let ((forwardp (> count
0))
1700 result beg end moved
)
1701 (while (not (or (zerop count
)
1704 (and (bobp) (not moved
)))))
1705 (setq count
(+ count
(if forwardp -
1 1)))
1706 (setq beg
(line-beginning-position)
1707 end
(line-end-position))
1708 (push (occur-engine-line beg end keep-props
) result
)
1709 (setq moved
(= 0 (forward-line (if forwardp
1 -
1)))))
1710 (nreverse result
))))
1712 ;; Generate context display for occur.
1713 ;; OUT-LINE is the line where the match is.
1714 ;; NLINES and KEEP-PROPS are args to occur-engine.
1715 ;; CURR-LINE is line count of the current match,
1716 ;; PREV-LINE is line count of the previous match,
1717 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1718 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1719 ;; then concatenate them all together.
1720 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1721 curr-line prev-line prev-after-lines
1722 &optional prefix-face
)
1723 ;; Find after- and before-context lines of the current match.
1725 (nreverse (cdr (occur-accumulate-lines
1726 (- (1+ (abs nlines
))) keep-props begpt
))))
1728 (cdr (occur-accumulate-lines
1729 (1+ nlines
) keep-props endpt
)))
1732 ;; Combine after-lines of the previous match
1733 ;; with before-lines of the current match.
1735 (when prev-after-lines
1736 ;; Don't overlap prev after-lines with current before-lines.
1737 (if (>= (+ prev-line
(length prev-after-lines
))
1738 (- curr-line
(length before-lines
)))
1739 (setq prev-after-lines
1740 (butlast prev-after-lines
1741 (- (length prev-after-lines
)
1742 (- curr-line prev-line
(length before-lines
) 1))))
1743 ;; Separate non-overlapping context lines with a dashed line.
1744 (setq separator
"-------\n")))
1747 ;; Don't overlap current before-lines with previous match line.
1748 (if (<= (- curr-line
(length before-lines
))
1751 (nthcdr (- (length before-lines
)
1752 (- curr-line prev-line
1))
1754 ;; Separate non-overlapping before-context lines.
1755 (unless (> nlines
0)
1756 (setq separator
"-------\n"))))
1759 ;; Return a list where the first element is the output line.
1762 (if prev-after-lines
1763 (occur-engine-add-prefix prev-after-lines prefix-face
))
1765 (list (if prefix-face
1766 (propertize separator
'font-lock-face prefix-face
)
1768 (occur-engine-add-prefix before-lines prefix-face
)
1770 ;; And the second element is the list of context after-lines.
1771 (if (> nlines
0) after-lines
))))
1774 ;; It would be nice to use \\[...], but there is no reasonable way
1775 ;; to make that display both SPC and Y.
1776 (defconst query-replace-help
1777 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1778 RET or `q' to exit, Period to replace one match and exit,
1779 Comma to replace but not move point immediately,
1780 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1781 C-w to delete match and recursive edit,
1782 C-l to clear the screen, redisplay, and offer same replacement again,
1783 ! to replace all remaining matches in this buffer with no more questions,
1784 ^ to move point back to previous match,
1785 E to edit the replacement string.
1786 In multi-buffer replacements type `Y' to replace all remaining
1787 matches in all remaining buffers with no more questions,
1788 `N' to skip to the next buffer without replacing remaining matches
1789 in the current buffer."
1790 "Help message while in `query-replace'.")
1792 (defvar query-replace-map
1793 (let ((map (make-sparse-keymap)))
1794 (define-key map
" " 'act
)
1795 (define-key map
"\d" 'skip
)
1796 (define-key map
[delete] 'skip)
1797 (define-key map [backspace] 'skip)
1798 (define-key map "y" 'act)
1799 (define-key map "n" 'skip)
1800 (define-key map "Y" 'act)
1801 (define-key map "N" 'skip)
1802 (define-key map "e" 'edit-replacement)
1803 (define-key map "E" 'edit-replacement)
1804 (define-key map "," 'act-and-show)
1805 (define-key map "q" 'exit)
1806 (define-key map "\r" 'exit)
1807 (define-key map [return] 'exit)
1808 (define-key map "." 'act-and-exit)
1809 (define-key map "\C-r" 'edit)
1810 (define-key map "\C-w" 'delete-and-edit)
1811 (define-key map "\C-l" 'recenter)
1812 (define-key map "!" 'automatic)
1813 (define-key map "^" 'backup)
1814 (define-key map "\C-h" 'help)
1815 (define-key map [f1] 'help)
1816 (define-key map [help] 'help)
1817 (define-key map "?" 'help)
1818 (define-key map "\C-g" 'quit)
1819 (define-key map "\C-]" 'quit)
1820 (define-key map "\C-v" 'scroll-up)
1821 (define-key map "\M-v" 'scroll-down)
1822 (define-key map [next] 'scroll-up)
1823 (define-key map [prior] 'scroll-down)
1824 (define-key map [?\C-\M-v] 'scroll-other-window)
1825 (define-key map [M-next] 'scroll-other-window)
1826 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1827 (define-key map [M-prior] 'scroll-other-window-down)
1828 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1829 ;; should check for ESC specially.
1830 ;; (define-key map "\e" 'exit-prefix)
1831 (define-key map [escape] 'exit-prefix)
1833 "Keymap of responses to questions posed by commands like `query-replace'.
1834 The \"bindings\" in this map are not commands; they are answers.
1835 The valid answers include `act', `skip', `act-and-show',
1836 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1837 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1838 `edit', `edit-replacement', `delete-and-edit', `automatic',
1839 `backup', `quit', and `help'.
1841 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1843 (defvar multi-query-replace-map
1844 (let ((map (make-sparse-keymap)))
1845 (set-keymap-parent map query-replace-map)
1846 (define-key map "Y" 'automatic-all)
1847 (define-key map "N" 'exit-current)
1849 "Keymap that defines additional bindings for multi-buffer replacements.
1850 It extends its parent map `query-replace-map' with new bindings to
1851 operate on a set of buffers/files. The difference with its parent map
1852 is the additional answers `automatic-all' to replace all remaining
1853 matches in all remaining buffers with no more questions, and
1854 `exit-current' to skip remaining matches in the current buffer
1855 and to continue with the next buffer in the sequence.")
1857 (defun replace-match-string-symbols (n)
1858 "Process a list (and any sub-lists), expanding certain symbols.
1860 N (match-string N) (where N is a string of digits)
1861 #N (string-to-number (match-string N))
1863 #& (string-to-number (match-string 0))
1866 Note that these symbols must be preceded by a backslash in order to
1867 type them using Lisp syntax."
1871 (replace-match-string-symbols (car n))) ;Process sub-list
1873 (let ((name (symbol-name (car n))))
1875 ((string-match "^[0-9]+$" name)
1876 (setcar n (list 'match-string (string-to-number name))))
1877 ((string-match "^#[0-9]+$" name)
1878 (setcar n (list 'string-to-number
1880 (string-to-number (substring name 1))))))
1882 (setcar n '(match-string 0)))
1883 ((string= "#&" name)
1884 (setcar n '(string-to-number (match-string 0))))
1886 (setcar n 'replace-count))))))
1889 (defun replace-eval-replacement (expression count)
1890 (let* ((replace-count count)
1896 (error "Error evaluating replacement expression: %S" err)))))
1897 (if (stringp replacement)
1899 (prin1-to-string replacement t))))
1901 (defun replace-quote (replacement)
1902 "Quote a replacement string.
1903 This just doubles all backslashes in REPLACEMENT and
1904 returns the resulting string. If REPLACEMENT is not
1905 a string, it is first passed through `prin1-to-string'
1906 with the `noescape' argument set.
1908 `match-data' is preserved across the call."
1910 (replace-regexp-in-string "\\\\" "\\\\"
1911 (if (stringp replacement)
1913 (prin1-to-string replacement t))
1916 (defun replace-loop-through-replacements (data count)
1917 ;; DATA is a vector containing the following values:
1918 ;; 0 next-rotate-count
1920 ;; 2 next-replacement
1922 (if (= (aref data 0) count)
1924 (aset data 0 (+ count (aref data 1)))
1925 (let ((next (cdr (aref data 2))))
1926 (aset data 2 (if (consp next) next (aref data 3))))))
1927 (car (aref data 2)))
1929 (defun replace-match-data (integers reuse &optional new)
1930 "Like `match-data', but markers in REUSE get invalidated.
1931 If NEW is non-nil, it is set and returned instead of fresh data,
1932 but coerced to the correct value of INTEGERS."
1935 (set-match-data new)
1937 (eq (null integers) (markerp (car reuse)))
1939 (match-data integers reuse t)))
1941 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data backward)
1942 "Make a replacement with `replace-match', editing `\\?'.
1943 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
1944 After possibly editing it (if `\\?' is present), NEWTEXT is also
1945 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
1946 is made (to save time). MATCH-DATA is used for the replacement.
1947 In case editing is done, it is changed to use markers.
1949 The return value is non-nil if there has been no `\\?' or NOEDIT was
1950 passed in. If LITERAL is set, no checking is done, anyway."
1951 (unless (or literal noedit)
1953 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1956 (read-string "Edit replacement string: "
1959 (replace-match "" t t newtext 3)
1960 (1+ (match-beginning 3)))
1963 nil match-data match-data))))
1965 (set-match-data match-data)
1966 (replace-match newtext fixedcase literal)
1967 ;; `replace-match' leaves point at the end of the replacement text,
1968 ;; so move point to the beginning when replacing backward.
1969 (when backward (goto-char (nth 0 match-data)))
1972 (defvar replace-search-function nil
1973 "Function to use when searching for strings to replace.
1974 It is used by `query-replace' and `replace-string', and is called
1975 with three arguments, as if it were `search-forward'.")
1977 (defvar replace-re-search-function nil
1978 "Function to use when searching for regexps to replace.
1979 It is used by `query-replace-regexp', `replace-regexp',
1980 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1981 It is called with three arguments, as if it were
1982 `re-search-forward'.")
1984 (defun replace-search (search-string limit regexp-flag delimited-flag
1985 case-fold-search backward)
1986 "Search for the next occurrence of SEARCH-STRING to replace."
1987 ;; Let-bind global isearch-* variables to values used
1988 ;; to search the next replacement. These let-bindings
1989 ;; should be effective both at the time of calling
1990 ;; `isearch-search-fun-default' and also at the
1991 ;; time of funcalling `search-function'.
1992 ;; These isearch-* bindings can't be placed higher
1993 ;; outside of this function because then another I-search
1994 ;; used after `recursive-edit' might override them.
1995 (let* ((isearch-regexp regexp-flag)
1996 (isearch-word delimited-flag)
1997 (isearch-lax-whitespace
1998 replace-lax-whitespace)
1999 (isearch-regexp-lax-whitespace
2000 replace-regexp-lax-whitespace)
2001 (isearch-case-fold-search case-fold-search)
2002 (isearch-adjusted nil)
2003 (isearch-nonincremental t) ; don't use lax word mode
2004 (isearch-forward (not backward))
2007 replace-re-search-function
2008 replace-search-function)
2009 (isearch-search-fun-default))))
2010 (funcall search-function search-string limit t)))
2012 (defvar replace-overlay nil)
2014 (defun replace-highlight (match-beg match-end range-beg range-end
2015 search-string regexp-flag delimited-flag
2016 case-fold-search backward)
2017 (if query-replace-highlight
2019 (move-overlay replace-overlay match-beg match-end (current-buffer))
2020 (setq replace-overlay (make-overlay match-beg match-end))
2021 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2022 (overlay-put replace-overlay 'face 'query-replace)))
2023 (if query-replace-lazy-highlight
2024 (let ((isearch-string search-string)
2025 (isearch-regexp regexp-flag)
2026 (isearch-word delimited-flag)
2027 (isearch-lax-whitespace
2028 replace-lax-whitespace)
2029 (isearch-regexp-lax-whitespace
2030 replace-regexp-lax-whitespace)
2031 (isearch-case-fold-search case-fold-search)
2032 (isearch-forward (not backward))
2033 (isearch-other-end match-beg)
2034 (isearch-error nil))
2035 (isearch-lazy-highlight-new-loop range-beg range-end))))
2037 (defun replace-dehighlight ()
2038 (when replace-overlay
2039 (delete-overlay replace-overlay))
2040 (when query-replace-lazy-highlight
2041 (lazy-highlight-cleanup lazy-highlight-cleanup)
2042 (setq isearch-lazy-highlight-last-string nil))
2043 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2044 (isearch-clean-overlays))
2046 (defun perform-replace (from-string replacements
2047 query-flag regexp-flag delimited-flag
2048 &optional repeat-count map start end backward)
2049 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2050 Don't use this in your own program unless you want to query and set the mark
2051 just as `query-replace' does. Instead, write a simple loop like this:
2053 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2054 (replace-match \"foobar\" nil nil))
2056 which will run faster and probably do exactly what you want. Please
2057 see the documentation of `replace-match' to find out how to simulate
2060 This function returns nil if and only if there were no matches to
2061 make, or the user didn't cancel the call."
2062 (or map (setq map query-replace-map))
2063 (and query-flag minibuffer-auto-raise
2064 (raise-frame (window-frame (minibuffer-window))))
2065 (let* ((case-fold-search
2066 (if (and case-fold-search search-upper-case)
2067 (isearch-no-upper-case-p from-string regexp-flag)
2069 (nocasify (not (and case-replace case-fold-search)))
2070 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2071 (search-string from-string)
2072 (real-match-data nil) ; The match data for the current match.
2073 (next-replacement nil)
2074 ;; This is non-nil if we know there is nothing for the user
2075 ;; to edit in the replacement.
2080 (skip-read-only-count 0)
2081 (skip-filtered-count 0)
2082 (skip-invisible-count 0)
2083 (nonempty-match nil)
2085 (recenter-last-op nil) ; Start cycling order with initial position.
2087 ;; If non-nil, it is marker saying where in the buffer to stop.
2090 ;; Data for the next match. If a cons, it has the same format as
2091 ;; (match-data); otherwise it is t if a match is possible at point.
2097 (substitute-command-keys
2098 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2099 minibuffer-prompt-properties))))
2101 ;; If region is active, in Transient Mark mode, operate on region.
2104 (setq limit (copy-marker (min start end)))
2105 (goto-char (max start end))
2108 (setq limit (copy-marker (max start end)))
2109 (goto-char (min start end))
2112 ;; If last typed key in previous call of multi-buffer perform-replace
2113 ;; was `automatic-all', don't ask more questions in next files
2114 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2115 (setq query-flag nil multi-buffer t))
2117 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
2118 ;; containing a function and its first argument. The function is
2119 ;; called to generate each replacement like this:
2120 ;; (funcall (car replacements) (cdr replacements) replace-count)
2121 ;; It must return a string.
2123 ((stringp replacements)
2124 (setq next-replacement replacements
2126 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2127 (or repeat-count (setq repeat-count 1))
2128 (setq replacements (cons 'replace-loop-through-replacements
2129 (vector repeat-count repeat-count
2130 replacements replacements)))))
2132 (when query-replace-lazy-highlight
2133 (setq isearch-lazy-highlight-last-string nil))
2138 ;; Loop finding occurrences that perhaps should be replaced.
2139 (while (and keep-going
2141 (not (or (bobp) (and limit (<= (point) limit))))
2142 (not (or (eobp) (and limit (>= (point) limit)))))
2143 ;; Use the next match if it is already known;
2144 ;; otherwise, search for a match after moving forward
2145 ;; one char if progress is required.
2146 (setq real-match-data
2147 (cond ((consp match-again)
2148 (goto-char (if backward
2150 (nth 1 match-again)))
2152 t real-match-data match-again))
2153 ;; MATCH-AGAIN non-nil means accept an
2157 (replace-search search-string limit
2158 regexp-flag delimited-flag
2159 case-fold-search backward)
2160 ;; For speed, use only integers and
2161 ;; reuse the list used last time.
2162 (replace-match-data t real-match-data)))
2164 (> (1- (point)) (point-min))
2165 (< (1+ (point)) (point-max)))
2168 (> (1- (point)) limit)
2169 (< (1+ (point)) limit))))
2170 ;; If not accepting adjacent matches,
2171 ;; move one char to the right before
2172 ;; searching again. Undo the motion
2173 ;; if the search fails.
2174 (let ((opoint (point)))
2175 (forward-char (if backward -1 1))
2176 (if (replace-search search-string limit
2177 regexp-flag delimited-flag
2178 case-fold-search backward)
2184 ;; Record whether the match is nonempty, to avoid an infinite loop
2185 ;; repeatedly matching the same empty string.
2186 (setq nonempty-match
2187 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2189 ;; If the match is empty, record that the next one can't be
2192 ;; Otherwise, if matching a regular expression, do the next
2193 ;; match now, since the replacement for this match may
2194 ;; affect whether the next match is adjacent to this one.
2195 ;; If that match is empty, don't use it.
2198 (or (not regexp-flag)
2200 (looking-back search-string)
2201 (looking-at search-string))
2202 (let ((match (match-data)))
2203 (and (/= (nth 0 match) (nth 1 match))
2207 ;; Optionally ignore matches that have a read-only property.
2208 ((not (or (not query-replace-skip-read-only)
2209 (not (text-property-not-all
2210 (nth 0 real-match-data) (nth 1 real-match-data)
2212 (setq skip-read-only-count (1+ skip-read-only-count)))
2213 ;; Optionally filter out matches.
2214 ((not (funcall isearch-filter-predicate
2215 (nth 0 real-match-data) (nth 1 real-match-data)))
2216 (setq skip-filtered-count (1+ skip-filtered-count)))
2217 ;; Optionally ignore invisible matches.
2218 ((not (or (eq search-invisible t)
2219 ;; Don't open overlays for automatic replacements.
2220 (and (not query-flag) search-invisible)
2221 ;; Open hidden overlays for interactive replacements.
2222 (not (isearch-range-invisible
2223 (nth 0 real-match-data) (nth 1 real-match-data)))))
2224 (setq skip-invisible-count (1+ skip-invisible-count)))
2226 ;; Calculate the replacement string, if necessary.
2228 (set-match-data real-match-data)
2229 (setq next-replacement
2230 (funcall (car replacements) (cdr replacements)
2232 (if (not query-flag)
2234 (unless (or literal noedit)
2236 (nth 0 real-match-data) (nth 1 real-match-data)
2237 start end search-string
2238 regexp-flag delimited-flag case-fold-search backward))
2240 (replace-match-maybe-edit
2241 next-replacement nocasify literal
2242 noedit real-match-data backward)
2243 replace-count (1+ replace-count)))
2245 (let (done replaced key def)
2246 ;; Loop reading commands until one of them sets done,
2247 ;; which means it has finished handling this
2248 ;; occurrence. Any command that sets `done' should
2249 ;; leave behind proper match data for the stack.
2250 ;; Commands not setting `done' need to adjust
2251 ;; `real-match-data'.
2253 (set-match-data real-match-data)
2255 (match-beginning 0) (match-end 0)
2256 start end search-string
2257 regexp-flag delimited-flag case-fold-search backward)
2258 ;; Bind message-log-max so we don't fill up the message log
2259 ;; with a bunch of identical messages.
2260 (let ((message-log-max nil)
2261 (replacement-presentation
2262 (if query-replace-show-replacement
2264 (set-match-data real-match-data)
2265 (match-substitute-replacement next-replacement
2269 (query-replace-descr from-string)
2270 (query-replace-descr replacement-presentation)))
2271 (setq key (read-event))
2272 ;; Necessary in case something happens during read-event
2273 ;; that clobbers the match data.
2274 (set-match-data real-match-data)
2275 (setq key (vector key))
2276 (setq def (lookup-key map key))
2277 ;; Restore the match data while we process the command.
2278 (cond ((eq def 'help)
2279 (with-output-to-temp-buffer "*Help*"
2281 (concat "Query replacing "
2283 (or (and (symbolp delimited-flag)
2284 (get delimited-flag 'isearch-message-prefix))
2286 (if regexp-flag "regexp " "")
2287 (if backward "backward " "")
2288 from-string " with "
2289 next-replacement ".\n\n"
2290 (substitute-command-keys
2291 query-replace-help)))
2292 (with-current-buffer standard-output
2295 (setq keep-going nil)
2297 ((eq def 'exit-current)
2298 (setq multi-buffer t keep-going nil done t))
2301 (let ((elt (pop stack)))
2302 (goto-char (nth 0 elt))
2303 (setq replaced (nth 1 elt)
2308 (message "No previous match")
2309 (ding 'no-terminate)
2314 (replace-match-maybe-edit
2315 next-replacement nocasify literal
2316 noedit real-match-data backward)
2317 replace-count (1+ replace-count)))
2318 (setq done t replaced t))
2319 ((eq def 'act-and-exit)
2322 (replace-match-maybe-edit
2323 next-replacement nocasify literal
2324 noedit real-match-data backward)
2325 replace-count (1+ replace-count)))
2326 (setq keep-going nil)
2327 (setq done t replaced t))
2328 ((eq def 'act-and-show)
2331 (replace-match-maybe-edit
2332 next-replacement nocasify literal
2333 noedit real-match-data backward)
2334 replace-count (1+ replace-count)
2335 real-match-data (replace-match-data
2338 ((or (eq def 'automatic) (eq def 'automatic-all))
2341 (replace-match-maybe-edit
2342 next-replacement nocasify literal
2343 noedit real-match-data backward)
2344 replace-count (1+ replace-count)))
2345 (setq done t query-flag nil replaced t)
2346 (if (eq def 'automatic-all) (setq multi-buffer t)))
2350 ;; `this-command' has the value `query-replace',
2351 ;; so we need to bind it to `recenter-top-bottom'
2352 ;; to allow it to detect a sequence of `C-l'.
2353 (let ((this-command 'recenter-top-bottom)
2354 (last-command 'recenter-top-bottom))
2355 (recenter-top-bottom)))
2357 (let ((opos (point-marker)))
2358 (setq real-match-data (replace-match-data
2361 (goto-char (match-beginning 0))
2363 (save-window-excursion
2366 (set-marker opos nil))
2367 ;; Before we make the replacement,
2368 ;; decide whether the search string
2369 ;; can match again just after this match.
2370 (if (and regexp-flag nonempty-match)
2371 (setq match-again (and (looking-at search-string)
2373 ;; Edit replacement.
2374 ((eq def 'edit-replacement)
2375 (setq real-match-data (replace-match-data
2379 (read-string "Edit replacement string: "
2383 (set-match-data real-match-data)
2385 (replace-match-maybe-edit
2386 next-replacement nocasify literal noedit
2387 real-match-data backward)
2391 ((eq def 'delete-and-edit)
2392 (replace-match "" t t)
2393 (setq real-match-data (replace-match-data
2394 nil real-match-data))
2395 (replace-dehighlight)
2396 (save-excursion (recursive-edit))
2398 ;; Note: we do not need to treat `exit-prefix'
2399 ;; specially here, since we reread
2400 ;; any unrecognized character.
2402 (setq this-command 'mode-exited)
2403 (setq keep-going nil)
2404 (setq unread-command-events
2405 (append (listify-key-sequence key)
2406 unread-command-events))
2408 (when query-replace-lazy-highlight
2409 ;; Force lazy rehighlighting only after replacements.
2410 (if (not (memq def '(skip backup)))
2411 (setq isearch-lazy-highlight-last-string nil)))
2412 (unless (eq def 'recenter)
2413 ;; Reset recenter cycling order to initial position.
2414 (setq recenter-last-op nil)))
2415 ;; Record previous position for ^ when we move on.
2416 ;; Change markers to numbers in the match data
2417 ;; since lots of markers slow down editing.
2418 (push (list (point) replaced
2419 ;;; If the replacement has already happened, all we need is the
2420 ;;; current match start and end. We could get this with a trivial
2422 ;;; (save-excursion (goto-char (match-beginning 0))
2423 ;;; (search-forward (match-string 0))
2425 ;;; if we really wanted to avoid manually constructing match data.
2426 ;;; Adding current-buffer is necessary so that match-data calls can
2427 ;;; return markers which are appropriate for editing.
2436 (replace-dehighlight))
2437 (or unread-command-events
2438 (message "Replaced %d occurrence%s%s"
2440 (if (= replace-count 1) "" "s")
2441 (if (> (+ skip-read-only-count
2443 skip-invisible-count) 0)
2444 (format " (skipped %s)"
2448 (if (> skip-read-only-count 0)
2449 (format "%s read-only"
2450 skip-read-only-count))
2451 (if (> skip-invisible-count 0)
2452 (format "%s invisible"
2453 skip-invisible-count))
2454 (if (> skip-filtered-count 0)
2455 (format "%s filtered out"
2456 skip-filtered-count))))
2459 (or (and keep-going stack) multi-buffer)))
2461 ;;; replace.el ends here