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-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 ;; Ignore errors when attempt to autoload char-displayable-p
74 ;; fails while preparing to dump.
75 (if (char-displayable-p ?
\u2192) " \u2192 " " -> "))
77 'face
'minibuffer-prompt
)
78 "String that separates FROM and TO in the history of replacement pairs."
83 (defcustom query-replace-from-history-variable
'query-replace-history
84 "History list to use for the FROM argument of `query-replace' commands.
85 The value of this variable should be a symbol; that symbol
86 is used as a variable to hold a history list for the strings
87 or patterns to be replaced."
92 (defcustom query-replace-to-history-variable
'query-replace-history
93 "History list to use for the TO argument of `query-replace' commands.
94 The value of this variable should be a symbol; that symbol
95 is used as a variable to hold a history list for replacement
101 (defcustom query-replace-skip-read-only nil
102 "Non-nil means `query-replace' and friends ignore read-only matches."
107 (defcustom query-replace-show-replacement t
108 "Non-nil means to show what actual replacement text will be."
113 (defcustom query-replace-highlight t
114 "Non-nil means to highlight matches during query replacement."
118 (defcustom query-replace-lazy-highlight t
119 "Controls the lazy-highlighting during query replacements.
120 When non-nil, all text in the buffer matching the current match
121 is highlighted lazily using isearch lazy highlighting (see
122 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
124 :group
'lazy-highlight
128 (defface query-replace
129 '((t (:inherit isearch
)))
130 "Face for highlighting query replacement matches."
134 (defvar replace-count
0
135 "Number of replacements done so far.
136 See `replace-regexp' and `query-replace-regexp-eval'.")
138 (defun query-replace-descr (string)
139 (mapconcat 'isearch-text-char-description string
""))
141 (defun query-replace-read-from (prompt regexp-flag
)
142 "Query and return the `from' argument of a query-replace operation.
143 The return value can also be a pair (FROM . TO) indicating that the user
144 wants to replace FROM with TO."
145 (if query-replace-interactive
146 (car (if regexp-flag regexp-search-ring search-ring
))
147 ;; Reevaluating will check char-displayable-p that is
148 ;; unavailable while preparing to dump.
149 (custom-reevaluate-setting 'query-replace-from-to-separator
)
150 (let* ((history-add-new-input nil
)
152 (when query-replace-from-to-separator
154 'display query-replace-from-to-separator
156 (query-replace-from-to-history
159 (mapcar (lambda (from-to)
160 (concat (query-replace-descr (car from-to
))
162 (query-replace-descr (cdr from-to
))))
163 query-replace-defaults
))
164 (symbol-value query-replace-from-history-variable
)))
165 (minibuffer-allow-text-properties t
) ; separator uses text-properties
167 (if (and query-replace-defaults separator
)
168 (format "%s (default %s): " prompt
(car query-replace-from-to-history
))
169 (format "%s: " prompt
)))
171 ;; The save-excursion here is in case the user marks and copies
172 ;; a region in order to specify the minibuffer input.
173 ;; That should not clobber the region for the query-replace itself.
176 (read-regexp prompt nil
'query-replace-from-to-history
)
177 (read-from-minibuffer
178 prompt nil nil nil
'query-replace-from-to-history
179 (car (if regexp-flag regexp-search-ring search-ring
)) t
)))))
180 (if (and (zerop (length from
)) query-replace-defaults
)
181 (cons (caar query-replace-defaults
)
182 (query-replace-compile-replacement
183 (cdar query-replace-defaults
) regexp-flag
))
184 (let* ((to (if (and (string-match separator from
)
185 (get-text-property (match-beginning 0) 'separator from
))
186 (substring-no-properties from
(match-end 0))))
187 (from (if to
(substring-no-properties from
0 (match-beginning 0))
188 (substring-no-properties from
))))
189 (add-to-history query-replace-from-history-variable from nil t
)
190 ;; Warn if user types \n or \t, but don't reject the input.
192 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
193 (let ((match (match-string 3 from
)))
195 ((string= match
"\\n")
196 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
197 ((string= match
"\\t")
198 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
202 (add-to-history query-replace-to-history-variable to nil t
)
203 (add-to-history 'query-replace-defaults
(cons from to
) nil t
)
204 (cons from
(query-replace-compile-replacement to regexp-flag
))))))))
206 (defun query-replace-compile-replacement (to regexp-flag
)
207 "Maybe convert a regexp replacement TO to Lisp.
208 Returns a list suitable for `perform-replace' if necessary,
209 the original string if not."
211 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
))
215 (setq pos
(match-end 0))
216 (push (substring to
0 (- pos
2)) list
)
217 (setq char
(aref to
(1- pos
))
218 to
(substring to pos
))
220 (push '(number-to-string replace-count
) list
))
222 (setq pos
(read-from-string to
))
223 (push `(replace-quote ,(car pos
)) list
)
225 ;; Swallow a space after a symbol
226 ;; if there is a space.
227 (if (and (or (symbolp (car pos
))
228 ;; Swallow a space after 'foo
229 ;; but not after (quote foo).
230 (and (eq (car-safe (car pos
)) 'quote
)
231 (not (= ?\
( (aref to
0)))))
232 (eq (string-match " " to
(cdr pos
))
236 (setq to
(substring to end
)))))
237 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
)))
238 (setq to
(nreverse (delete "" (cons to list
))))
239 (replace-match-string-symbols to
)
240 (cons 'replace-eval-replacement
247 (defun query-replace-read-to (from prompt regexp-flag
)
248 "Query and return the `to' argument of a query-replace operation."
249 (query-replace-compile-replacement
251 (let* ((history-add-new-input nil
)
252 (to (read-from-minibuffer
253 (format "%s %s with: " prompt
(query-replace-descr from
))
255 query-replace-to-history-variable from t
)))
256 (add-to-history query-replace-to-history-variable to nil t
)
257 (add-to-history 'query-replace-defaults
(cons from to
) nil t
)
261 (defun query-replace-read-args (prompt regexp-flag
&optional noerror
)
263 (barf-if-buffer-read-only))
264 (let* ((from (query-replace-read-from prompt regexp-flag
))
265 (to (if (consp from
) (prog1 (cdr from
) (setq from
(car from
)))
266 (query-replace-read-to from prompt regexp-flag
))))
268 (and current-prefix-arg
(not (eq current-prefix-arg
'-
)))
269 (and current-prefix-arg
(eq current-prefix-arg
'-
)))))
271 (defun query-replace (from-string to-string
&optional delimited start end backward
)
272 "Replace some occurrences of FROM-STRING with TO-STRING.
273 As each match is found, the user must type a character saying
274 what to do with it. For directions, type \\[help-command] at that time.
276 In Transient Mark mode, if the mark is active, operate on the contents
277 of the region. Otherwise, operate from point to the end of the buffer.
279 Use \\<minibuffer-local-map>\\[next-history-element] \
280 to pull the last incremental search string to the minibuffer
281 that reads FROM-STRING, or invoke replacements from
282 incremental search with a key sequence like `C-s C-s M-%'
283 to use its current search string as the string to replace.
285 Matching is independent of case if `case-fold-search' is non-nil and
286 FROM-STRING has no uppercase letters. Replacement transfers the case
287 pattern of the old text to the new text, if `case-replace' and
288 `case-fold-search' are non-nil and FROM-STRING has no uppercase
289 letters. (Transferring the case pattern means that if the old text
290 matched is all caps, or capitalized, then its replacement is upcased
293 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
294 ignore hidden matches if `search-invisible' is nil, and ignore more
295 matches using `isearch-filter-predicate'.
297 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
298 to be replaced will match a sequence of whitespace chars defined by the
299 regexp in `search-whitespace-regexp'.
301 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
302 only matches surrounded by word boundaries. A negative prefix arg means
305 Fourth and fifth arg START and END specify the region to operate on.
307 To customize possible responses, change the bindings in `query-replace-map'."
310 (query-replace-read-args
311 (concat "Query replace"
312 (if current-prefix-arg
313 (if (eq current-prefix-arg
'-
) " backward" " word")
315 (if (and transient-mark-mode mark-active
) " in region" ""))
317 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
318 ;; These are done separately here
319 ;; so that command-history will record these expressions
320 ;; rather than the values they had this time.
321 (if (and transient-mark-mode mark-active
)
323 (if (and transient-mark-mode mark-active
)
326 (perform-replace from-string to-string t nil delimited nil nil start end backward
))
328 (define-key esc-map
"%" 'query-replace
)
330 (defun query-replace-regexp (regexp to-string
&optional delimited start end backward
)
331 "Replace some things after point matching REGEXP with TO-STRING.
332 As each match is found, the user must type a character saying
333 what to do with it. For directions, type \\[help-command] at that time.
335 In Transient Mark mode, if the mark is active, operate on the contents
336 of the region. Otherwise, operate from point to the end of the buffer.
338 Use \\<minibuffer-local-map>\\[next-history-element] \
339 to pull the last incremental search regexp to the minibuffer
340 that reads REGEXP, or invoke replacements from
341 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
342 to use its current search regexp as the regexp to replace.
344 Matching is independent of case if `case-fold-search' is non-nil and
345 REGEXP has no uppercase letters. Replacement transfers the case
346 pattern of the old text to the new text, if `case-replace' and
347 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
348 \(Transferring the case pattern means that if the old text matched is
349 all caps, or capitalized, then its replacement is upcased or
352 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
353 ignore hidden matches if `search-invisible' is nil, and ignore more
354 matches using `isearch-filter-predicate'.
356 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
357 to be replaced will match a sequence of whitespace chars defined by the
358 regexp in `search-whitespace-regexp'.
360 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
361 only matches surrounded by word boundaries. A negative prefix arg means
364 Fourth and fifth arg START and END specify the region to operate on.
366 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
367 and `\\=\\N' (where N is a digit) stands for
368 whatever what matched the Nth `\\(...\\)' in REGEXP.
369 `\\?' lets you edit the replacement text in the minibuffer
370 at the given position for each replacement.
372 In interactive calls, the replacement text can contain `\\,'
373 followed by a Lisp expression. Each
374 replacement evaluates that expression to compute the replacement
375 string. Inside of that expression, `\\&' is a string denoting the
376 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
377 for the whole or a partial match converted to a number with
378 `string-to-number', and `\\#' itself for the number of replacements
379 done so far (starting with zero).
381 If the replacement expression is a symbol, write a space after it
382 to terminate it. One space there, if any, will be discarded.
384 When using those Lisp features interactively in the replacement
385 text, TO-STRING is actually made a list instead of a string.
386 Use \\[repeat-complex-command] after this command for details."
389 (query-replace-read-args
390 (concat "Query replace"
391 (if current-prefix-arg
392 (if (eq current-prefix-arg
'-
) " backward" " word")
395 (if (and transient-mark-mode mark-active
) " in region" ""))
397 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
398 ;; These are done separately here
399 ;; so that command-history will record these expressions
400 ;; rather than the values they had this time.
401 (if (and transient-mark-mode mark-active
)
403 (if (and transient-mark-mode mark-active
)
406 (perform-replace regexp to-string t t delimited nil nil start end backward
))
408 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
410 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
411 "Replace some things after point matching REGEXP with the result of TO-EXPR.
413 Interactive use of this function is deprecated in favor of the
414 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
415 using `search-forward-regexp' and `replace-match' is preferred.
417 As each match is found, the user must type a character saying
418 what to do with it. For directions, type \\[help-command] at that time.
420 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
421 reference `replace-count' to get the number of replacements already made.
422 If the result of TO-EXPR is not a string, it is converted to one using
423 `prin1-to-string' with the NOESCAPE argument (which see).
425 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
426 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
427 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
428 Use `\\#&' or `\\#N' if you want a number instead of a string.
429 In interactive use, `\\#' in itself stands for `replace-count'.
431 In Transient Mark mode, if the mark is active, operate on the contents
432 of the region. Otherwise, operate from point to the end of the buffer.
434 Use \\<minibuffer-local-map>\\[next-history-element] \
435 to pull the last incremental search regexp to the minibuffer
438 Preserves case in each replacement if `case-replace' and `case-fold-search'
439 are non-nil and REGEXP has no uppercase letters.
441 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
442 ignore hidden matches if `search-invisible' is nil, and ignore more
443 matches using `isearch-filter-predicate'.
445 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
446 to be replaced will match a sequence of whitespace chars defined by the
447 regexp in `search-whitespace-regexp'.
449 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
450 only matches that are surrounded by word boundaries.
451 Fourth and fifth arg START and END specify the region to operate on."
452 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
453 for interactive calls, and `search-forward-regexp'/`replace-match'
454 for Lisp calls." "22.1"))
457 (barf-if-buffer-read-only)
459 ;; Let-bind the history var to disable the "foo -> bar"
460 ;; default. Maybe we shouldn't disable this default, but
461 ;; for now I'll leave it off. --Stef
462 (let ((query-replace-defaults nil
))
463 (query-replace-read-from "Query replace regexp" t
)))
464 (to (list (read-from-minibuffer
465 (format "Query replace regexp %s with eval: "
466 (query-replace-descr from
))
467 nil nil t query-replace-to-history-variable from t
))))
468 ;; We make TO a list because replace-match-string-symbols requires one,
469 ;; and the user might enter a single token.
470 (replace-match-string-symbols to
)
471 (list from
(car to
) current-prefix-arg
472 (if (and transient-mark-mode mark-active
)
474 (if (and transient-mark-mode mark-active
)
476 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
477 t
'literal delimited nil nil start end
))
479 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
480 "Replace some matches for REGEXP with various strings, in rotation.
481 The second argument TO-STRINGS contains the replacement strings, separated
482 by spaces. This command works like `query-replace-regexp' except that
483 each successive replacement uses the next successive replacement string,
484 wrapping around from the last such string to the first.
486 In Transient Mark mode, if the mark is active, operate on the contents
487 of the region. Otherwise, operate from point to the end of the buffer.
489 Non-interactively, TO-STRINGS may be a list of replacement strings.
491 Interactively, reads the regexp using `read-regexp'.
492 Use \\<minibuffer-local-map>\\[next-history-element] \
493 to pull the last incremental search regexp to the minibuffer
496 A prefix argument N says to use each replacement string N times
497 before rotating to the next.
498 Fourth and fifth arg START and END specify the region to operate on."
500 (let* ((from (read-regexp "Map query replace (regexp): " nil
501 query-replace-from-history-variable
))
502 (to (read-from-minibuffer
503 (format "Query replace %s with (space-separated strings): "
504 (query-replace-descr from
))
506 query-replace-to-history-variable from t
)))
508 (and current-prefix-arg
509 (prefix-numeric-value current-prefix-arg
))
510 (if (and transient-mark-mode mark-active
)
512 (if (and transient-mark-mode mark-active
)
515 (if (listp to-strings
)
516 (setq replacements to-strings
)
517 (while (/= (length to-strings
) 0)
518 (if (string-match " " to-strings
)
521 (list (substring to-strings
0
522 (string-match " " to-strings
))))
523 to-strings
(substring to-strings
524 (1+ (string-match " " to-strings
))))
525 (setq replacements
(append replacements
(list to-strings
))
527 (perform-replace regexp replacements t t nil n nil start end
)))
529 (defun replace-string (from-string to-string
&optional delimited start end backward
)
530 "Replace occurrences of FROM-STRING with TO-STRING.
531 Preserve case in each match if `case-replace' and `case-fold-search'
532 are non-nil and FROM-STRING has no uppercase letters.
533 \(Preserving case means that if the string matched is all caps, or capitalized,
534 then its replacement is upcased or capitalized.)
536 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
537 ignore hidden matches if `search-invisible' is nil, and ignore more
538 matches using `isearch-filter-predicate'.
540 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
541 to be replaced will match a sequence of whitespace chars defined by the
542 regexp in `search-whitespace-regexp'.
544 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
545 only matches surrounded by word boundaries. A negative prefix arg means
548 Operates on the region between START and END (if both are nil, from point
549 to the end of the buffer). Interactively, if Transient Mark mode is
550 enabled and the mark is active, operates on the contents of the region;
551 otherwise from point to the end of the buffer.
553 Use \\<minibuffer-local-map>\\[next-history-element] \
554 to pull the last incremental search string to the minibuffer
555 that reads FROM-STRING.
557 This function is usually the wrong thing to use in a Lisp program.
558 What you probably want is a loop like this:
559 (while (search-forward FROM-STRING nil t)
560 (replace-match TO-STRING nil t))
561 which will run faster and will not set the mark or print anything.
562 \(You may need a more complex loop if FROM-STRING can match the null string
563 and TO-STRING is also null.)"
564 (declare (interactive-only
565 "use `search-forward' and `replace-match' instead."))
568 (query-replace-read-args
570 (if current-prefix-arg
571 (if (eq current-prefix-arg
'-
) " backward" " word")
574 (if (and transient-mark-mode mark-active
) " in region" ""))
576 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
577 (if (and transient-mark-mode mark-active
)
579 (if (and transient-mark-mode mark-active
)
582 (perform-replace from-string to-string nil nil delimited nil nil start end backward
))
584 (defun replace-regexp (regexp to-string
&optional delimited start end backward
)
585 "Replace things after point matching REGEXP with TO-STRING.
586 Preserve case in each match if `case-replace' and `case-fold-search'
587 are non-nil and REGEXP has no uppercase letters.
589 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
590 ignore hidden matches if `search-invisible' is nil, and ignore more
591 matches using `isearch-filter-predicate'.
593 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
594 to be replaced will match a sequence of whitespace chars defined by the
595 regexp in `search-whitespace-regexp'.
597 In Transient Mark mode, if the mark is active, operate on the contents
598 of the region. Otherwise, operate from point to the end of the buffer.
600 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
601 only matches surrounded by word boundaries. A negative prefix arg means
604 Fourth and fifth arg START and END specify the region to operate on.
606 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
607 and `\\=\\N' (where N is a digit) stands for
608 whatever what matched the Nth `\\(...\\)' in REGEXP.
609 `\\?' lets you edit the replacement text in the minibuffer
610 at the given position for each replacement.
612 In interactive calls, the replacement text may contain `\\,'
613 followed by a Lisp expression used as part of the replacement
614 text. Inside of that expression, `\\&' is a string denoting the
615 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
616 numeric values from `string-to-number', and `\\#' itself for
617 `replace-count', the number of replacements occurred so far.
619 If your Lisp expression is an identifier and the next letter in
620 the replacement string would be interpreted as part of it, you
621 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
622 for this particular case you may also enter `\\#' in the
623 replacement text directly.
625 When using those Lisp features interactively in the replacement
626 text, TO-STRING is actually made a list instead of a string.
627 Use \\[repeat-complex-command] after this command for details.
629 Use \\<minibuffer-local-map>\\[next-history-element] \
630 to pull the last incremental search regexp to the minibuffer
633 This function is usually the wrong thing to use in a Lisp program.
634 What you probably want is a loop like this:
635 (while (re-search-forward REGEXP nil t)
636 (replace-match TO-STRING nil nil))
637 which will run faster and will not set the mark or print anything."
638 (declare (interactive-only
639 "use `re-search-forward' and `replace-match' instead."))
642 (query-replace-read-args
644 (if current-prefix-arg
645 (if (eq current-prefix-arg
'-
) " backward" " word")
648 (if (and transient-mark-mode mark-active
) " in region" ""))
650 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
651 (if (and transient-mark-mode mark-active
)
653 (if (and transient-mark-mode mark-active
)
656 (perform-replace regexp to-string nil t delimited nil nil start end backward
))
659 (defvar regexp-history nil
660 "History list for some commands that read regular expressions.
662 Maximum length of the history list is determined by the value
663 of `history-length', which see.")
665 (defvar occur-collect-regexp-history
'("\\1")
666 "History of regexp for occur's collect operation")
668 (defcustom read-regexp-defaults-function nil
669 "Function that provides default regexp(s) for `read-regexp'.
670 This function should take no arguments and return one of: nil, a
671 regexp, or a list of regexps. Interactively, `read-regexp' uses
672 the return value of this function for its DEFAULT argument.
674 As an example, set this variable to `find-tag-default-as-regexp'
675 to default to the symbol at point.
677 To provide different default regexps for different commands,
678 the function that you set this to can check `this-command'."
680 (const :tag
"No default regexp reading function" nil
)
681 (const :tag
"Latest regexp history" regexp-history-last
)
682 (function-item :tag
"Tag at point"
684 (function-item :tag
"Tag at point as regexp"
685 find-tag-default-as-regexp
)
686 (function-item :tag
"Tag at point as symbol regexp"
687 find-tag-default-as-symbol-regexp
)
688 (function :tag
"Your choice of function"))
692 (defun read-regexp-suggestions ()
693 "Return a list of standard suggestions for `read-regexp'.
694 By default, the list includes the tag at point, the last isearch regexp,
695 the last isearch string, and the last replacement regexp. `read-regexp'
696 appends the list returned by this function to the end of values available
697 via \\<minibuffer-local-map>\\[next-history-element]."
699 (find-tag-default-as-regexp)
700 (find-tag-default-as-symbol-regexp)
701 (car regexp-search-ring
)
702 (regexp-quote (or (car search-ring
) ""))
703 (car (symbol-value query-replace-from-history-variable
))))
705 (defun read-regexp (prompt &optional defaults history
)
706 "Read and return a regular expression as a string.
707 Prompt with the string PROMPT. If PROMPT ends in \":\" (followed by
708 optional whitespace), use it as-is. Otherwise, add \": \" to the end,
709 possibly preceded by the default result (see below).
711 The optional argument DEFAULTS can be either: nil, a string, a list
712 of strings, or a symbol. We use DEFAULTS to construct the default
713 return value in case of empty input.
715 If DEFAULTS is a string, we use it as-is.
717 If DEFAULTS is a list of strings, the first element is the
718 default return value, but all the elements are accessible
719 using the history command \\<minibuffer-local-map>\\[next-history-element].
721 If DEFAULTS is a non-nil symbol, then if `read-regexp-defaults-function'
722 is non-nil, we use that in place of DEFAULTS in the following:
723 If DEFAULTS is the symbol `regexp-history-last', we use the first
724 element of HISTORY (if specified) or `regexp-history'.
725 If DEFAULTS is a function, we call it with no arguments and use
726 what it returns, which should be either nil, a string, or a list of strings.
728 We append the standard values from `read-regexp-suggestions' to DEFAULTS
731 If the first element of DEFAULTS is non-nil (and if PROMPT does not end
732 in \":\", followed by optional whitespace), we add it to the prompt.
734 The optional argument HISTORY is a symbol to use for the history list.
735 If nil, uses `regexp-history'."
737 (if (and defaults
(symbolp defaults
))
739 ((eq (or read-regexp-defaults-function defaults
)
740 'regexp-history-last
)
741 (car (symbol-value (or history
'regexp-history
))))
742 ((functionp (or read-regexp-defaults-function defaults
))
743 (funcall (or read-regexp-defaults-function defaults
))))
745 (default (if (consp defaults
) (car defaults
) defaults
))
746 (suggestions (if (listp defaults
) defaults
(list defaults
)))
747 (suggestions (append suggestions
(read-regexp-suggestions)))
748 (suggestions (delete-dups (delq nil
(delete "" suggestions
))))
749 ;; Do not automatically add default to the history for empty input.
750 (history-add-new-input nil
)
751 (input (read-from-minibuffer
752 (cond ((string-match-p ":[ \t]*\\'" prompt
)
754 ((and default
(> (length default
) 0))
755 (format "%s (default %s): " prompt
756 (query-replace-descr default
)))
758 (format "%s: " prompt
)))
759 nil nil nil
(or history
'regexp-history
) suggestions t
)))
761 ;; Return the default value when the user enters empty input.
762 (prog1 (or default input
)
764 (add-to-history (or history
'regexp-history
) default
)))
765 ;; Otherwise, add non-empty input to the history and return input.
767 (add-to-history (or history
'regexp-history
) input
)))))
770 (defalias 'delete-non-matching-lines
'keep-lines
)
771 (defalias 'delete-matching-lines
'flush-lines
)
772 (defalias 'count-matches
'how-many
)
775 (defun keep-lines-read-args (prompt)
776 "Read arguments for `keep-lines' and friends.
777 Prompt for a regexp with PROMPT.
778 Value is a list, (REGEXP)."
779 (list (read-regexp prompt
) nil nil t
))
781 (defun keep-lines (regexp &optional rstart rend interactive
)
782 "Delete all lines except those containing matches for REGEXP.
783 A match split across lines preserves all the lines it lies in.
784 When called from Lisp (and usually interactively as well, see below)
785 applies to all lines starting after point.
787 If REGEXP contains upper case characters (excluding those preceded by `\\')
788 and `search-upper-case' is non-nil, the matching is case-sensitive.
790 Second and third arg RSTART and REND specify the region to operate on.
791 This command operates on (the accessible part of) all lines whose
792 accessible part is entirely contained in the region determined by RSTART
793 and REND. (A newline ending a line counts as part of that line.)
795 Interactively, in Transient Mark mode when the mark is active, operate
796 on all lines whose accessible part is entirely contained in the region.
797 Otherwise, the command applies to all lines starting after point.
798 When calling this function from Lisp, you can pretend that it was
799 called interactively by passing a non-nil INTERACTIVE argument.
801 This function starts looking for the next match from the end of
802 the previous match. Hence, it ignores matches that overlap
803 a previously found match."
807 (barf-if-buffer-read-only)
808 (keep-lines-read-args "Keep lines containing match for regexp")))
811 (goto-char (min rstart rend
))
815 (goto-char (max rstart rend
))
816 (unless (or (bolp) (eobp))
819 (if (and interactive transient-mark-mode mark-active
)
820 (setq rstart
(region-beginning)
822 (goto-char (region-end))
823 (unless (or (bolp) (eobp))
827 rend
(point-max-marker)))
830 (or (bolp) (forward-line 1))
831 (let ((start (point))
833 (if (and case-fold-search search-upper-case
)
834 (isearch-no-upper-case-p regexp t
)
836 (while (< (point) rend
)
837 ;; Start is first char not preserved by previous match.
838 (if (not (re-search-forward regexp rend
'move
))
839 (delete-region start rend
)
840 (let ((end (save-excursion (goto-char (match-beginning 0))
843 ;; Now end is first char preserved by the new match.
845 (delete-region start end
))))
847 (setq start
(save-excursion (forward-line 1) (point)))
848 ;; If the match was empty, avoid matching again at same place.
849 (and (< (point) rend
)
850 (= (match-beginning 0) (match-end 0))
852 (set-marker rend nil
)
856 (defun flush-lines (regexp &optional rstart rend interactive
)
857 "Delete lines containing matches for REGEXP.
858 When called from Lisp (and usually when called interactively as
859 well, see below), applies to the part of the buffer after point.
860 The line point is in is deleted if and only if it contains a
861 match for regexp starting after point.
863 If REGEXP contains upper case characters (excluding those preceded by `\\')
864 and `search-upper-case' is non-nil, the matching is case-sensitive.
866 Second and third arg RSTART and REND specify the region to operate on.
867 Lines partially contained in this region are deleted if and only if
868 they contain a match entirely contained in it.
870 Interactively, in Transient Mark mode when the mark is active, operate
871 on the contents of the region. Otherwise, operate from point to the
872 end of (the accessible portion of) the buffer. When calling this function
873 from Lisp, you can pretend that it was called interactively by passing
874 a non-nil INTERACTIVE argument.
876 If a match is split across lines, all the lines it lies in are deleted.
877 They are deleted _before_ looking for the next match. Hence, a match
878 starting on the same line at which another match ended is ignored."
882 (barf-if-buffer-read-only)
883 (keep-lines-read-args "Flush lines containing match for regexp")))
886 (goto-char (min rstart rend
))
887 (setq rend
(copy-marker (max rstart rend
))))
888 (if (and interactive transient-mark-mode mark-active
)
889 (setq rstart
(region-beginning)
890 rend
(copy-marker (region-end)))
892 rend
(point-max-marker)))
894 (let ((case-fold-search
895 (if (and case-fold-search search-upper-case
)
896 (isearch-no-upper-case-p regexp t
)
899 (while (and (< (point) rend
)
900 (re-search-forward regexp rend t
))
901 (delete-region (save-excursion (goto-char (match-beginning 0))
904 (progn (forward-line 1) (point))))))
905 (set-marker rend nil
)
909 (defun how-many (regexp &optional rstart rend interactive
)
910 "Print and return number of matches for REGEXP following point.
911 When called from Lisp and INTERACTIVE is omitted or nil, just return
912 the number, do not print it; if INTERACTIVE is t, the function behaves
913 in all respects as if it had been called interactively.
915 If REGEXP contains upper case characters (excluding those preceded by `\\')
916 and `search-upper-case' is non-nil, the matching is case-sensitive.
918 Second and third arg RSTART and REND specify the region to operate on.
920 Interactively, in Transient Mark mode when the mark is active, operate
921 on the contents of the region. Otherwise, operate from point to the
922 end of (the accessible portion of) the buffer.
924 This function starts looking for the next match from the end of
925 the previous match. Hence, it ignores matches that overlap
926 a previously found match."
929 (keep-lines-read-args "How many matches for regexp"))
934 (goto-char (min rstart rend
))
935 (setq rend
(max rstart rend
)))
937 (setq rend
(point-max)))
938 (if (and interactive transient-mark-mode mark-active
)
939 (setq rstart
(region-beginning)
947 (if (and case-fold-search search-upper-case
)
948 (isearch-no-upper-case-p regexp t
)
950 (while (and (< (point) rend
)
951 (progn (setq opoint
(point))
952 (re-search-forward regexp rend t
)))
953 (if (= opoint
(point))
955 (setq count
(1+ count
))))
956 (when interactive
(message "%d occurrence%s"
958 (if (= count
1) "" "s")))
962 (defvar occur-menu-map
963 (let ((map (make-sparse-keymap)))
964 (bindings--define-key map
[next-error-follow-minor-mode
]
965 '(menu-item "Auto Occurrence Display"
966 next-error-follow-minor-mode
967 :help
"Display another occurrence when moving the cursor"
968 :button
(:toggle .
(and (boundp 'next-error-follow-minor-mode
)
969 next-error-follow-minor-mode
))))
970 (bindings--define-key map
[separator-1
] menu-bar-separator
)
971 (bindings--define-key map
[kill-this-buffer
]
972 '(menu-item "Kill Occur Buffer" kill-this-buffer
973 :help
"Kill the current *Occur* buffer"))
974 (bindings--define-key map
[quit-window
]
975 '(menu-item "Quit Occur Window" quit-window
976 :help
"Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
977 (bindings--define-key map
[revert-buffer
]
978 '(menu-item "Revert Occur Buffer" revert-buffer
979 :help
"Replace the text in the *Occur* buffer with the results of rerunning occur"))
980 (bindings--define-key map
[clone-buffer
]
981 '(menu-item "Clone Occur Buffer" clone-buffer
982 :help
"Create and return a twin copy of the current *Occur* buffer"))
983 (bindings--define-key map
[occur-rename-buffer
]
984 '(menu-item "Rename Occur Buffer" occur-rename-buffer
985 :help
"Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
986 (bindings--define-key map
[occur-edit-buffer
]
987 '(menu-item "Edit Occur Buffer" occur-edit-mode
988 :help
"Edit the *Occur* buffer and apply changes to the original buffers."))
989 (bindings--define-key map
[separator-2
] menu-bar-separator
)
990 (bindings--define-key map
[occur-mode-goto-occurrence-other-window
]
991 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
992 :help
"Go to the occurrence the current line describes, in another window"))
993 (bindings--define-key map
[occur-mode-goto-occurrence
]
994 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
995 :help
"Go to the occurrence the current line describes"))
996 (bindings--define-key map
[occur-mode-display-occurrence
]
997 '(menu-item "Display Occurrence" occur-mode-display-occurrence
998 :help
"Display in another window the occurrence the current line describes"))
999 (bindings--define-key map
[occur-next
]
1000 '(menu-item "Move to Next Match" occur-next
1001 :help
"Move to the Nth (default 1) next match in an Occur mode buffer"))
1002 (bindings--define-key map
[occur-prev
]
1003 '(menu-item "Move to Previous Match" occur-prev
1004 :help
"Move to the Nth (default 1) previous match in an Occur mode buffer"))
1006 "Menu keymap for `occur-mode'.")
1008 (defvar occur-mode-map
1009 (let ((map (make-sparse-keymap)))
1010 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
1011 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
1012 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
1013 (define-key map
"e" 'occur-edit-mode
)
1014 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
1015 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
1016 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
1017 (define-key map
"\M-n" 'occur-next
)
1018 (define-key map
"\M-p" 'occur-prev
)
1019 (define-key map
"r" 'occur-rename-buffer
)
1020 (define-key map
"c" 'clone-buffer
)
1021 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
1022 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
1024 "Keymap for `occur-mode'.")
1026 (defvar occur-revert-arguments nil
1027 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
1028 See `occur-revert-function'.")
1029 (make-variable-buffer-local 'occur-revert-arguments
)
1030 (put 'occur-revert-arguments
'permanent-local t
)
1032 (defcustom occur-mode-hook
'(turn-on-font-lock)
1033 "Hook run when entering Occur mode."
1037 (defcustom occur-hook nil
1038 "Hook run by Occur when there are any matches."
1042 (defcustom occur-mode-find-occurrence-hook nil
1043 "Hook run by Occur after locating an occurrence.
1044 This will be called with the cursor position at the occurrence. An application
1045 for this is to reveal context in an outline-mode when the occurrence is hidden."
1049 (put 'occur-mode
'mode-class
'special
)
1050 (define-derived-mode occur-mode special-mode
"Occur"
1051 "Major mode for output from \\[occur].
1052 \\<occur-mode-map>Move point to one of the items in this buffer, then use
1053 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
1054 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
1057 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
1058 (setq next-error-function
'occur-next-error
))
1063 (defvar occur-edit-mode-map
1064 (let ((map (make-sparse-keymap)))
1065 (set-keymap-parent map text-mode-map
)
1066 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
1067 (define-key map
"\C-c\C-c" 'occur-cease-edit
)
1068 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
1069 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
1070 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
1072 "Keymap for `occur-edit-mode'.")
1074 (define-derived-mode occur-edit-mode occur-mode
"Occur-Edit"
1075 "Major mode for editing *Occur* buffers.
1076 In this mode, changes to the *Occur* buffer are also applied to
1077 the originating buffer.
1079 To return to ordinary Occur mode, use \\[occur-cease-edit]."
1080 (setq buffer-read-only nil
)
1081 (add-hook 'after-change-functions
'occur-after-change-function nil t
)
1082 (message (substitute-command-keys
1083 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
1085 (defun occur-cease-edit ()
1086 "Switch from Occur Edit mode to Occur mode."
1088 (when (derived-mode-p 'occur-edit-mode
)
1090 (message "Switching to Occur mode.")))
1092 (defun occur-after-change-function (beg end length
)
1095 (let* ((line-beg (line-beginning-position))
1096 (m (get-text-property line-beg
'occur-target
))
1097 (buf (marker-buffer m
))
1099 (when (and (get-text-property line-beg
'occur-prefix
)
1100 (not (get-text-property end
'occur-prefix
)))
1102 ;; Apply occur-target property to inserted (e.g. yanked) text.
1103 (put-text-property beg end
'occur-target m
)
1104 ;; Did we insert a newline? Occur Edit mode can't create new
1105 ;; Occur entries; just discard everything after the newline.
1107 (and (search-forward "\n" end t
)
1108 (delete-region (1- (point)) end
))))
1109 (let* ((line (- (line-number-at-pos)
1110 (line-number-at-pos (window-start))))
1111 (readonly (with-current-buffer buf buffer-read-only
))
1112 (win (or (get-buffer-window buf
)
1114 '(nil (inhibit-same-window . t
)
1115 (inhibit-switch-frame . t
)))))
1116 (line-end (line-end-position))
1117 (text (save-excursion
1118 (goto-char (next-single-property-change
1119 line-beg
'occur-prefix nil
1121 (setq col
(- (point) line-beg
))
1122 (buffer-substring-no-properties (point) line-end
))))
1123 (with-selected-window win
1127 (message "Buffer `%s' is read only." buf
)
1128 (delete-region (line-beginning-position) (line-end-position))
1130 (move-to-column col
)))))))
1133 (defun occur-revert-function (_ignore1 _ignore2
)
1134 "Handle `revert-buffer' for Occur mode buffers."
1135 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
1137 (defun occur-mode-find-occurrence ()
1138 (let ((pos (get-text-property (point) 'occur-target
)))
1140 (error "No occurrence on this line"))
1141 (unless (buffer-live-p (marker-buffer pos
))
1142 (error "Buffer for this occurrence was killed"))
1145 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
1146 (defun occur-mode-goto-occurrence (&optional event
)
1147 "Go to the occurrence on the current line."
1148 (interactive (list last-nonmenu-event
))
1151 ;; Actually `event-end' works correctly with a nil argument as
1152 ;; well, so we could dispense with this test, but let's not
1153 ;; rely on this undocumented behavior.
1154 (occur-mode-find-occurrence)
1155 (with-current-buffer (window-buffer (posn-window (event-end event
)))
1157 (goto-char (posn-point (event-end event
)))
1158 (occur-mode-find-occurrence))))))
1159 (pop-to-buffer (marker-buffer pos
))
1161 (run-hooks 'occur-mode-find-occurrence-hook
)))
1163 (defun occur-mode-goto-occurrence-other-window ()
1164 "Go to the occurrence the current line describes, in another window."
1166 (let ((pos (occur-mode-find-occurrence)))
1167 (switch-to-buffer-other-window (marker-buffer pos
))
1169 (run-hooks 'occur-mode-find-occurrence-hook
)))
1171 (defun occur-mode-display-occurrence ()
1172 "Display in another window the occurrence the current line describes."
1174 (let ((pos (occur-mode-find-occurrence))
1176 (setq window
(display-buffer (marker-buffer pos
) t
))
1177 ;; This is the way to set point in the proper window.
1178 (save-selected-window
1179 (select-window window
)
1181 (run-hooks 'occur-mode-find-occurrence-hook
))))
1183 (defun occur-find-match (n search message
)
1184 (if (not n
) (setq n
1))
1187 (setq r
(funcall search
(point) 'occur-match
))
1189 (get-text-property r
'occur-match
)
1190 (setq r
(funcall search r
'occur-match
)))
1196 (defun occur-next (&optional n
)
1197 "Move to the Nth (default 1) next match in an Occur mode buffer."
1199 (occur-find-match n
#'next-single-property-change
"No more matches"))
1201 (defun occur-prev (&optional n
)
1202 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1204 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
1206 (defun occur-next-error (&optional argp reset
)
1207 "Move to the Nth (default 1) next match in an Occur mode buffer.
1208 Compatibility function for \\[next-error] invocations."
1210 ;; we need to run occur-find-match from within the Occur buffer
1211 (with-current-buffer
1212 ;; Choose the buffer and make it current.
1213 (if (next-error-buffer-p (current-buffer))
1215 (next-error-find-buffer nil nil
1217 (eq major-mode
'occur-mode
))))
1219 (goto-char (cond (reset (point-min))
1220 ((< argp
0) (line-beginning-position))
1221 ((> argp
0) (line-end-position))
1226 #'previous-single-property-change
1227 #'next-single-property-change
)
1229 ;; In case the *Occur* buffer is visible in a nonselected window.
1230 (let ((win (get-buffer-window (current-buffer) t
)))
1231 (if win
(set-window-point win
(point))))
1232 (occur-mode-goto-occurrence)))
1235 '((((class color
) (min-colors 88) (background light
))
1236 :background
"yellow1")
1237 (((class color
) (min-colors 88) (background dark
))
1238 :background
"RoyalBlue3")
1239 (((class color
) (min-colors 8) (background light
))
1240 :background
"yellow" :foreground
"black")
1241 (((class color
) (min-colors 8) (background dark
))
1242 :background
"blue" :foreground
"white")
1243 (((type tty
) (class mono
))
1245 (t :background
"gray"))
1246 "Face used to highlight matches permanently."
1250 (defcustom list-matching-lines-default-context-lines
0
1251 "Default number of context lines included around `list-matching-lines' matches.
1252 A negative number means to include that many lines before the match.
1253 A positive number means to include that many lines both before and after."
1257 (defalias 'list-matching-lines
'occur
)
1259 (defcustom list-matching-lines-face
'match
1260 "Face used by \\[list-matching-lines] to show the text that matches.
1261 If the value is nil, don't highlight the matching portions specially."
1265 (defcustom list-matching-lines-buffer-name-face
'underline
1266 "Face used by \\[list-matching-lines] to show the names of buffers.
1267 If the value is nil, don't highlight the buffer names specially."
1271 (defcustom list-matching-lines-prefix-face
'shadow
1272 "Face used by \\[list-matching-lines] to show the prefix column.
1273 If the face doesn't differ from the default face,
1274 don't highlight the prefix with line numbers specially."
1279 (defcustom occur-excluded-properties
1280 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1281 yank-handler follow-link
)
1282 "Text properties to discard when copying lines to the *Occur* buffer.
1283 The value should be a list of text properties to discard or t,
1284 which means to discard all text properties."
1285 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
1289 (defun occur-read-primary-args ()
1290 (let* ((perform-collect (consp current-prefix-arg
))
1291 (regexp (read-regexp (if perform-collect
1292 "Collect strings matching regexp"
1293 "List lines matching regexp")
1294 'regexp-history-last
)))
1297 ;; Perform collect operation
1298 (if (zerop (regexp-opt-depth regexp
))
1299 ;; No subexpression so collect the entire match.
1301 ;; Get the regexp for collection pattern.
1302 (let ((default (car occur-collect-regexp-history
)))
1304 (format "Regexp to collect (default %s): " default
)
1305 default
'occur-collect-regexp-history
)))
1306 ;; Otherwise normal occur takes numerical prefix argument.
1307 (when current-prefix-arg
1308 (prefix-numeric-value current-prefix-arg
))))))
1310 (defun occur-rename-buffer (&optional unique-p interactive-p
)
1311 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1312 Here `original-buffer-name' is the buffer name where Occur was originally run.
1313 When given the prefix argument, or called non-interactively, the renaming
1314 will not clobber the existing buffer(s) of that name, but use
1315 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1316 if you always want a separate *Occur* buffer for each buffer where you
1318 (interactive "P\np")
1319 (with-current-buffer
1320 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
1321 (rename-buffer (concat "*Occur: "
1322 (mapconcat #'buffer-name
1323 (car (cddr occur-revert-arguments
)) "/")
1325 (or unique-p
(not interactive-p
)))))
1327 (defun occur (regexp &optional nlines
)
1328 "Show all lines in the current buffer containing a match for REGEXP.
1329 If a match spreads across multiple lines, all those lines are shown.
1331 Each line is displayed with NLINES lines before and after, or -NLINES
1332 before if NLINES is negative.
1333 NLINES defaults to `list-matching-lines-default-context-lines'.
1334 Interactively it is the prefix arg.
1336 The lines are shown in a buffer named `*Occur*'.
1337 It serves as a menu to find any of the occurrences in this buffer.
1338 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1340 If REGEXP contains upper case characters (excluding those preceded by `\\')
1341 and `search-upper-case' is non-nil, the matching is case-sensitive.
1343 When NLINES is a string or when the function is called
1344 interactively with prefix argument without a number (`C-u' alone
1345 as prefix) the matching strings are collected into the `*Occur*'
1346 buffer by using NLINES as a replacement regexp. NLINES may
1347 contain \\& and \\N which convention follows `replace-match'.
1348 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1349 \"\\1\" for NLINES collects all the function names in a lisp
1350 program. When there is no parenthesized subexpressions in REGEXP
1351 the entire match is collected. In any case the searched buffer
1353 (interactive (occur-read-primary-args))
1354 (occur-1 regexp nlines
(list (current-buffer))))
1356 (defvar ido-ignore-item-temp-list
)
1358 (defun multi-occur (bufs regexp
&optional nlines
)
1359 "Show all lines in buffers BUFS containing a match for REGEXP.
1360 This function acts on multiple buffers; otherwise, it is exactly like
1361 `occur'. When you invoke this command interactively, you must specify
1362 the buffer names that you want, one by one.
1363 See also `multi-occur-in-matching-buffers'."
1366 (let* ((bufs (list (read-buffer "First buffer to search: "
1367 (current-buffer) t
)))
1369 (ido-ignore-item-temp-list bufs
))
1370 (while (not (string-equal
1371 (setq buf
(read-buffer
1372 (if (eq read-buffer-function
#'ido-read-buffer
)
1373 "Next buffer to search (C-j to end): "
1374 "Next buffer to search (RET to end): ")
1377 (add-to-list 'bufs buf
)
1378 (setq ido-ignore-item-temp-list bufs
))
1379 (nreverse (mapcar #'get-buffer bufs
)))
1380 (occur-read-primary-args)))
1381 (occur-1 regexp nlines bufs
))
1383 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1384 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1385 Normally BUFREGEXP matches against each buffer's visited file name,
1386 but if you specify a prefix argument, it matches against the buffer name.
1387 See also `multi-occur'."
1390 (let* ((default (car regexp-history
))
1393 (if current-prefix-arg
1394 "List lines in buffers whose names match regexp: "
1395 "List lines in buffers whose filenames match regexp: "))))
1396 (if (equal input
"")
1399 (occur-read-primary-args)))
1403 (mapcar (lambda (buf)
1405 (string-match bufregexp
1407 (and (buffer-file-name buf
)
1408 (string-match bufregexp
1409 (buffer-file-name buf
))))
1413 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1414 (unless (and regexp
(not (equal regexp
"")))
1415 (error "Occur doesn't work with the empty regexp"))
1417 (setq buf-name
"*Occur*"))
1419 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1420 (when (buffer-live-p buf
) buf
))
1422 ;; Handle the case where one of the buffers we're searching is the
1423 ;; output buffer. Just rename it.
1424 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1425 (with-current-buffer (get-buffer buf-name
)
1428 ;; Now find or create the output buffer.
1429 ;; If we just renamed that buffer, we will make a new one here.
1430 (setq occur-buf
(get-buffer-create buf-name
))
1432 (with-current-buffer occur-buf
1433 (if (stringp nlines
)
1434 (fundamental-mode) ;; This is for collect operation.
1436 (let ((inhibit-read-only t
)
1437 ;; Don't generate undo entries for creation of the initial contents.
1438 (buffer-undo-list t
))
1441 (if (stringp nlines
)
1442 ;; Treat nlines as a regexp to collect.
1443 (let ((bufs active-bufs
)
1446 (with-current-buffer (car bufs
)
1448 (goto-char (point-min))
1449 (while (re-search-forward regexp nil t
)
1450 ;; Insert the replacement regexp.
1451 (let ((str (match-substitute-replacement nlines
)))
1453 (with-current-buffer occur-buf
1455 (setq count
(1+ count
))
1456 (or (zerop (current-column))
1457 (insert "\n"))))))))
1458 (setq bufs
(cdr bufs
)))
1460 ;; Perform normal occur.
1462 regexp active-bufs occur-buf
1463 (or nlines list-matching-lines-default-context-lines
)
1464 (if (and case-fold-search search-upper-case
)
1465 (isearch-no-upper-case-p regexp t
)
1467 list-matching-lines-buffer-name-face
1468 (if (face-differs-from-default-p list-matching-lines-prefix-face
)
1469 list-matching-lines-prefix-face
)
1470 list-matching-lines-face
1471 (not (eq occur-excluded-properties t
))))))
1472 (let* ((bufcount (length active-bufs
))
1473 (diff (- (length bufs
) bufcount
)))
1474 (message "Searched %d buffer%s%s; %s match%s%s"
1475 bufcount
(if (= bufcount
1) "" "s")
1476 (if (zerop diff
) "" (format " (%d killed)" diff
))
1477 (if (zerop count
) "no" (format "%d" count
))
1478 (if (= count
1) "" "es")
1479 ;; Don't display regexp if with remaining text
1480 ;; it is longer than window-width.
1481 (if (> (+ (length regexp
) 42) (window-width))
1482 "" (format " for `%s'" (query-replace-descr regexp
)))))
1483 (setq occur-revert-arguments
(list regexp nlines bufs
))
1485 (kill-buffer occur-buf
)
1486 (display-buffer occur-buf
)
1487 (setq next-error-last-buffer occur-buf
)
1488 (setq buffer-read-only t
)
1489 (set-buffer-modified-p nil
)
1490 (run-hooks 'occur-hook
)))))))
1492 (defun occur-engine (regexp buffers out-buf nlines case-fold
1493 title-face prefix-face match-face keep-props
)
1494 (with-current-buffer out-buf
1495 (let ((global-lines 0) ;; total count of matching lines
1496 (global-matches 0) ;; total count of matches
1498 (case-fold-search case-fold
))
1499 ;; Map over all the buffers
1500 (dolist (buf buffers
)
1501 (when (buffer-live-p buf
)
1502 (let ((lines 0) ;; count of matching lines
1503 (matches 0) ;; count of matches
1504 (curr-line 1) ;; line count
1505 (prev-line nil
) ;; line number of prev match endpt
1506 (prev-after-lines nil
) ;; context lines of prev match
1514 (inhibit-field-text-motion t
)
1515 (headerpt (with-current-buffer out-buf
(point))))
1516 (with-current-buffer buf
1518 ;; Set CODING only if the current buffer locally
1519 ;; binds buffer-file-coding-system.
1520 (not (local-variable-p 'buffer-file-coding-system
))
1521 (setq coding buffer-file-coding-system
))
1523 (goto-char (point-min)) ;; begin searching in the buffer
1525 (setq origpt
(point))
1526 (when (setq endpt
(re-search-forward regexp nil t
))
1527 (setq lines
(1+ lines
)) ;; increment matching lines count
1528 (setq matchbeg
(match-beginning 0))
1529 ;; Get beginning of first match line and end of the last.
1531 (goto-char matchbeg
)
1532 (setq begpt
(line-beginning-position))
1534 (setq endpt
(line-end-position)))
1535 ;; Sum line numbers up to the first match line.
1536 (setq curr-line
(+ curr-line
(count-lines origpt begpt
)))
1537 (setq marker
(make-marker))
1538 (set-marker marker matchbeg
)
1539 (setq curstring
(occur-engine-line begpt endpt keep-props
))
1540 ;; Highlight the matches
1541 (let ((len (length curstring
))
1543 (while (and (< start len
)
1544 (string-match regexp curstring start
))
1545 (setq matches
(1+ matches
))
1546 (add-text-properties
1547 (match-beginning 0) (match-end 0)
1548 '(occur-match t
) curstring
)
1550 ;; Add `match-face' to faces copied from the buffer.
1551 (add-face-text-property
1552 (match-beginning 0) (match-end 0)
1553 match-face nil curstring
))
1554 ;; Avoid infloop (Bug#7593).
1555 (let ((end (match-end 0)))
1556 (setq start
(if (= start end
) (1+ start
) end
)))))
1557 ;; Generate the string to insert for this match
1558 (let* ((match-prefix
1559 ;; Using 7 digits aligns tabs properly.
1560 (apply #'propertize
(format "%7d:" curr-line
)
1563 `(font-lock-face ,prefix-face
))
1564 `(occur-prefix t mouse-face
(highlight)
1565 ;; Allow insertion of text at
1566 ;; the end of the prefix (for
1567 ;; Occur Edit mode).
1568 front-sticky t rear-nonsticky t
1569 occur-target
,marker follow-link t
1570 help-echo
"mouse-2: go to this occurrence"))))
1572 ;; We don't put `mouse-face' on the newline,
1573 ;; because that loses. And don't put it
1574 ;; on context lines to reduce flicker.
1575 (propertize curstring
'mouse-face
(list 'highlight
)
1576 'occur-target marker
1579 "mouse-2: go to this occurrence"))
1583 ;; Add non-numeric prefix to all non-first lines
1584 ;; of multi-line matches.
1585 (replace-regexp-in-string
1588 (propertize "\n :" 'font-lock-face prefix-face
)
1591 ;; Add marker at eol, but no mouse props.
1592 (propertize "\n" 'occur-target marker
)))
1595 ;; The simple display style
1597 ;; The complex multi-line display style.
1598 (setq ret
(occur-context-lines
1599 out-line nlines keep-props begpt endpt
1600 curr-line prev-line prev-after-lines
1602 ;; Set first elem of the returned list to `data',
1603 ;; and the second elem to `prev-after-lines'.
1604 (setq prev-after-lines
(nth 1 ret
))
1606 ;; Actually insert the match display data
1607 (with-current-buffer out-buf
1612 ;; Sum line numbers between first and last match lines.
1613 (setq curr-line
(+ curr-line
(count-lines begpt endpt
)
1614 ;; Add 1 for empty last match line since
1615 ;; count-lines returns 1 line less.
1616 (if (and (bolp) (eolp)) 1 0)))
1617 ;; On to the next match...
1619 (goto-char (point-max)))
1620 (setq prev-line
(1- curr-line
)))
1621 ;; Flush remaining context after-lines.
1622 (when prev-after-lines
1623 (with-current-buffer out-buf
1624 (insert (apply #'concat
(occur-engine-add-prefix
1625 prev-after-lines prefix-face
)))))))
1626 (when (not (zerop lines
)) ;; is the count zero?
1627 (setq global-lines
(+ global-lines lines
)
1628 global-matches
(+ global-matches matches
))
1629 (with-current-buffer out-buf
1630 (goto-char headerpt
)
1634 (format "%d match%s%s%s in buffer: %s\n"
1635 matches
(if (= matches
1) "" "es")
1636 ;; Don't display the same number of lines
1637 ;; and matches in case of 1 match per line.
1638 (if (= lines matches
)
1639 "" (format " in %d line%s"
1640 lines
(if (= lines
1) "" "s")))
1641 ;; Don't display regexp for multi-buffer.
1642 (if (> (length buffers
) 1)
1643 "" (format " for \"%s\""
1644 (query-replace-descr regexp
)))
1648 (add-text-properties beg end
`(occur-title ,buf
))
1650 (add-face-text-property beg end title-face
)))
1651 (goto-char (point-min)))))))
1652 ;; Display total match count and regexp for multi-buffer.
1653 (when (and (not (zerop global-lines
)) (> (length buffers
) 1))
1654 (goto-char (point-min))
1657 (insert (format "%d match%s%s total for \"%s\":\n"
1658 global-matches
(if (= global-matches
1) "" "es")
1659 ;; Don't display the same number of lines
1660 ;; and matches in case of 1 match per line.
1661 (if (= global-lines global-matches
)
1662 "" (format " in %d line%s"
1663 global-lines
(if (= global-lines
1) "" "s")))
1664 (query-replace-descr regexp
)))
1667 (add-face-text-property beg end title-face
)))
1668 (goto-char (point-min)))
1670 ;; CODING is buffer-file-coding-system of the first buffer
1671 ;; that locally binds it. Let's use it also for the output
1673 (set-buffer-file-coding-system coding
))
1674 ;; Return the number of matches
1677 (defun occur-engine-line (beg end
&optional keep-props
)
1678 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
1679 (text-property-not-all beg end
'fontified t
))
1680 (if (fboundp 'jit-lock-fontify-now
)
1681 (jit-lock-fontify-now beg end
)))
1682 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1683 (let ((str (buffer-substring beg end
)))
1684 (remove-list-of-text-properties
1685 0 (length str
) occur-excluded-properties str
)
1687 (buffer-substring-no-properties beg end
)))
1689 (defun occur-engine-add-prefix (lines &optional prefix-face
)
1692 (concat (if prefix-face
1693 (propertize " :" 'font-lock-face prefix-face
)
1698 (defun occur-accumulate-lines (count &optional keep-props pt
)
1702 (let ((forwardp (> count
0))
1703 result beg end moved
)
1704 (while (not (or (zerop count
)
1707 (and (bobp) (not moved
)))))
1708 (setq count
(+ count
(if forwardp -
1 1)))
1709 (setq beg
(line-beginning-position)
1710 end
(line-end-position))
1711 (push (occur-engine-line beg end keep-props
) result
)
1712 (setq moved
(= 0 (forward-line (if forwardp
1 -
1)))))
1713 (nreverse result
))))
1715 ;; Generate context display for occur.
1716 ;; OUT-LINE is the line where the match is.
1717 ;; NLINES and KEEP-PROPS are args to occur-engine.
1718 ;; CURR-LINE is line count of the current match,
1719 ;; PREV-LINE is line count of the previous match,
1720 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1721 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1722 ;; then concatenate them all together.
1723 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1724 curr-line prev-line prev-after-lines
1725 &optional prefix-face
)
1726 ;; Find after- and before-context lines of the current match.
1728 (nreverse (cdr (occur-accumulate-lines
1729 (- (1+ (abs nlines
))) keep-props begpt
))))
1731 (cdr (occur-accumulate-lines
1732 (1+ nlines
) keep-props endpt
)))
1735 ;; Combine after-lines of the previous match
1736 ;; with before-lines of the current match.
1738 (when prev-after-lines
1739 ;; Don't overlap prev after-lines with current before-lines.
1740 (if (>= (+ prev-line
(length prev-after-lines
))
1741 (- curr-line
(length before-lines
)))
1742 (setq prev-after-lines
1743 (butlast prev-after-lines
1744 (- (length prev-after-lines
)
1745 (- curr-line prev-line
(length before-lines
) 1))))
1746 ;; Separate non-overlapping context lines with a dashed line.
1747 (setq separator
"-------\n")))
1750 ;; Don't overlap current before-lines with previous match line.
1751 (if (<= (- curr-line
(length before-lines
))
1754 (nthcdr (- (length before-lines
)
1755 (- curr-line prev-line
1))
1757 ;; Separate non-overlapping before-context lines.
1758 (unless (> nlines
0)
1759 (setq separator
"-------\n"))))
1762 ;; Return a list where the first element is the output line.
1765 (if prev-after-lines
1766 (occur-engine-add-prefix prev-after-lines prefix-face
))
1768 (list (if prefix-face
1769 (propertize separator
'font-lock-face prefix-face
)
1771 (occur-engine-add-prefix before-lines prefix-face
)
1773 ;; And the second element is the list of context after-lines.
1774 (if (> nlines
0) after-lines
))))
1777 ;; It would be nice to use \\[...], but there is no reasonable way
1778 ;; to make that display both SPC and Y.
1779 (defconst query-replace-help
1780 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1781 RET or `q' to exit, Period to replace one match and exit,
1782 Comma to replace but not move point immediately,
1783 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1784 C-w to delete match and recursive edit,
1785 C-l to clear the screen, redisplay, and offer same replacement again,
1786 ! to replace all remaining matches in this buffer with no more questions,
1787 ^ to move point back to previous match,
1788 E to edit the replacement string.
1789 In multi-buffer replacements type `Y' to replace all remaining
1790 matches in all remaining buffers with no more questions,
1791 `N' to skip to the next buffer without replacing remaining matches
1792 in the current buffer."
1793 "Help message while in `query-replace'.")
1795 (defvar query-replace-map
1796 (let ((map (make-sparse-keymap)))
1797 (define-key map
" " 'act
)
1798 (define-key map
"\d" 'skip
)
1799 (define-key map
[delete] 'skip)
1800 (define-key map [backspace] 'skip)
1801 (define-key map "y" 'act)
1802 (define-key map "n" 'skip)
1803 (define-key map "Y" 'act)
1804 (define-key map "N" 'skip)
1805 (define-key map "e" 'edit-replacement)
1806 (define-key map "E" 'edit-replacement)
1807 (define-key map "," 'act-and-show)
1808 (define-key map "q" 'exit)
1809 (define-key map "\r" 'exit)
1810 (define-key map [return] 'exit)
1811 (define-key map "." 'act-and-exit)
1812 (define-key map "\C-r" 'edit)
1813 (define-key map "\C-w" 'delete-and-edit)
1814 (define-key map "\C-l" 'recenter)
1815 (define-key map "!" 'automatic)
1816 (define-key map "^" 'backup)
1817 (define-key map "\C-h" 'help)
1818 (define-key map [f1] 'help)
1819 (define-key map [help] 'help)
1820 (define-key map "?" 'help)
1821 (define-key map "\C-g" 'quit)
1822 (define-key map "\C-]" 'quit)
1823 (define-key map "\C-v" 'scroll-up)
1824 (define-key map "\M-v" 'scroll-down)
1825 (define-key map [next] 'scroll-up)
1826 (define-key map [prior] 'scroll-down)
1827 (define-key map [?\C-\M-v] 'scroll-other-window)
1828 (define-key map [M-next] 'scroll-other-window)
1829 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1830 (define-key map [M-prior] 'scroll-other-window-down)
1831 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1832 ;; should check for ESC specially.
1833 ;; (define-key map "\e" 'exit-prefix)
1834 (define-key map [escape] 'exit-prefix)
1836 "Keymap of responses to questions posed by commands like `query-replace'.
1837 The \"bindings\" in this map are not commands; they are answers.
1838 The valid answers include `act', `skip', `act-and-show',
1839 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1840 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1841 `edit', `edit-replacement', `delete-and-edit', `automatic',
1842 `backup', `quit', and `help'.
1844 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1846 (defvar multi-query-replace-map
1847 (let ((map (make-sparse-keymap)))
1848 (set-keymap-parent map query-replace-map)
1849 (define-key map "Y" 'automatic-all)
1850 (define-key map "N" 'exit-current)
1852 "Keymap that defines additional bindings for multi-buffer replacements.
1853 It extends its parent map `query-replace-map' with new bindings to
1854 operate on a set of buffers/files. The difference with its parent map
1855 is the additional answers `automatic-all' to replace all remaining
1856 matches in all remaining buffers with no more questions, and
1857 `exit-current' to skip remaining matches in the current buffer
1858 and to continue with the next buffer in the sequence.")
1860 (defun replace-match-string-symbols (n)
1861 "Process a list (and any sub-lists), expanding certain symbols.
1863 N (match-string N) (where N is a string of digits)
1864 #N (string-to-number (match-string N))
1866 #& (string-to-number (match-string 0))
1869 Note that these symbols must be preceded by a backslash in order to
1870 type them using Lisp syntax."
1874 (replace-match-string-symbols (car n))) ;Process sub-list
1876 (let ((name (symbol-name (car n))))
1878 ((string-match "^[0-9]+$" name)
1879 (setcar n (list 'match-string (string-to-number name))))
1880 ((string-match "^#[0-9]+$" name)
1881 (setcar n (list 'string-to-number
1883 (string-to-number (substring name 1))))))
1885 (setcar n '(match-string 0)))
1886 ((string= "#&" name)
1887 (setcar n '(string-to-number (match-string 0))))
1889 (setcar n 'replace-count))))))
1892 (defun replace-eval-replacement (expression count)
1893 (let* ((replace-count count)
1899 (error "Error evaluating replacement expression: %S" err)))))
1900 (if (stringp replacement)
1902 (prin1-to-string replacement t))))
1904 (defun replace-quote (replacement)
1905 "Quote a replacement string.
1906 This just doubles all backslashes in REPLACEMENT and
1907 returns the resulting string. If REPLACEMENT is not
1908 a string, it is first passed through `prin1-to-string'
1909 with the `noescape' argument set.
1911 `match-data' is preserved across the call."
1913 (replace-regexp-in-string "\\\\" "\\\\"
1914 (if (stringp replacement)
1916 (prin1-to-string replacement t))
1919 (defun replace-loop-through-replacements (data count)
1920 ;; DATA is a vector containing the following values:
1921 ;; 0 next-rotate-count
1923 ;; 2 next-replacement
1925 (if (= (aref data 0) count)
1927 (aset data 0 (+ count (aref data 1)))
1928 (let ((next (cdr (aref data 2))))
1929 (aset data 2 (if (consp next) next (aref data 3))))))
1930 (car (aref data 2)))
1932 (defun replace-match-data (integers reuse &optional new)
1933 "Like `match-data', but markers in REUSE get invalidated.
1934 If NEW is non-nil, it is set and returned instead of fresh data,
1935 but coerced to the correct value of INTEGERS."
1938 (set-match-data new)
1940 (eq (null integers) (markerp (car reuse)))
1942 (match-data integers reuse t)))
1944 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data backward)
1945 "Make a replacement with `replace-match', editing `\\?'.
1946 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
1947 After possibly editing it (if `\\?' is present), NEWTEXT is also
1948 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
1949 is made (to save time). MATCH-DATA is used for the replacement.
1950 In case editing is done, it is changed to use markers.
1952 The return value is non-nil if there has been no `\\?' or NOEDIT was
1953 passed in. If LITERAL is set, no checking is done, anyway."
1954 (unless (or literal noedit)
1956 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1959 (read-string "Edit replacement string: "
1962 (replace-match "" t t newtext 3)
1963 (1+ (match-beginning 3)))
1966 nil match-data match-data))))
1968 (set-match-data match-data)
1969 (replace-match newtext fixedcase literal)
1970 ;; `replace-match' leaves point at the end of the replacement text,
1971 ;; so move point to the beginning when replacing backward.
1972 (when backward (goto-char (nth 0 match-data)))
1975 (defvar replace-search-function nil
1976 "Function to use when searching for strings to replace.
1977 It is used by `query-replace' and `replace-string', and is called
1978 with three arguments, as if it were `search-forward'.")
1980 (defvar replace-re-search-function nil
1981 "Function to use when searching for regexps to replace.
1982 It is used by `query-replace-regexp', `replace-regexp',
1983 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1984 It is called with three arguments, as if it were
1985 `re-search-forward'.")
1987 (defun replace-search (search-string limit regexp-flag delimited-flag
1988 case-fold-search backward)
1989 "Search for the next occurrence of SEARCH-STRING to replace."
1990 ;; Let-bind global isearch-* variables to values used
1991 ;; to search the next replacement. These let-bindings
1992 ;; should be effective both at the time of calling
1993 ;; `isearch-search-fun-default' and also at the
1994 ;; time of funcalling `search-function'.
1995 ;; These isearch-* bindings can't be placed higher
1996 ;; outside of this function because then another I-search
1997 ;; used after `recursive-edit' might override them.
1998 (let* ((isearch-regexp regexp-flag)
1999 (isearch-word delimited-flag)
2000 (isearch-lax-whitespace
2001 replace-lax-whitespace)
2002 (isearch-regexp-lax-whitespace
2003 replace-regexp-lax-whitespace)
2004 (isearch-case-fold-search case-fold-search)
2005 (isearch-adjusted nil)
2006 (isearch-nonincremental t) ; don't use lax word mode
2007 (isearch-forward (not backward))
2010 replace-re-search-function
2011 replace-search-function)
2012 (isearch-search-fun-default))))
2013 (funcall search-function search-string limit t)))
2015 (defvar replace-overlay nil)
2017 (defun replace-highlight (match-beg match-end range-beg range-end
2018 search-string regexp-flag delimited-flag
2019 case-fold-search backward)
2020 (if query-replace-highlight
2022 (move-overlay replace-overlay match-beg match-end (current-buffer))
2023 (setq replace-overlay (make-overlay match-beg match-end))
2024 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2025 (overlay-put replace-overlay 'face 'query-replace)))
2026 (if query-replace-lazy-highlight
2027 (let ((isearch-string search-string)
2028 (isearch-regexp regexp-flag)
2029 (isearch-word delimited-flag)
2030 (isearch-lax-whitespace
2031 replace-lax-whitespace)
2032 (isearch-regexp-lax-whitespace
2033 replace-regexp-lax-whitespace)
2034 (isearch-case-fold-search case-fold-search)
2035 (isearch-forward (not backward))
2036 (isearch-other-end match-beg)
2037 (isearch-error nil))
2038 (isearch-lazy-highlight-new-loop range-beg range-end))))
2040 (defun replace-dehighlight ()
2041 (when replace-overlay
2042 (delete-overlay replace-overlay))
2043 (when query-replace-lazy-highlight
2044 (lazy-highlight-cleanup lazy-highlight-cleanup)
2045 (setq isearch-lazy-highlight-last-string nil))
2046 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2047 (isearch-clean-overlays))
2049 (defun perform-replace (from-string replacements
2050 query-flag regexp-flag delimited-flag
2051 &optional repeat-count map start end backward)
2052 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2053 Don't use this in your own program unless you want to query and set the mark
2054 just as `query-replace' does. Instead, write a simple loop like this:
2056 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2057 (replace-match \"foobar\" nil nil))
2059 which will run faster and probably do exactly what you want. Please
2060 see the documentation of `replace-match' to find out how to simulate
2063 This function returns nil if and only if there were no matches to
2064 make, or the user didn't cancel the call."
2065 (or map (setq map query-replace-map))
2066 (and query-flag minibuffer-auto-raise
2067 (raise-frame (window-frame (minibuffer-window))))
2068 (let* ((case-fold-search
2069 (if (and case-fold-search search-upper-case)
2070 (isearch-no-upper-case-p from-string regexp-flag)
2072 (nocasify (not (and case-replace case-fold-search)))
2073 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2074 (search-string from-string)
2075 (real-match-data nil) ; The match data for the current match.
2076 (next-replacement nil)
2077 ;; This is non-nil if we know there is nothing for the user
2078 ;; to edit in the replacement.
2083 (skip-read-only-count 0)
2084 (skip-filtered-count 0)
2085 (skip-invisible-count 0)
2086 (nonempty-match nil)
2088 (recenter-last-op nil) ; Start cycling order with initial position.
2090 ;; If non-nil, it is marker saying where in the buffer to stop.
2093 ;; Data for the next match. If a cons, it has the same format as
2094 ;; (match-data); otherwise it is t if a match is possible at point.
2100 (substitute-command-keys
2101 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2102 minibuffer-prompt-properties))))
2104 ;; If region is active, in Transient Mark mode, operate on region.
2107 (setq limit (copy-marker (min start end)))
2108 (goto-char (max start end))
2111 (setq limit (copy-marker (max start end)))
2112 (goto-char (min start end))
2115 ;; If last typed key in previous call of multi-buffer perform-replace
2116 ;; was `automatic-all', don't ask more questions in next files
2117 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2118 (setq query-flag nil multi-buffer t))
2120 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
2121 ;; containing a function and its first argument. The function is
2122 ;; called to generate each replacement like this:
2123 ;; (funcall (car replacements) (cdr replacements) replace-count)
2124 ;; It must return a string.
2126 ((stringp replacements)
2127 (setq next-replacement replacements
2129 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2130 (or repeat-count (setq repeat-count 1))
2131 (setq replacements (cons 'replace-loop-through-replacements
2132 (vector repeat-count repeat-count
2133 replacements replacements)))))
2135 (when query-replace-lazy-highlight
2136 (setq isearch-lazy-highlight-last-string nil))
2141 ;; Loop finding occurrences that perhaps should be replaced.
2142 (while (and keep-going
2144 (not (or (bobp) (and limit (<= (point) limit))))
2145 (not (or (eobp) (and limit (>= (point) limit)))))
2146 ;; Use the next match if it is already known;
2147 ;; otherwise, search for a match after moving forward
2148 ;; one char if progress is required.
2149 (setq real-match-data
2150 (cond ((consp match-again)
2151 (goto-char (if backward
2153 (nth 1 match-again)))
2155 t real-match-data match-again))
2156 ;; MATCH-AGAIN non-nil means accept an
2160 (replace-search search-string limit
2161 regexp-flag delimited-flag
2162 case-fold-search backward)
2163 ;; For speed, use only integers and
2164 ;; reuse the list used last time.
2165 (replace-match-data t real-match-data)))
2167 (> (1- (point)) (point-min))
2168 (< (1+ (point)) (point-max)))
2171 (> (1- (point)) limit)
2172 (< (1+ (point)) limit))))
2173 ;; If not accepting adjacent matches,
2174 ;; move one char to the right before
2175 ;; searching again. Undo the motion
2176 ;; if the search fails.
2177 (let ((opoint (point)))
2178 (forward-char (if backward -1 1))
2179 (if (replace-search search-string limit
2180 regexp-flag delimited-flag
2181 case-fold-search backward)
2187 ;; Record whether the match is nonempty, to avoid an infinite loop
2188 ;; repeatedly matching the same empty string.
2189 (setq nonempty-match
2190 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2192 ;; If the match is empty, record that the next one can't be
2195 ;; Otherwise, if matching a regular expression, do the next
2196 ;; match now, since the replacement for this match may
2197 ;; affect whether the next match is adjacent to this one.
2198 ;; If that match is empty, don't use it.
2201 (or (not regexp-flag)
2203 (looking-back search-string)
2204 (looking-at search-string))
2205 (let ((match (match-data)))
2206 (and (/= (nth 0 match) (nth 1 match))
2210 ;; Optionally ignore matches that have a read-only property.
2211 ((not (or (not query-replace-skip-read-only)
2212 (not (text-property-not-all
2213 (nth 0 real-match-data) (nth 1 real-match-data)
2215 (setq skip-read-only-count (1+ skip-read-only-count)))
2216 ;; Optionally filter out matches.
2217 ((not (funcall isearch-filter-predicate
2218 (nth 0 real-match-data) (nth 1 real-match-data)))
2219 (setq skip-filtered-count (1+ skip-filtered-count)))
2220 ;; Optionally ignore invisible matches.
2221 ((not (or (eq search-invisible t)
2222 ;; Don't open overlays for automatic replacements.
2223 (and (not query-flag) search-invisible)
2224 ;; Open hidden overlays for interactive replacements.
2225 (not (isearch-range-invisible
2226 (nth 0 real-match-data) (nth 1 real-match-data)))))
2227 (setq skip-invisible-count (1+ skip-invisible-count)))
2229 ;; Calculate the replacement string, if necessary.
2231 (set-match-data real-match-data)
2232 (setq next-replacement
2233 (funcall (car replacements) (cdr replacements)
2235 (if (not query-flag)
2237 (unless (or literal noedit)
2239 (nth 0 real-match-data) (nth 1 real-match-data)
2240 start end search-string
2241 regexp-flag delimited-flag case-fold-search backward))
2243 (replace-match-maybe-edit
2244 next-replacement nocasify literal
2245 noedit real-match-data backward)
2246 replace-count (1+ replace-count)))
2248 (let (done replaced key def)
2249 ;; Loop reading commands until one of them sets done,
2250 ;; which means it has finished handling this
2251 ;; occurrence. Any command that sets `done' should
2252 ;; leave behind proper match data for the stack.
2253 ;; Commands not setting `done' need to adjust
2254 ;; `real-match-data'.
2256 (set-match-data real-match-data)
2258 (match-beginning 0) (match-end 0)
2259 start end search-string
2260 regexp-flag delimited-flag case-fold-search backward)
2261 ;; Bind message-log-max so we don't fill up the message log
2262 ;; with a bunch of identical messages.
2263 (let ((message-log-max nil)
2264 (replacement-presentation
2265 (if query-replace-show-replacement
2267 (set-match-data real-match-data)
2268 (match-substitute-replacement next-replacement
2272 (query-replace-descr from-string)
2273 (query-replace-descr replacement-presentation)))
2274 (setq key (read-event))
2275 ;; Necessary in case something happens during read-event
2276 ;; that clobbers the match data.
2277 (set-match-data real-match-data)
2278 (setq key (vector key))
2279 (setq def (lookup-key map key))
2280 ;; Restore the match data while we process the command.
2281 (cond ((eq def 'help)
2282 (with-output-to-temp-buffer "*Help*"
2284 (concat "Query replacing "
2286 (or (and (symbolp delimited-flag)
2287 (get delimited-flag 'isearch-message-prefix))
2289 (if regexp-flag "regexp " "")
2290 (if backward "backward " "")
2291 from-string " with "
2292 next-replacement ".\n\n"
2293 (substitute-command-keys
2294 query-replace-help)))
2295 (with-current-buffer standard-output
2298 (setq keep-going nil)
2300 ((eq def 'exit-current)
2301 (setq multi-buffer t keep-going nil done t))
2304 (let ((elt (pop stack)))
2305 (goto-char (nth 0 elt))
2306 (setq replaced (nth 1 elt)
2311 (message "No previous match")
2312 (ding 'no-terminate)
2317 (replace-match-maybe-edit
2318 next-replacement nocasify literal
2319 noedit real-match-data backward)
2320 replace-count (1+ replace-count)))
2321 (setq done t replaced t))
2322 ((eq def 'act-and-exit)
2325 (replace-match-maybe-edit
2326 next-replacement nocasify literal
2327 noedit real-match-data backward)
2328 replace-count (1+ replace-count)))
2329 (setq keep-going nil)
2330 (setq done t replaced t))
2331 ((eq def 'act-and-show)
2334 (replace-match-maybe-edit
2335 next-replacement nocasify literal
2336 noedit real-match-data backward)
2337 replace-count (1+ replace-count)
2338 real-match-data (replace-match-data
2341 ((or (eq def 'automatic) (eq def 'automatic-all))
2344 (replace-match-maybe-edit
2345 next-replacement nocasify literal
2346 noedit real-match-data backward)
2347 replace-count (1+ replace-count)))
2348 (setq done t query-flag nil replaced t)
2349 (if (eq def 'automatic-all) (setq multi-buffer t)))
2353 ;; `this-command' has the value `query-replace',
2354 ;; so we need to bind it to `recenter-top-bottom'
2355 ;; to allow it to detect a sequence of `C-l'.
2356 (let ((this-command 'recenter-top-bottom)
2357 (last-command 'recenter-top-bottom))
2358 (recenter-top-bottom)))
2360 (let ((opos (point-marker)))
2361 (setq real-match-data (replace-match-data
2364 (goto-char (match-beginning 0))
2366 (save-window-excursion
2369 (set-marker opos nil))
2370 ;; Before we make the replacement,
2371 ;; decide whether the search string
2372 ;; can match again just after this match.
2373 (if (and regexp-flag nonempty-match)
2374 (setq match-again (and (looking-at search-string)
2376 ;; Edit replacement.
2377 ((eq def 'edit-replacement)
2378 (setq real-match-data (replace-match-data
2382 (read-string "Edit replacement string: "
2386 (set-match-data real-match-data)
2388 (replace-match-maybe-edit
2389 next-replacement nocasify literal noedit
2390 real-match-data backward)
2394 ((eq def 'delete-and-edit)
2395 (replace-match "" t t)
2396 (setq real-match-data (replace-match-data
2397 nil real-match-data))
2398 (replace-dehighlight)
2399 (save-excursion (recursive-edit))
2401 ;; Note: we do not need to treat `exit-prefix'
2402 ;; specially here, since we reread
2403 ;; any unrecognized character.
2405 (setq this-command 'mode-exited)
2406 (setq keep-going nil)
2407 (setq unread-command-events
2408 (append (listify-key-sequence key)
2409 unread-command-events))
2411 (when query-replace-lazy-highlight
2412 ;; Force lazy rehighlighting only after replacements.
2413 (if (not (memq def '(skip backup)))
2414 (setq isearch-lazy-highlight-last-string nil)))
2415 (unless (eq def 'recenter)
2416 ;; Reset recenter cycling order to initial position.
2417 (setq recenter-last-op nil)))
2418 ;; Record previous position for ^ when we move on.
2419 ;; Change markers to numbers in the match data
2420 ;; since lots of markers slow down editing.
2421 (push (list (point) replaced
2422 ;;; If the replacement has already happened, all we need is the
2423 ;;; current match start and end. We could get this with a trivial
2425 ;;; (save-excursion (goto-char (match-beginning 0))
2426 ;;; (search-forward (match-string 0))
2428 ;;; if we really wanted to avoid manually constructing match data.
2429 ;;; Adding current-buffer is necessary so that match-data calls can
2430 ;;; return markers which are appropriate for editing.
2439 (replace-dehighlight))
2440 (or unread-command-events
2441 (message "Replaced %d occurrence%s%s"
2443 (if (= replace-count 1) "" "s")
2444 (if (> (+ skip-read-only-count
2446 skip-invisible-count) 0)
2447 (format " (skipped %s)"
2451 (if (> skip-read-only-count 0)
2452 (format "%s read-only"
2453 skip-read-only-count))
2454 (if (> skip-invisible-count 0)
2455 (format "%s invisible"
2456 skip-invisible-count))
2457 (if (> skip-filtered-count 0)
2458 (format "%s filtered out"
2459 skip-filtered-count))))
2462 (or (and keep-going stack) multi-buffer)))
2464 ;;; replace.el ends here