1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2013
4 ;; Free Software Foundation, Inc.
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 cons cell (FROM-STRING . TO-STRING), or nil if there is
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-history-variable
'query-replace-history
71 "History list to use for the FROM argument of `query-replace' commands.
72 The value of this variable should be a symbol; that symbol
73 is used as a variable to hold a history list for the strings
74 or patterns to be replaced."
79 (defcustom query-replace-to-history-variable
'query-replace-history
80 "History list to use for the TO argument of `query-replace' commands.
81 The value of this variable should be a symbol; that symbol
82 is used as a variable to hold a history list for replacement
88 (defcustom query-replace-skip-read-only nil
89 "Non-nil means `query-replace' and friends ignore read-only matches."
94 (defcustom query-replace-show-replacement t
95 "Non-nil means to show what actual replacement text will be."
100 (defcustom query-replace-highlight t
101 "Non-nil means to highlight matches during query replacement."
105 (defcustom query-replace-lazy-highlight t
106 "Controls the lazy-highlighting during query replacements.
107 When non-nil, all text in the buffer matching the current match
108 is highlighted lazily using isearch lazy highlighting (see
109 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
111 :group
'lazy-highlight
115 (defface query-replace
116 '((t (:inherit isearch
)))
117 "Face for highlighting query replacement matches."
121 (defvar replace-count
0
122 "Number of replacements done so far.
123 See `replace-regexp' and `query-replace-regexp-eval'.")
125 (defun query-replace-descr (string)
126 (mapconcat 'isearch-text-char-description string
""))
128 (defun query-replace-read-from (prompt regexp-flag
)
129 "Query and return the `from' argument of a query-replace operation.
130 The return value can also be a pair (FROM . TO) indicating that the user
131 wants to replace FROM with TO."
132 (if query-replace-interactive
133 (car (if regexp-flag regexp-search-ring search-ring
))
134 (let* ((history-add-new-input nil
)
136 (if query-replace-defaults
137 (format "%s (default %s -> %s): " prompt
138 (query-replace-descr (car query-replace-defaults
))
139 (query-replace-descr (cdr query-replace-defaults
)))
140 (format "%s: " prompt
)))
142 ;; The save-excursion here is in case the user marks and copies
143 ;; a region in order to specify the minibuffer input.
144 ;; That should not clobber the region for the query-replace itself.
147 (read-regexp prompt nil query-replace-from-history-variable
)
148 (read-from-minibuffer
149 prompt nil nil nil query-replace-from-history-variable
150 (car (if regexp-flag regexp-search-ring search-ring
)) t
)))))
151 (if (and (zerop (length from
)) query-replace-defaults
)
152 (cons (car query-replace-defaults
)
153 (query-replace-compile-replacement
154 (cdr query-replace-defaults
) regexp-flag
))
155 (add-to-history query-replace-from-history-variable from nil t
)
156 ;; Warn if user types \n or \t, but don't reject the input.
158 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
159 (let ((match (match-string 3 from
)))
161 ((string= match
"\\n")
162 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
163 ((string= match
"\\t")
164 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
168 (defun query-replace-compile-replacement (to regexp-flag
)
169 "Maybe convert a regexp replacement TO to Lisp.
170 Returns a list suitable for `perform-replace' if necessary,
171 the original string if not."
173 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
))
177 (setq pos
(match-end 0))
178 (push (substring to
0 (- pos
2)) list
)
179 (setq char
(aref to
(1- pos
))
180 to
(substring to pos
))
182 (push '(number-to-string replace-count
) list
))
184 (setq pos
(read-from-string to
))
185 (push `(replace-quote ,(car pos
)) list
)
187 ;; Swallow a space after a symbol
188 ;; if there is a space.
189 (if (and (or (symbolp (car pos
))
190 ;; Swallow a space after 'foo
191 ;; but not after (quote foo).
192 (and (eq (car-safe (car pos
)) 'quote
)
193 (not (= ?\
( (aref to
0)))))
194 (eq (string-match " " to
(cdr pos
))
198 (setq to
(substring to end
)))))
199 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
)))
200 (setq to
(nreverse (delete "" (cons to list
))))
201 (replace-match-string-symbols to
)
202 (cons 'replace-eval-replacement
209 (defun query-replace-read-to (from prompt regexp-flag
)
210 "Query and return the `to' argument of a query-replace operation."
211 (query-replace-compile-replacement
213 (let* ((history-add-new-input nil
)
214 (to (read-from-minibuffer
215 (format "%s %s with: " prompt
(query-replace-descr from
))
217 query-replace-to-history-variable from t
)))
218 (add-to-history query-replace-to-history-variable to nil t
)
219 (setq query-replace-defaults
(cons from to
))
223 (defun query-replace-read-args (prompt regexp-flag
&optional noerror
)
225 (barf-if-buffer-read-only))
226 (let* ((from (query-replace-read-from prompt regexp-flag
))
227 (to (if (consp from
) (prog1 (cdr from
) (setq from
(car from
)))
228 (query-replace-read-to from prompt regexp-flag
))))
230 (and current-prefix-arg
(not (eq current-prefix-arg
'-
)))
231 (and current-prefix-arg
(eq current-prefix-arg
'-
)))))
233 (defun query-replace (from-string to-string
&optional delimited start end backward
)
234 "Replace some occurrences of FROM-STRING with TO-STRING.
235 As each match is found, the user must type a character saying
236 what to do with it. For directions, type \\[help-command] at that time.
238 In Transient Mark mode, if the mark is active, operate on the contents
239 of the region. Otherwise, operate from point to the end of the buffer.
241 Use \\<minibuffer-local-map>\\[next-history-element] \
242 to pull the last incremental search string to the minibuffer
243 that reads FROM-STRING, or invoke replacements from
244 incremental search with a key sequence like `C-s C-s M-%'
245 to use its current search string as the string to replace.
247 Matching is independent of case if `case-fold-search' is non-nil and
248 FROM-STRING has no uppercase letters. Replacement transfers the case
249 pattern of the old text to the new text, if `case-replace' and
250 `case-fold-search' are non-nil and FROM-STRING has no uppercase
251 letters. (Transferring the case pattern means that if the old text
252 matched is all caps, or capitalized, then its replacement is upcased
255 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
256 ignore hidden matches if `search-invisible' is nil, and ignore more
257 matches using `isearch-filter-predicate'.
259 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
260 to be replaced will match a sequence of whitespace chars defined by the
261 regexp in `search-whitespace-regexp'.
263 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
264 only matches surrounded by word boundaries. A negative prefix arg means
267 Fourth and fifth arg START and END specify the region to operate on.
269 To customize possible responses, change the \"bindings\" in `query-replace-map'."
272 (query-replace-read-args
273 (concat "Query replace"
274 (if current-prefix-arg
275 (if (eq current-prefix-arg
'-
) " backward" " word")
277 (if (and transient-mark-mode mark-active
) " in region" ""))
279 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
280 ;; These are done separately here
281 ;; so that command-history will record these expressions
282 ;; rather than the values they had this time.
283 (if (and transient-mark-mode mark-active
)
285 (if (and transient-mark-mode mark-active
)
288 (perform-replace from-string to-string t nil delimited nil nil start end backward
))
290 (define-key esc-map
"%" 'query-replace
)
292 (defun query-replace-regexp (regexp to-string
&optional delimited start end backward
)
293 "Replace some things after point matching REGEXP with TO-STRING.
294 As each match is found, the user must type a character saying
295 what to do with it. For directions, type \\[help-command] at that time.
297 In Transient Mark mode, if the mark is active, operate on the contents
298 of the region. Otherwise, operate from point to the end of the buffer.
300 Use \\<minibuffer-local-map>\\[next-history-element] \
301 to pull the last incremental search regexp to the minibuffer
302 that reads REGEXP, or invoke replacements from
303 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
304 to use its current search regexp as the regexp to replace.
306 Matching is independent of case if `case-fold-search' is non-nil and
307 REGEXP has no uppercase letters. Replacement transfers the case
308 pattern of the old text to the new text, if `case-replace' and
309 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
310 \(Transferring the case pattern means that if the old text matched is
311 all caps, or capitalized, then its replacement is upcased or
314 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
315 ignore hidden matches if `search-invisible' is nil, and ignore more
316 matches using `isearch-filter-predicate'.
318 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
319 to be replaced will match a sequence of whitespace chars defined by the
320 regexp in `search-whitespace-regexp'.
322 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
323 only matches surrounded by word boundaries. A negative prefix arg means
326 Fourth and fifth arg START and END specify the region to operate on.
328 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
329 and `\\=\\N' (where N is a digit) stands for
330 whatever what matched the Nth `\\(...\\)' in REGEXP.
331 `\\?' lets you edit the replacement text in the minibuffer
332 at the given position for each replacement.
334 In interactive calls, the replacement text can contain `\\,'
335 followed by a Lisp expression. Each
336 replacement evaluates that expression to compute the replacement
337 string. Inside of that expression, `\\&' is a string denoting the
338 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
339 for the whole or a partial match converted to a number with
340 `string-to-number', and `\\#' itself for the number of replacements
341 done so far (starting with zero).
343 If the replacement expression is a symbol, write a space after it
344 to terminate it. One space there, if any, will be discarded.
346 When using those Lisp features interactively in the replacement
347 text, TO-STRING is actually made a list instead of a string.
348 Use \\[repeat-complex-command] after this command for details."
351 (query-replace-read-args
352 (concat "Query replace"
353 (if current-prefix-arg
354 (if (eq current-prefix-arg
'-
) " backward" " word")
357 (if (and transient-mark-mode mark-active
) " in region" ""))
359 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
360 ;; These are done separately here
361 ;; so that command-history will record these expressions
362 ;; rather than the values they had this time.
363 (if (and transient-mark-mode mark-active
)
365 (if (and transient-mark-mode mark-active
)
368 (perform-replace regexp to-string t t delimited nil nil start end backward
))
370 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
372 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
373 "Replace some things after point matching REGEXP with the result of TO-EXPR.
375 Interactive use of this function is deprecated in favor of the
376 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
377 using `search-forward-regexp' and `replace-match' is preferred.
379 As each match is found, the user must type a character saying
380 what to do with it. For directions, type \\[help-command] at that time.
382 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
383 reference `replace-count' to get the number of replacements already made.
384 If the result of TO-EXPR is not a string, it is converted to one using
385 `prin1-to-string' with the NOESCAPE argument (which see).
387 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
388 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
389 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
390 Use `\\#&' or `\\#N' if you want a number instead of a string.
391 In interactive use, `\\#' in itself stands for `replace-count'.
393 In Transient Mark mode, if the mark is active, operate on the contents
394 of the region. Otherwise, operate from point to the end of the buffer.
396 Use \\<minibuffer-local-map>\\[next-history-element] \
397 to pull the last incremental search regexp to the minibuffer
400 Preserves case in each replacement if `case-replace' and `case-fold-search'
401 are non-nil and REGEXP has no uppercase letters.
403 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
404 ignore hidden matches if `search-invisible' is nil, and ignore more
405 matches using `isearch-filter-predicate'.
407 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
408 to be replaced will match a sequence of whitespace chars defined by the
409 regexp in `search-whitespace-regexp'.
411 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
412 only matches that are surrounded by word boundaries.
413 Fourth and fifth arg START and END specify the region to operate on."
414 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
415 for interactive calls, and `search-forward-regexp'/`replace-match'
416 for Lisp calls." "22.1"))
419 (barf-if-buffer-read-only)
421 ;; Let-bind the history var to disable the "foo -> bar"
422 ;; default. Maybe we shouldn't disable this default, but
423 ;; for now I'll leave it off. --Stef
424 (let ((query-replace-to-history-variable nil
))
425 (query-replace-read-from "Query replace regexp" t
)))
426 (to (list (read-from-minibuffer
427 (format "Query replace regexp %s with eval: "
428 (query-replace-descr from
))
429 nil nil t query-replace-to-history-variable from t
))))
430 ;; We make TO a list because replace-match-string-symbols requires one,
431 ;; and the user might enter a single token.
432 (replace-match-string-symbols to
)
433 (list from
(car to
) current-prefix-arg
434 (if (and transient-mark-mode mark-active
)
436 (if (and transient-mark-mode mark-active
)
438 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
439 t
'literal delimited nil nil start end
))
441 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
442 "Replace some matches for REGEXP with various strings, in rotation.
443 The second argument TO-STRINGS contains the replacement strings, separated
444 by spaces. This command works like `query-replace-regexp' except that
445 each successive replacement uses the next successive replacement string,
446 wrapping around from the last such string to the first.
448 In Transient Mark mode, if the mark is active, operate on the contents
449 of the region. Otherwise, operate from point to the end of the buffer.
451 Non-interactively, TO-STRINGS may be a list of replacement strings.
453 Use \\<minibuffer-local-map>\\[next-history-element] \
454 to pull the last incremental search regexp to the minibuffer
457 A prefix argument N says to use each replacement string N times
458 before rotating to the next.
459 Fourth and fifth arg START and END specify the region to operate on."
461 (let* ((from (read-regexp "Map query replace (regexp): " nil
462 query-replace-from-history-variable
))
463 (to (read-from-minibuffer
464 (format "Query replace %s with (space-separated strings): "
465 (query-replace-descr from
))
467 query-replace-to-history-variable from t
)))
469 (and current-prefix-arg
470 (prefix-numeric-value current-prefix-arg
))
471 (if (and transient-mark-mode mark-active
)
473 (if (and transient-mark-mode mark-active
)
476 (if (listp to-strings
)
477 (setq replacements to-strings
)
478 (while (/= (length to-strings
) 0)
479 (if (string-match " " to-strings
)
482 (list (substring to-strings
0
483 (string-match " " to-strings
))))
484 to-strings
(substring to-strings
485 (1+ (string-match " " to-strings
))))
486 (setq replacements
(append replacements
(list to-strings
))
488 (perform-replace regexp replacements t t nil n nil start end
)))
490 (defun replace-string (from-string to-string
&optional delimited start end backward
)
491 "Replace occurrences of FROM-STRING with TO-STRING.
492 Preserve case in each match if `case-replace' and `case-fold-search'
493 are non-nil and FROM-STRING has no uppercase letters.
494 \(Preserving case means that if the string matched is all caps, or capitalized,
495 then its replacement is upcased or capitalized.)
497 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
498 ignore hidden matches if `search-invisible' is nil, and ignore more
499 matches using `isearch-filter-predicate'.
501 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
502 to be replaced will match a sequence of whitespace chars defined by the
503 regexp in `search-whitespace-regexp'.
505 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
506 only matches surrounded by word boundaries. A negative prefix arg means
509 Operates on the region between START and END (if both are nil, from point
510 to the end of the buffer). Interactively, if Transient Mark mode is
511 enabled and the mark is active, operates on the contents of the region;
512 otherwise from point to the end of the buffer.
514 Use \\<minibuffer-local-map>\\[next-history-element] \
515 to pull the last incremental search string to the minibuffer
516 that reads FROM-STRING.
518 This function is usually the wrong thing to use in a Lisp program.
519 What you probably want is a loop like this:
520 (while (search-forward FROM-STRING nil t)
521 (replace-match TO-STRING nil t))
522 which will run faster and will not set the mark or print anything.
523 \(You may need a more complex loop if FROM-STRING can match the null string
524 and TO-STRING is also null.)"
527 (query-replace-read-args
529 (if current-prefix-arg
530 (if (eq current-prefix-arg
'-
) " backward" " word")
533 (if (and transient-mark-mode mark-active
) " in region" ""))
535 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
536 (if (and transient-mark-mode mark-active
)
538 (if (and transient-mark-mode mark-active
)
541 (perform-replace from-string to-string nil nil delimited nil nil start end backward
))
542 (put 'replace-string
'interactive-only
543 "use `search-forward' and `replace-match' instead.")
545 (defun replace-regexp (regexp to-string
&optional delimited start end backward
)
546 "Replace things after point matching REGEXP with TO-STRING.
547 Preserve case in each match if `case-replace' and `case-fold-search'
548 are non-nil and REGEXP has no uppercase letters.
550 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
551 ignore hidden matches if `search-invisible' is nil, and ignore more
552 matches using `isearch-filter-predicate'.
554 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
555 to be replaced will match a sequence of whitespace chars defined by the
556 regexp in `search-whitespace-regexp'.
558 In Transient Mark mode, if the mark is active, operate on the contents
559 of the region. Otherwise, operate from point to the end of the buffer.
561 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
562 only matches surrounded by word boundaries. A negative prefix arg means
565 Fourth and fifth arg START and END specify the region to operate on.
567 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
568 and `\\=\\N' (where N is a digit) stands for
569 whatever what matched the Nth `\\(...\\)' in REGEXP.
570 `\\?' lets you edit the replacement text in the minibuffer
571 at the given position for each replacement.
573 In interactive calls, the replacement text may contain `\\,'
574 followed by a Lisp expression used as part of the replacement
575 text. Inside of that expression, `\\&' is a string denoting the
576 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
577 numeric values from `string-to-number', and `\\#' itself for
578 `replace-count', the number of replacements occurred so far.
580 If your Lisp expression is an identifier and the next letter in
581 the replacement string would be interpreted as part of it, you
582 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
583 for this particular case you may also enter `\\#' in the
584 replacement text directly.
586 When using those Lisp features interactively in the replacement
587 text, TO-STRING is actually made a list instead of a string.
588 Use \\[repeat-complex-command] after this command for details.
590 Use \\<minibuffer-local-map>\\[next-history-element] \
591 to pull the last incremental search regexp to the minibuffer
594 This function is usually the wrong thing to use in a Lisp program.
595 What you probably want is a loop like this:
596 (while (re-search-forward REGEXP nil t)
597 (replace-match TO-STRING nil nil))
598 which will run faster and will not set the mark or print anything."
601 (query-replace-read-args
603 (if current-prefix-arg
604 (if (eq current-prefix-arg
'-
) " backward" " word")
607 (if (and transient-mark-mode mark-active
) " in region" ""))
609 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
610 (if (and transient-mark-mode mark-active
)
612 (if (and transient-mark-mode mark-active
)
615 (perform-replace regexp to-string nil t delimited nil nil start end backward
))
616 (put 'replace-regexp
'interactive-only
617 "use `re-search-forward' and `replace-match' instead.")
620 (defvar regexp-history nil
621 "History list for some commands that read regular expressions.
623 Maximum length of the history list is determined by the value
624 of `history-length', which see.")
626 (defvar occur-collect-regexp-history
'("\\1")
627 "History of regexp for occur's collect operation")
629 (defun read-regexp (prompt &optional defaults history
)
630 "Read and return a regular expression as a string.
631 When PROMPT doesn't end with a colon and space, it adds a final \": \".
632 If the first element of DEFAULTS is non-nil, it's added to the prompt.
634 Optional arg DEFAULTS has the form (DEFAULT . SUGGESTIONS)
635 or simply DEFAULT where DEFAULT, if non-nil, should be a string that
636 is returned as the default value when the user enters empty input.
637 SUGGESTIONS is a list of strings that can be inserted into
638 the minibuffer using \\<minibuffer-local-map>\\[next-history-element]. \
639 The values supplied in SUGGESTIONS
640 are prepended to the list of standard suggestions that include
641 the tag at point, the last isearch regexp, the last isearch string,
642 and the last replacement regexp.
644 Optional arg HISTORY is a symbol to use for the history list.
645 If HISTORY is nil, `regexp-history' is used."
646 (let* ((default (if (consp defaults
) (car defaults
) defaults
))
647 (suggestions (if (listp defaults
) defaults
(list defaults
)))
652 (find-tag-default-as-regexp)
653 (car regexp-search-ring
)
654 (regexp-quote (or (car search-ring
) ""))
655 (car (symbol-value query-replace-from-history-variable
)))))
656 (suggestions (delete-dups (delq nil
(delete "" suggestions
))))
657 ;; Do not automatically add default to the history for empty input.
658 (history-add-new-input nil
)
659 (input (read-from-minibuffer
660 (cond ((string-match-p ":[ \t]*\\'" prompt
)
663 (format "%s (default %s): " prompt
664 (query-replace-descr default
)))
666 (format "%s: " prompt
)))
667 nil nil nil
(or history
'regexp-history
) suggestions t
)))
669 ;; Return the default value when the user enters empty input.
671 ;; Otherwise, add non-empty input to the history and return input.
673 (add-to-history (or history
'regexp-history
) input
)))))
676 (defalias 'delete-non-matching-lines
'keep-lines
)
677 (defalias 'delete-matching-lines
'flush-lines
)
678 (defalias 'count-matches
'how-many
)
681 (defun keep-lines-read-args (prompt)
682 "Read arguments for `keep-lines' and friends.
683 Prompt for a regexp with PROMPT.
684 Value is a list, (REGEXP)."
685 (list (read-regexp prompt
) nil nil t
))
687 (defun keep-lines (regexp &optional rstart rend interactive
)
688 "Delete all lines except those containing matches for REGEXP.
689 A match split across lines preserves all the lines it lies in.
690 When called from Lisp (and usually interactively as well, see below)
691 applies to all lines starting after point.
693 If REGEXP contains upper case characters (excluding those preceded by `\\')
694 and `search-upper-case' is non-nil, the matching is case-sensitive.
696 Second and third arg RSTART and REND specify the region to operate on.
697 This command operates on (the accessible part of) all lines whose
698 accessible part is entirely contained in the region determined by RSTART
699 and REND. (A newline ending a line counts as part of that line.)
701 Interactively, in Transient Mark mode when the mark is active, operate
702 on all lines whose accessible part is entirely contained in the region.
703 Otherwise, the command applies to all lines starting after point.
704 When calling this function from Lisp, you can pretend that it was
705 called interactively by passing a non-nil INTERACTIVE argument.
707 This function starts looking for the next match from the end of
708 the previous match. Hence, it ignores matches that overlap
709 a previously found match."
713 (barf-if-buffer-read-only)
714 (keep-lines-read-args "Keep lines containing match for regexp")))
717 (goto-char (min rstart rend
))
721 (goto-char (max rstart rend
))
722 (unless (or (bolp) (eobp))
725 (if (and interactive transient-mark-mode mark-active
)
726 (setq rstart
(region-beginning)
728 (goto-char (region-end))
729 (unless (or (bolp) (eobp))
733 rend
(point-max-marker)))
736 (or (bolp) (forward-line 1))
737 (let ((start (point))
739 (if (and case-fold-search search-upper-case
)
740 (isearch-no-upper-case-p regexp t
)
742 (while (< (point) rend
)
743 ;; Start is first char not preserved by previous match.
744 (if (not (re-search-forward regexp rend
'move
))
745 (delete-region start rend
)
746 (let ((end (save-excursion (goto-char (match-beginning 0))
749 ;; Now end is first char preserved by the new match.
751 (delete-region start end
))))
753 (setq start
(save-excursion (forward-line 1) (point)))
754 ;; If the match was empty, avoid matching again at same place.
755 (and (< (point) rend
)
756 (= (match-beginning 0) (match-end 0))
758 (set-marker rend nil
)
762 (defun flush-lines (regexp &optional rstart rend interactive
)
763 "Delete lines containing matches for REGEXP.
764 When called from Lisp (and usually when called interactively as
765 well, see below), applies to the part of the buffer after point.
766 The line point is in is deleted if and only if it contains a
767 match for regexp starting after point.
769 If REGEXP contains upper case characters (excluding those preceded by `\\')
770 and `search-upper-case' is non-nil, the matching is case-sensitive.
772 Second and third arg RSTART and REND specify the region to operate on.
773 Lines partially contained in this region are deleted if and only if
774 they contain a match entirely contained in it.
776 Interactively, in Transient Mark mode when the mark is active, operate
777 on the contents of the region. Otherwise, operate from point to the
778 end of (the accessible portion of) the buffer. When calling this function
779 from Lisp, you can pretend that it was called interactively by passing
780 a non-nil INTERACTIVE argument.
782 If a match is split across lines, all the lines it lies in are deleted.
783 They are deleted _before_ looking for the next match. Hence, a match
784 starting on the same line at which another match ended is ignored."
788 (barf-if-buffer-read-only)
789 (keep-lines-read-args "Flush lines containing match for regexp")))
792 (goto-char (min rstart rend
))
793 (setq rend
(copy-marker (max rstart rend
))))
794 (if (and interactive transient-mark-mode mark-active
)
795 (setq rstart
(region-beginning)
796 rend
(copy-marker (region-end)))
798 rend
(point-max-marker)))
800 (let ((case-fold-search
801 (if (and case-fold-search search-upper-case
)
802 (isearch-no-upper-case-p regexp t
)
805 (while (and (< (point) rend
)
806 (re-search-forward regexp rend t
))
807 (delete-region (save-excursion (goto-char (match-beginning 0))
810 (progn (forward-line 1) (point))))))
811 (set-marker rend nil
)
815 (defun how-many (regexp &optional rstart rend interactive
)
816 "Print and return number of matches for REGEXP following point.
817 When called from Lisp and INTERACTIVE is omitted or nil, just return
818 the number, do not print it; if INTERACTIVE is t, the function behaves
819 in all respects as if it had been called interactively.
821 If REGEXP contains upper case characters (excluding those preceded by `\\')
822 and `search-upper-case' is non-nil, the matching is case-sensitive.
824 Second and third arg RSTART and REND specify the region to operate on.
826 Interactively, in Transient Mark mode when the mark is active, operate
827 on the contents of the region. Otherwise, operate from point to the
828 end of (the accessible portion of) the buffer.
830 This function starts looking for the next match from the end of
831 the previous match. Hence, it ignores matches that overlap
832 a previously found match."
835 (keep-lines-read-args "How many matches for regexp"))
840 (goto-char (min rstart rend
))
841 (setq rend
(max rstart rend
)))
843 (setq rend
(point-max)))
844 (if (and interactive transient-mark-mode mark-active
)
845 (setq rstart
(region-beginning)
853 (if (and case-fold-search search-upper-case
)
854 (isearch-no-upper-case-p regexp t
)
856 (while (and (< (point) rend
)
857 (progn (setq opoint
(point))
858 (re-search-forward regexp rend t
)))
859 (if (= opoint
(point))
861 (setq count
(1+ count
))))
862 (when interactive
(message "%d occurrence%s"
864 (if (= count
1) "" "s")))
868 (defvar occur-menu-map
869 (let ((map (make-sparse-keymap)))
870 (bindings--define-key map
[next-error-follow-minor-mode
]
871 '(menu-item "Auto Occurrence Display"
872 next-error-follow-minor-mode
873 :help
"Display another occurrence when moving the cursor"
874 :button
(:toggle .
(and (boundp 'next-error-follow-minor-mode
)
875 next-error-follow-minor-mode
))))
876 (bindings--define-key map
[separator-1
] menu-bar-separator
)
877 (bindings--define-key map
[kill-this-buffer
]
878 '(menu-item "Kill Occur Buffer" kill-this-buffer
879 :help
"Kill the current *Occur* buffer"))
880 (bindings--define-key map
[quit-window
]
881 '(menu-item "Quit Occur Window" quit-window
882 :help
"Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
883 (bindings--define-key map
[revert-buffer
]
884 '(menu-item "Revert Occur Buffer" revert-buffer
885 :help
"Replace the text in the *Occur* buffer with the results of rerunning occur"))
886 (bindings--define-key map
[clone-buffer
]
887 '(menu-item "Clone Occur Buffer" clone-buffer
888 :help
"Create and return a twin copy of the current *Occur* buffer"))
889 (bindings--define-key map
[occur-rename-buffer
]
890 '(menu-item "Rename Occur Buffer" occur-rename-buffer
891 :help
"Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
892 (bindings--define-key map
[occur-edit-buffer
]
893 '(menu-item "Edit Occur Buffer" occur-edit-mode
894 :help
"Edit the *Occur* buffer and apply changes to the original buffers."))
895 (bindings--define-key map
[separator-2
] menu-bar-separator
)
896 (bindings--define-key map
[occur-mode-goto-occurrence-other-window
]
897 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
898 :help
"Go to the occurrence the current line describes, in another window"))
899 (bindings--define-key map
[occur-mode-goto-occurrence
]
900 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
901 :help
"Go to the occurrence the current line describes"))
902 (bindings--define-key map
[occur-mode-display-occurrence
]
903 '(menu-item "Display Occurrence" occur-mode-display-occurrence
904 :help
"Display in another window the occurrence the current line describes"))
905 (bindings--define-key map
[occur-next
]
906 '(menu-item "Move to Next Match" occur-next
907 :help
"Move to the Nth (default 1) next match in an Occur mode buffer"))
908 (bindings--define-key map
[occur-prev
]
909 '(menu-item "Move to Previous Match" occur-prev
910 :help
"Move to the Nth (default 1) previous match in an Occur mode buffer"))
912 "Menu keymap for `occur-mode'.")
914 (defvar occur-mode-map
915 (let ((map (make-sparse-keymap)))
916 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
917 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
918 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
919 (define-key map
"e" 'occur-edit-mode
)
920 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
921 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
922 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
923 (define-key map
"\M-n" 'occur-next
)
924 (define-key map
"\M-p" 'occur-prev
)
925 (define-key map
"r" 'occur-rename-buffer
)
926 (define-key map
"c" 'clone-buffer
)
927 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
928 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
930 "Keymap for `occur-mode'.")
932 (defvar occur-revert-arguments nil
933 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
934 See `occur-revert-function'.")
935 (make-variable-buffer-local 'occur-revert-arguments
)
936 (put 'occur-revert-arguments
'permanent-local t
)
938 (defcustom occur-mode-hook
'(turn-on-font-lock)
939 "Hook run when entering Occur mode."
943 (defcustom occur-hook nil
944 "Hook run by Occur when there are any matches."
948 (defcustom occur-mode-find-occurrence-hook nil
949 "Hook run by Occur after locating an occurrence.
950 This will be called with the cursor position at the occurrence. An application
951 for this is to reveal context in an outline-mode when the occurrence is hidden."
955 (put 'occur-mode
'mode-class
'special
)
956 (define-derived-mode occur-mode special-mode
"Occur"
957 "Major mode for output from \\[occur].
958 \\<occur-mode-map>Move point to one of the items in this buffer, then use
959 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
960 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
963 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
964 (setq next-error-function
'occur-next-error
))
969 (defvar occur-edit-mode-map
970 (let ((map (make-sparse-keymap)))
971 (set-keymap-parent map text-mode-map
)
972 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
973 (define-key map
"\C-c\C-c" 'occur-cease-edit
)
974 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
975 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
976 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
978 "Keymap for `occur-edit-mode'.")
980 (define-derived-mode occur-edit-mode occur-mode
"Occur-Edit"
981 "Major mode for editing *Occur* buffers.
982 In this mode, changes to the *Occur* buffer are also applied to
983 the originating buffer.
985 To return to ordinary Occur mode, use \\[occur-cease-edit]."
986 (setq buffer-read-only nil
)
987 (add-hook 'after-change-functions
'occur-after-change-function nil t
)
988 (message (substitute-command-keys
989 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
991 (defun occur-cease-edit ()
992 "Switch from Occur Edit mode to Occur mode."
994 (when (derived-mode-p 'occur-edit-mode
)
996 (message "Switching to Occur mode.")))
998 (defun occur-after-change-function (beg end length
)
1001 (let* ((line-beg (line-beginning-position))
1002 (m (get-text-property line-beg
'occur-target
))
1003 (buf (marker-buffer m
))
1005 (when (and (get-text-property line-beg
'occur-prefix
)
1006 (not (get-text-property end
'occur-prefix
)))
1008 ;; Apply occur-target property to inserted (e.g. yanked) text.
1009 (put-text-property beg end
'occur-target m
)
1010 ;; Did we insert a newline? Occur Edit mode can't create new
1011 ;; Occur entries; just discard everything after the newline.
1013 (and (search-forward "\n" end t
)
1014 (delete-region (1- (point)) end
))))
1015 (let* ((line (- (line-number-at-pos)
1016 (line-number-at-pos (window-start))))
1017 (readonly (with-current-buffer buf buffer-read-only
))
1018 (win (or (get-buffer-window buf
)
1020 '(nil (inhibit-same-window . t
)
1021 (inhibit-switch-frame . t
)))))
1022 (line-end (line-end-position))
1023 (text (save-excursion
1024 (goto-char (next-single-property-change
1025 line-beg
'occur-prefix nil
1027 (setq col
(- (point) line-beg
))
1028 (buffer-substring-no-properties (point) line-end
))))
1029 (with-selected-window win
1033 (message "Buffer `%s' is read only." buf
)
1034 (delete-region (line-beginning-position) (line-end-position))
1036 (move-to-column col
)))))))
1039 (defun occur-revert-function (_ignore1 _ignore2
)
1040 "Handle `revert-buffer' for Occur mode buffers."
1041 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
1043 (defun occur-mode-find-occurrence ()
1044 (let ((pos (get-text-property (point) 'occur-target
)))
1046 (error "No occurrence on this line"))
1047 (unless (buffer-live-p (marker-buffer pos
))
1048 (error "Buffer for this occurrence was killed"))
1051 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
1052 (defun occur-mode-goto-occurrence (&optional event
)
1053 "Go to the occurrence on the current line."
1054 (interactive (list last-nonmenu-event
))
1057 ;; Actually `event-end' works correctly with a nil argument as
1058 ;; well, so we could dispense with this test, but let's not
1059 ;; rely on this undocumented behavior.
1060 (occur-mode-find-occurrence)
1061 (with-current-buffer (window-buffer (posn-window (event-end event
)))
1063 (goto-char (posn-point (event-end event
)))
1064 (occur-mode-find-occurrence))))))
1065 (pop-to-buffer (marker-buffer pos
))
1067 (run-hooks 'occur-mode-find-occurrence-hook
)))
1069 (defun occur-mode-goto-occurrence-other-window ()
1070 "Go to the occurrence the current line describes, in another window."
1072 (let ((pos (occur-mode-find-occurrence)))
1073 (switch-to-buffer-other-window (marker-buffer pos
))
1075 (run-hooks 'occur-mode-find-occurrence-hook
)))
1077 (defun occur-mode-display-occurrence ()
1078 "Display in another window the occurrence the current line describes."
1080 (let ((pos (occur-mode-find-occurrence))
1082 (setq window
(display-buffer (marker-buffer pos
) t
))
1083 ;; This is the way to set point in the proper window.
1084 (save-selected-window
1085 (select-window window
)
1087 (run-hooks 'occur-mode-find-occurrence-hook
))))
1089 (defun occur-find-match (n search message
)
1090 (if (not n
) (setq n
1))
1093 (setq r
(funcall search
(point) 'occur-match
))
1095 (get-text-property r
'occur-match
)
1096 (setq r
(funcall search r
'occur-match
)))
1102 (defun occur-next (&optional n
)
1103 "Move to the Nth (default 1) next match in an Occur mode buffer."
1105 (occur-find-match n
#'next-single-property-change
"No more matches"))
1107 (defun occur-prev (&optional n
)
1108 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1110 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
1112 (defun occur-next-error (&optional argp reset
)
1113 "Move to the Nth (default 1) next match in an Occur mode buffer.
1114 Compatibility function for \\[next-error] invocations."
1116 ;; we need to run occur-find-match from within the Occur buffer
1117 (with-current-buffer
1118 ;; Choose the buffer and make it current.
1119 (if (next-error-buffer-p (current-buffer))
1121 (next-error-find-buffer nil nil
1123 (eq major-mode
'occur-mode
))))
1125 (goto-char (cond (reset (point-min))
1126 ((< argp
0) (line-beginning-position))
1127 ((> argp
0) (line-end-position))
1132 #'previous-single-property-change
1133 #'next-single-property-change
)
1135 ;; In case the *Occur* buffer is visible in a nonselected window.
1136 (let ((win (get-buffer-window (current-buffer) t
)))
1137 (if win
(set-window-point win
(point))))
1138 (occur-mode-goto-occurrence)))
1141 '((((class color
) (min-colors 88) (background light
))
1142 :background
"yellow1")
1143 (((class color
) (min-colors 88) (background dark
))
1144 :background
"RoyalBlue3")
1145 (((class color
) (min-colors 8) (background light
))
1146 :background
"yellow" :foreground
"black")
1147 (((class color
) (min-colors 8) (background dark
))
1148 :background
"blue" :foreground
"white")
1149 (((type tty
) (class mono
))
1151 (t :background
"gray"))
1152 "Face used to highlight matches permanently."
1156 (defcustom list-matching-lines-default-context-lines
0
1157 "Default number of context lines included around `list-matching-lines' matches.
1158 A negative number means to include that many lines before the match.
1159 A positive number means to include that many lines both before and after."
1163 (defalias 'list-matching-lines
'occur
)
1165 (defcustom list-matching-lines-face
'match
1166 "Face used by \\[list-matching-lines] to show the text that matches.
1167 If the value is nil, don't highlight the matching portions specially."
1171 (defcustom list-matching-lines-buffer-name-face
'underline
1172 "Face used by \\[list-matching-lines] to show the names of buffers.
1173 If the value is nil, don't highlight the buffer names specially."
1177 (defcustom list-matching-lines-prefix-face
'shadow
1178 "Face used by \\[list-matching-lines] to show the prefix column.
1179 If the face doesn't differ from the default face,
1180 don't highlight the prefix with line numbers specially."
1185 (defcustom occur-excluded-properties
1186 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1187 yank-handler follow-link
)
1188 "Text properties to discard when copying lines to the *Occur* buffer.
1189 The value should be a list of text properties to discard or t,
1190 which means to discard all text properties."
1191 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
1195 (defvar occur-read-regexp-defaults-function
1196 'occur-read-regexp-defaults
1197 "Function that provides default regexp(s) for occur commands.
1198 This function should take no arguments and return one of nil, a
1199 regexp or a list of regexps for use with occur commands -
1200 `occur', `multi-occur' and `multi-occur-in-matching-buffers'.
1201 The return value of this function is used as DEFAULTS param of
1202 `read-regexp' while executing the occur command. This function
1203 is called only during interactive use.
1205 For example, to check for occurrence of symbol at point use
1207 (setq occur-read-regexp-defaults-function
1208 'find-tag-default-as-regexp).")
1210 (defun occur-read-regexp-defaults ()
1211 "Return the latest regexp from `regexp-history'.
1212 See `occur-read-regexp-defaults-function' for details."
1213 (car regexp-history
))
1215 (defun occur-read-primary-args ()
1216 (let* ((perform-collect (consp current-prefix-arg
))
1217 (regexp (read-regexp (if perform-collect
1218 "Collect strings matching regexp"
1219 "List lines matching regexp")
1220 (funcall occur-read-regexp-defaults-function
))))
1223 ;; Perform collect operation
1224 (if (zerop (regexp-opt-depth regexp
))
1225 ;; No subexpression so collect the entire match.
1227 ;; Get the regexp for collection pattern.
1228 (let ((default (car occur-collect-regexp-history
)))
1230 (format "Regexp to collect (default %s): " default
)
1231 default
'occur-collect-regexp-history
)))
1232 ;; Otherwise normal occur takes numerical prefix argument.
1233 (when current-prefix-arg
1234 (prefix-numeric-value current-prefix-arg
))))))
1236 (defun occur-rename-buffer (&optional unique-p interactive-p
)
1237 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1238 Here `original-buffer-name' is the buffer name where Occur was originally run.
1239 When given the prefix argument, or called non-interactively, the renaming
1240 will not clobber the existing buffer(s) of that name, but use
1241 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1242 if you always want a separate *Occur* buffer for each buffer where you
1244 (interactive "P\np")
1245 (with-current-buffer
1246 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
1247 (rename-buffer (concat "*Occur: "
1248 (mapconcat #'buffer-name
1249 (car (cddr occur-revert-arguments
)) "/")
1251 (or unique-p
(not interactive-p
)))))
1253 (defun occur (regexp &optional nlines
)
1254 "Show all lines in the current buffer containing a match for REGEXP.
1255 If a match spreads across multiple lines, all those lines are shown.
1257 Each line is displayed with NLINES lines before and after, or -NLINES
1258 before if NLINES is negative.
1259 NLINES defaults to `list-matching-lines-default-context-lines'.
1260 Interactively it is the prefix arg.
1262 The lines are shown in a buffer named `*Occur*'.
1263 It serves as a menu to find any of the occurrences in this buffer.
1264 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1266 If REGEXP contains upper case characters (excluding those preceded by `\\')
1267 and `search-upper-case' is non-nil, the matching is case-sensitive.
1269 When NLINES is a string or when the function is called
1270 interactively with prefix argument without a number (`C-u' alone
1271 as prefix) the matching strings are collected into the `*Occur*'
1272 buffer by using NLINES as a replacement regexp. NLINES may
1273 contain \\& and \\N which convention follows `replace-match'.
1274 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1275 \"\\1\" for NLINES collects all the function names in a lisp
1276 program. When there is no parenthesized subexpressions in REGEXP
1277 the entire match is collected. In any case the searched buffer
1279 (interactive (occur-read-primary-args))
1280 (occur-1 regexp nlines
(list (current-buffer))))
1282 (defvar ido-ignore-item-temp-list
)
1284 (defun multi-occur (bufs regexp
&optional nlines
)
1285 "Show all lines in buffers BUFS containing a match for REGEXP.
1286 This function acts on multiple buffers; otherwise, it is exactly like
1287 `occur'. When you invoke this command interactively, you must specify
1288 the buffer names that you want, one by one.
1289 See also `multi-occur-in-matching-buffers'."
1292 (let* ((bufs (list (read-buffer "First buffer to search: "
1293 (current-buffer) t
)))
1295 (ido-ignore-item-temp-list bufs
))
1296 (while (not (string-equal
1297 (setq buf
(read-buffer
1298 (if (eq read-buffer-function
'ido-read-buffer
)
1299 "Next buffer to search (C-j to end): "
1300 "Next buffer to search (RET to end): ")
1303 (add-to-list 'bufs buf
)
1304 (setq ido-ignore-item-temp-list bufs
))
1305 (nreverse (mapcar #'get-buffer bufs
)))
1306 (occur-read-primary-args)))
1307 (occur-1 regexp nlines bufs
))
1309 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1310 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1311 Normally BUFREGEXP matches against each buffer's visited file name,
1312 but if you specify a prefix argument, it matches against the buffer name.
1313 See also `multi-occur'."
1316 (let* ((default (car regexp-history
))
1319 (if current-prefix-arg
1320 "List lines in buffers whose names match regexp: "
1321 "List lines in buffers whose filenames match regexp: "))))
1322 (if (equal input
"")
1325 (occur-read-primary-args)))
1329 (mapcar (lambda (buf)
1331 (string-match bufregexp
1333 (and (buffer-file-name buf
)
1334 (string-match bufregexp
1335 (buffer-file-name buf
))))
1339 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1340 (unless (and regexp
(not (equal regexp
"")))
1341 (error "Occur doesn't work with the empty regexp"))
1343 (setq buf-name
"*Occur*"))
1345 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1346 (when (buffer-live-p buf
) buf
))
1348 ;; Handle the case where one of the buffers we're searching is the
1349 ;; output buffer. Just rename it.
1350 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1351 (with-current-buffer (get-buffer buf-name
)
1354 ;; Now find or create the output buffer.
1355 ;; If we just renamed that buffer, we will make a new one here.
1356 (setq occur-buf
(get-buffer-create buf-name
))
1358 (with-current-buffer occur-buf
1359 (if (stringp nlines
)
1360 (fundamental-mode) ;; This is for collect operation.
1362 (let ((inhibit-read-only t
)
1363 ;; Don't generate undo entries for creation of the initial contents.
1364 (buffer-undo-list t
))
1367 (if (stringp nlines
)
1368 ;; Treat nlines as a regexp to collect.
1369 (let ((bufs active-bufs
)
1372 (with-current-buffer (car bufs
)
1374 (goto-char (point-min))
1375 (while (re-search-forward regexp nil t
)
1376 ;; Insert the replacement regexp.
1377 (let ((str (match-substitute-replacement nlines
)))
1379 (with-current-buffer occur-buf
1381 (setq count
(1+ count
))
1382 (or (zerop (current-column))
1383 (insert "\n"))))))))
1384 (setq bufs
(cdr bufs
)))
1386 ;; Perform normal occur.
1388 regexp active-bufs occur-buf
1389 (or nlines list-matching-lines-default-context-lines
)
1390 (if (and case-fold-search search-upper-case
)
1391 (isearch-no-upper-case-p regexp t
)
1393 list-matching-lines-buffer-name-face
1394 (if (face-differs-from-default-p list-matching-lines-prefix-face
)
1395 list-matching-lines-prefix-face
)
1396 list-matching-lines-face
1397 (not (eq occur-excluded-properties t
))))))
1398 (let* ((bufcount (length active-bufs
))
1399 (diff (- (length bufs
) bufcount
)))
1400 (message "Searched %d buffer%s%s; %s match%s%s"
1401 bufcount
(if (= bufcount
1) "" "s")
1402 (if (zerop diff
) "" (format " (%d killed)" diff
))
1403 (if (zerop count
) "no" (format "%d" count
))
1404 (if (= count
1) "" "es")
1405 ;; Don't display regexp if with remaining text
1406 ;; it is longer than window-width.
1407 (if (> (+ (length regexp
) 42) (window-width))
1408 "" (format " for `%s'" (query-replace-descr regexp
)))))
1409 (setq occur-revert-arguments
(list regexp nlines bufs
))
1411 (kill-buffer occur-buf
)
1412 (display-buffer occur-buf
)
1413 (setq next-error-last-buffer occur-buf
)
1414 (setq buffer-read-only t
)
1415 (set-buffer-modified-p nil
)
1416 (run-hooks 'occur-hook
)))))))
1418 (defun occur-engine (regexp buffers out-buf nlines case-fold
1419 title-face prefix-face match-face keep-props
)
1420 (with-current-buffer out-buf
1421 (let ((global-lines 0) ;; total count of matching lines
1422 (global-matches 0) ;; total count of matches
1424 (case-fold-search case-fold
))
1425 ;; Map over all the buffers
1426 (dolist (buf buffers
)
1427 (when (buffer-live-p buf
)
1428 (let ((lines 0) ;; count of matching lines
1429 (matches 0) ;; count of matches
1430 (curr-line 1) ;; line count
1431 (prev-line nil
) ;; line number of prev match endpt
1432 (prev-after-lines nil
) ;; context lines of prev match
1440 (inhibit-field-text-motion t
)
1441 (headerpt (with-current-buffer out-buf
(point))))
1442 (with-current-buffer buf
1444 ;; Set CODING only if the current buffer locally
1445 ;; binds buffer-file-coding-system.
1446 (not (local-variable-p 'buffer-file-coding-system
))
1447 (setq coding buffer-file-coding-system
))
1449 (goto-char (point-min)) ;; begin searching in the buffer
1451 (setq origpt
(point))
1452 (when (setq endpt
(re-search-forward regexp nil t
))
1453 (setq lines
(1+ lines
)) ;; increment matching lines count
1454 (setq matchbeg
(match-beginning 0))
1455 ;; Get beginning of first match line and end of the last.
1457 (goto-char matchbeg
)
1458 (setq begpt
(line-beginning-position))
1460 (setq endpt
(line-end-position)))
1461 ;; Sum line numbers up to the first match line.
1462 (setq curr-line
(+ curr-line
(count-lines origpt begpt
)))
1463 (setq marker
(make-marker))
1464 (set-marker marker matchbeg
)
1465 (setq curstring
(occur-engine-line begpt endpt keep-props
))
1466 ;; Highlight the matches
1467 (let ((len (length curstring
))
1469 (while (and (< start len
)
1470 (string-match regexp curstring start
))
1471 (setq matches
(1+ matches
))
1472 (add-text-properties
1473 (match-beginning 0) (match-end 0)
1474 '(occur-match t
) curstring
)
1476 ;; Add `match-face' to faces copied from the buffer.
1477 (add-face-text-property
1478 (match-beginning 0) (match-end 0)
1479 match-face nil curstring
))
1480 ;; Avoid infloop (Bug#7593).
1481 (let ((end (match-end 0)))
1482 (setq start
(if (= start end
) (1+ start
) end
)))))
1483 ;; Generate the string to insert for this match
1484 (let* ((match-prefix
1485 ;; Using 7 digits aligns tabs properly.
1486 (apply #'propertize
(format "%7d:" curr-line
)
1489 `(font-lock-face ,prefix-face
))
1490 `(occur-prefix t mouse-face
(highlight)
1491 ;; Allow insertion of text at
1492 ;; the end of the prefix (for
1493 ;; Occur Edit mode).
1494 front-sticky t rear-nonsticky t
1495 occur-target
,marker follow-link t
1496 help-echo
"mouse-2: go to this occurrence"))))
1498 ;; We don't put `mouse-face' on the newline,
1499 ;; because that loses. And don't put it
1500 ;; on context lines to reduce flicker.
1501 (propertize curstring
'mouse-face
(list 'highlight
)
1502 'occur-target marker
1505 "mouse-2: go to this occurrence"))
1509 ;; Add non-numeric prefix to all non-first lines
1510 ;; of multi-line matches.
1511 (replace-regexp-in-string
1514 (propertize "\n :" 'font-lock-face prefix-face
)
1517 ;; Add marker at eol, but no mouse props.
1518 (propertize "\n" 'occur-target marker
)))
1521 ;; The simple display style
1523 ;; The complex multi-line display style.
1524 (setq ret
(occur-context-lines
1525 out-line nlines keep-props begpt endpt
1526 curr-line prev-line prev-after-lines
1528 ;; Set first elem of the returned list to `data',
1529 ;; and the second elem to `prev-after-lines'.
1530 (setq prev-after-lines
(nth 1 ret
))
1532 ;; Actually insert the match display data
1533 (with-current-buffer out-buf
1538 ;; Sum line numbers between first and last match lines.
1539 (setq curr-line
(+ curr-line
(count-lines begpt endpt
)
1540 ;; Add 1 for empty last match line since
1541 ;; count-lines returns 1 line less.
1542 (if (and (bolp) (eolp)) 1 0)))
1543 ;; On to the next match...
1545 (goto-char (point-max)))
1546 (setq prev-line
(1- curr-line
)))
1547 ;; Flush remaining context after-lines.
1548 (when prev-after-lines
1549 (with-current-buffer out-buf
1550 (insert (apply #'concat
(occur-engine-add-prefix
1551 prev-after-lines prefix-face
)))))))
1552 (when (not (zerop lines
)) ;; is the count zero?
1553 (setq global-lines
(+ global-lines lines
)
1554 global-matches
(+ global-matches matches
))
1555 (with-current-buffer out-buf
1556 (goto-char headerpt
)
1560 (format "%d match%s%s%s in buffer: %s\n"
1561 matches
(if (= matches
1) "" "es")
1562 ;; Don't display the same number of lines
1563 ;; and matches in case of 1 match per line.
1564 (if (= lines matches
)
1565 "" (format " in %d line%s"
1566 lines
(if (= lines
1) "" "s")))
1567 ;; Don't display regexp for multi-buffer.
1568 (if (> (length buffers
) 1)
1569 "" (format " for \"%s\""
1570 (query-replace-descr regexp
)))
1574 (add-text-properties beg end
`(occur-title ,buf
))
1576 (add-face-text-property beg end title-face
)))
1577 (goto-char (point-min)))))))
1578 ;; Display total match count and regexp for multi-buffer.
1579 (when (and (not (zerop global-lines
)) (> (length buffers
) 1))
1580 (goto-char (point-min))
1583 (insert (format "%d match%s%s total for \"%s\":\n"
1584 global-matches
(if (= global-matches
1) "" "es")
1585 ;; Don't display the same number of lines
1586 ;; and matches in case of 1 match per line.
1587 (if (= global-lines global-matches
)
1588 "" (format " in %d line%s"
1589 global-lines
(if (= global-lines
1) "" "s")))
1590 (query-replace-descr regexp
)))
1593 (add-face-text-property beg end title-face
)))
1594 (goto-char (point-min)))
1596 ;; CODING is buffer-file-coding-system of the first buffer
1597 ;; that locally binds it. Let's use it also for the output
1599 (set-buffer-file-coding-system coding
))
1600 ;; Return the number of matches
1603 (defun occur-engine-line (beg end
&optional keep-props
)
1604 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
1605 (text-property-not-all beg end
'fontified t
))
1606 (if (fboundp 'jit-lock-fontify-now
)
1607 (jit-lock-fontify-now beg end
)))
1608 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1609 (let ((str (buffer-substring beg end
)))
1610 (remove-list-of-text-properties
1611 0 (length str
) occur-excluded-properties str
)
1613 (buffer-substring-no-properties beg end
)))
1615 (defun occur-engine-add-prefix (lines &optional prefix-face
)
1618 (concat (if prefix-face
1619 (propertize " :" 'font-lock-face prefix-face
)
1624 (defun occur-accumulate-lines (count &optional keep-props pt
)
1628 (let ((forwardp (> count
0))
1629 result beg end moved
)
1630 (while (not (or (zerop count
)
1633 (and (bobp) (not moved
)))))
1634 (setq count
(+ count
(if forwardp -
1 1)))
1635 (setq beg
(line-beginning-position)
1636 end
(line-end-position))
1637 (push (occur-engine-line beg end keep-props
) result
)
1638 (setq moved
(= 0 (forward-line (if forwardp
1 -
1)))))
1639 (nreverse result
))))
1641 ;; Generate context display for occur.
1642 ;; OUT-LINE is the line where the match is.
1643 ;; NLINES and KEEP-PROPS are args to occur-engine.
1644 ;; CURR-LINE is line count of the current match,
1645 ;; PREV-LINE is line count of the previous match,
1646 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1647 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1648 ;; then concatenate them all together.
1649 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1650 curr-line prev-line prev-after-lines
1651 &optional prefix-face
)
1652 ;; Find after- and before-context lines of the current match.
1654 (nreverse (cdr (occur-accumulate-lines
1655 (- (1+ (abs nlines
))) keep-props begpt
))))
1657 (cdr (occur-accumulate-lines
1658 (1+ nlines
) keep-props endpt
)))
1661 ;; Combine after-lines of the previous match
1662 ;; with before-lines of the current match.
1664 (when prev-after-lines
1665 ;; Don't overlap prev after-lines with current before-lines.
1666 (if (>= (+ prev-line
(length prev-after-lines
))
1667 (- curr-line
(length before-lines
)))
1668 (setq prev-after-lines
1669 (butlast prev-after-lines
1670 (- (length prev-after-lines
)
1671 (- curr-line prev-line
(length before-lines
) 1))))
1672 ;; Separate non-overlapping context lines with a dashed line.
1673 (setq separator
"-------\n")))
1676 ;; Don't overlap current before-lines with previous match line.
1677 (if (<= (- curr-line
(length before-lines
))
1680 (nthcdr (- (length before-lines
)
1681 (- curr-line prev-line
1))
1683 ;; Separate non-overlapping before-context lines.
1684 (unless (> nlines
0)
1685 (setq separator
"-------\n"))))
1688 ;; Return a list where the first element is the output line.
1691 (if prev-after-lines
1692 (occur-engine-add-prefix prev-after-lines prefix-face
))
1694 (list (if prefix-face
1695 (propertize separator
'font-lock-face prefix-face
)
1697 (occur-engine-add-prefix before-lines prefix-face
)
1699 ;; And the second element is the list of context after-lines.
1700 (if (> nlines
0) after-lines
))))
1703 ;; It would be nice to use \\[...], but there is no reasonable way
1704 ;; to make that display both SPC and Y.
1705 (defconst query-replace-help
1706 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1707 RET or `q' to exit, Period to replace one match and exit,
1708 Comma to replace but not move point immediately,
1709 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1710 C-w to delete match and recursive edit,
1711 C-l to clear the screen, redisplay, and offer same replacement again,
1712 ! to replace all remaining matches in this buffer with no more questions,
1713 ^ to move point back to previous match,
1714 E to edit the replacement string.
1715 In multi-buffer replacements type `Y' to replace all remaining
1716 matches in all remaining buffers with no more questions,
1717 `N' to skip to the next buffer without replacing remaining matches
1718 in the current buffer."
1719 "Help message while in `query-replace'.")
1721 (defvar query-replace-map
1722 (let ((map (make-sparse-keymap)))
1723 (define-key map
" " 'act
)
1724 (define-key map
"\d" 'skip
)
1725 (define-key map
[delete] 'skip)
1726 (define-key map [backspace] 'skip)
1727 (define-key map "y" 'act)
1728 (define-key map "n" 'skip)
1729 (define-key map "Y" 'act)
1730 (define-key map "N" 'skip)
1731 (define-key map "e" 'edit-replacement)
1732 (define-key map "E" 'edit-replacement)
1733 (define-key map "," 'act-and-show)
1734 (define-key map "q" 'exit)
1735 (define-key map "\r" 'exit)
1736 (define-key map [return] 'exit)
1737 (define-key map "." 'act-and-exit)
1738 (define-key map "\C-r" 'edit)
1739 (define-key map "\C-w" 'delete-and-edit)
1740 (define-key map "\C-l" 'recenter)
1741 (define-key map "!" 'automatic)
1742 (define-key map "^" 'backup)
1743 (define-key map "\C-h" 'help)
1744 (define-key map [f1] 'help)
1745 (define-key map [help] 'help)
1746 (define-key map "?" 'help)
1747 (define-key map "\C-g" 'quit)
1748 (define-key map "\C-]" 'quit)
1749 (define-key map "\C-v" 'scroll-up)
1750 (define-key map "\M-v" 'scroll-down)
1751 (define-key map [next] 'scroll-up)
1752 (define-key map [prior] 'scroll-down)
1753 (define-key map [?\C-\M-v] 'scroll-other-window)
1754 (define-key map [M-next] 'scroll-other-window)
1755 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1756 (define-key map [M-prior] 'scroll-other-window-down)
1757 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1758 ;; should check for ESC specially.
1759 ;; (define-key map "\e" 'exit-prefix)
1760 (define-key map [escape] 'exit-prefix)
1762 "Keymap of responses to questions posed by commands like `query-replace'.
1763 The \"bindings\" in this map are not commands; they are answers.
1764 The valid answers include `act', `skip', `act-and-show',
1765 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1766 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1767 `edit', `edit-replacement', `delete-and-edit', `automatic',
1768 `backup', `quit', and `help'.
1770 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1772 (defvar multi-query-replace-map
1773 (let ((map (make-sparse-keymap)))
1774 (set-keymap-parent map query-replace-map)
1775 (define-key map "Y" 'automatic-all)
1776 (define-key map "N" 'exit-current)
1778 "Keymap that defines additional bindings for multi-buffer replacements.
1779 It extends its parent map `query-replace-map' with new bindings to
1780 operate on a set of buffers/files. The difference with its parent map
1781 is the additional answers `automatic-all' to replace all remaining
1782 matches in all remaining buffers with no more questions, and
1783 `exit-current' to skip remaining matches in the current buffer
1784 and to continue with the next buffer in the sequence.")
1786 (defun replace-match-string-symbols (n)
1787 "Process a list (and any sub-lists), expanding certain symbols.
1789 N (match-string N) (where N is a string of digits)
1790 #N (string-to-number (match-string N))
1792 #& (string-to-number (match-string 0))
1795 Note that these symbols must be preceded by a backslash in order to
1796 type them using Lisp syntax."
1800 (replace-match-string-symbols (car n))) ;Process sub-list
1802 (let ((name (symbol-name (car n))))
1804 ((string-match "^[0-9]+$" name)
1805 (setcar n (list 'match-string (string-to-number name))))
1806 ((string-match "^#[0-9]+$" name)
1807 (setcar n (list 'string-to-number
1809 (string-to-number (substring name 1))))))
1811 (setcar n '(match-string 0)))
1812 ((string= "#&" name)
1813 (setcar n '(string-to-number (match-string 0))))
1815 (setcar n 'replace-count))))))
1818 (defun replace-eval-replacement (expression count)
1819 (let* ((replace-count count)
1825 (error "Error evaluating replacement expression: %S" err)))))
1826 (if (stringp replacement)
1828 (prin1-to-string replacement t))))
1830 (defun replace-quote (replacement)
1831 "Quote a replacement string.
1832 This just doubles all backslashes in REPLACEMENT and
1833 returns the resulting string. If REPLACEMENT is not
1834 a string, it is first passed through `prin1-to-string'
1835 with the `noescape' argument set.
1837 `match-data' is preserved across the call."
1839 (replace-regexp-in-string "\\\\" "\\\\"
1840 (if (stringp replacement)
1842 (prin1-to-string replacement t))
1845 (defun replace-loop-through-replacements (data count)
1846 ;; DATA is a vector containing the following values:
1847 ;; 0 next-rotate-count
1849 ;; 2 next-replacement
1851 (if (= (aref data 0) count)
1853 (aset data 0 (+ count (aref data 1)))
1854 (let ((next (cdr (aref data 2))))
1855 (aset data 2 (if (consp next) next (aref data 3))))))
1856 (car (aref data 2)))
1858 (defun replace-match-data (integers reuse &optional new)
1859 "Like `match-data', but markers in REUSE get invalidated.
1860 If NEW is non-nil, it is set and returned instead of fresh data,
1861 but coerced to the correct value of INTEGERS."
1864 (set-match-data new)
1866 (eq (null integers) (markerp (car reuse)))
1868 (match-data integers reuse t)))
1870 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data backward)
1871 "Make a replacement with `replace-match', editing `\\?'.
1872 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1873 check for `\\?' is made to save time. MATCH-DATA is used for the
1874 replacement. In case editing is done, it is changed to use markers.
1876 The return value is non-nil if there has been no `\\?' or NOEDIT was
1877 passed in. If LITERAL is set, no checking is done, anyway."
1878 (unless (or literal noedit)
1880 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1883 (read-string "Edit replacement string: "
1886 (replace-match "" t t newtext 3)
1887 (1+ (match-beginning 3)))
1890 nil match-data match-data))))
1892 (set-match-data match-data)
1893 (replace-match newtext fixedcase literal)
1894 ;; `replace-match' leaves point at the end of the replacement text,
1895 ;; so move point to the beginning when replacing backward.
1896 (when backward (goto-char (nth 0 match-data)))
1899 (defvar replace-search-function nil
1900 "Function to use when searching for strings to replace.
1901 It is used by `query-replace' and `replace-string', and is called
1902 with three arguments, as if it were `search-forward'.")
1904 (defvar replace-re-search-function nil
1905 "Function to use when searching for regexps to replace.
1906 It is used by `query-replace-regexp', `replace-regexp',
1907 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1908 It is called with three arguments, as if it were
1909 `re-search-forward'.")
1911 (defun replace-search (search-string limit regexp-flag delimited-flag
1912 case-fold-search backward)
1913 "Search for the next occurrence of SEARCH-STRING to replace."
1914 ;; Let-bind global isearch-* variables to values used
1915 ;; to search the next replacement. These let-bindings
1916 ;; should be effective both at the time of calling
1917 ;; `isearch-search-fun-default' and also at the
1918 ;; time of funcalling `search-function'.
1919 ;; These isearch-* bindings can't be placed higher
1920 ;; outside of this function because then another I-search
1921 ;; used after `recursive-edit' might override them.
1922 (let* ((isearch-regexp regexp-flag)
1923 (isearch-word delimited-flag)
1924 (isearch-lax-whitespace
1925 replace-lax-whitespace)
1926 (isearch-regexp-lax-whitespace
1927 replace-regexp-lax-whitespace)
1928 (isearch-case-fold-search case-fold-search)
1929 (isearch-adjusted nil)
1930 (isearch-nonincremental t) ; don't use lax word mode
1931 (isearch-forward (not backward))
1934 replace-re-search-function
1935 replace-search-function)
1936 (isearch-search-fun-default))))
1937 (funcall search-function search-string limit t)))
1939 (defvar replace-overlay nil)
1941 (defun replace-highlight (match-beg match-end range-beg range-end
1942 search-string regexp-flag delimited-flag
1943 case-fold-search backward)
1944 (if query-replace-highlight
1946 (move-overlay replace-overlay match-beg match-end (current-buffer))
1947 (setq replace-overlay (make-overlay match-beg match-end))
1948 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
1949 (overlay-put replace-overlay 'face 'query-replace)))
1950 (if query-replace-lazy-highlight
1951 (let ((isearch-string search-string)
1952 (isearch-regexp regexp-flag)
1953 (isearch-word delimited-flag)
1954 (isearch-lax-whitespace
1955 replace-lax-whitespace)
1956 (isearch-regexp-lax-whitespace
1957 replace-regexp-lax-whitespace)
1958 (isearch-case-fold-search case-fold-search)
1959 (isearch-forward (not backward))
1960 (isearch-other-end match-beg)
1961 (isearch-error nil))
1962 (isearch-lazy-highlight-new-loop range-beg range-end))))
1964 (defun replace-dehighlight ()
1965 (when replace-overlay
1966 (delete-overlay replace-overlay))
1967 (when query-replace-lazy-highlight
1968 (lazy-highlight-cleanup lazy-highlight-cleanup)
1969 (setq isearch-lazy-highlight-last-string nil))
1970 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
1971 (isearch-clean-overlays))
1973 (defun perform-replace (from-string replacements
1974 query-flag regexp-flag delimited-flag
1975 &optional repeat-count map start end backward)
1976 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1977 Don't use this in your own program unless you want to query and set the mark
1978 just as `query-replace' does. Instead, write a simple loop like this:
1980 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1981 (replace-match \"foobar\" nil nil))
1983 which will run faster and probably do exactly what you want. Please
1984 see the documentation of `replace-match' to find out how to simulate
1987 This function returns nil if and only if there were no matches to
1988 make, or the user didn't cancel the call."
1989 (or map (setq map query-replace-map))
1990 (and query-flag minibuffer-auto-raise
1991 (raise-frame (window-frame (minibuffer-window))))
1992 (let* ((case-fold-search
1993 (if (and case-fold-search search-upper-case)
1994 (isearch-no-upper-case-p from-string regexp-flag)
1996 (nocasify (not (and case-replace case-fold-search)))
1997 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1998 (search-string from-string)
1999 (real-match-data nil) ; The match data for the current match.
2000 (next-replacement nil)
2001 ;; This is non-nil if we know there is nothing for the user
2002 ;; to edit in the replacement.
2007 (skip-read-only-count 0)
2008 (skip-filtered-count 0)
2009 (skip-invisible-count 0)
2010 (nonempty-match nil)
2012 (recenter-last-op nil) ; Start cycling order with initial position.
2014 ;; If non-nil, it is marker saying where in the buffer to stop.
2017 ;; Data for the next match. If a cons, it has the same format as
2018 ;; (match-data); otherwise it is t if a match is possible at point.
2024 (substitute-command-keys
2025 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2026 minibuffer-prompt-properties))))
2028 ;; If region is active, in Transient Mark mode, operate on region.
2031 (setq limit (copy-marker (min start end)))
2032 (goto-char (max start end))
2035 (setq limit (copy-marker (max start end)))
2036 (goto-char (min start end))
2039 ;; If last typed key in previous call of multi-buffer perform-replace
2040 ;; was `automatic-all', don't ask more questions in next files
2041 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2042 (setq query-flag nil multi-buffer t))
2044 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
2045 ;; containing a function and its first argument. The function is
2046 ;; called to generate each replacement like this:
2047 ;; (funcall (car replacements) (cdr replacements) replace-count)
2048 ;; It must return a string.
2050 ((stringp replacements)
2051 (setq next-replacement replacements
2053 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2054 (or repeat-count (setq repeat-count 1))
2055 (setq replacements (cons 'replace-loop-through-replacements
2056 (vector repeat-count repeat-count
2057 replacements replacements)))))
2059 (when query-replace-lazy-highlight
2060 (setq isearch-lazy-highlight-last-string nil))
2065 ;; Loop finding occurrences that perhaps should be replaced.
2066 (while (and keep-going
2068 (not (or (bobp) (and limit (<= (point) limit))))
2069 (not (or (eobp) (and limit (>= (point) limit)))))
2070 ;; Use the next match if it is already known;
2071 ;; otherwise, search for a match after moving forward
2072 ;; one char if progress is required.
2073 (setq real-match-data
2074 (cond ((consp match-again)
2075 (goto-char (if backward
2077 (nth 1 match-again)))
2079 t real-match-data match-again))
2080 ;; MATCH-AGAIN non-nil means accept an
2084 (replace-search search-string limit
2085 regexp-flag delimited-flag
2086 case-fold-search backward)
2087 ;; For speed, use only integers and
2088 ;; reuse the list used last time.
2089 (replace-match-data t real-match-data)))
2091 (> (1- (point)) (point-min))
2092 (< (1+ (point)) (point-max)))
2095 (> (1- (point)) limit)
2096 (< (1+ (point)) limit))))
2097 ;; If not accepting adjacent matches,
2098 ;; move one char to the right before
2099 ;; searching again. Undo the motion
2100 ;; if the search fails.
2101 (let ((opoint (point)))
2102 (forward-char (if backward -1 1))
2103 (if (replace-search search-string limit
2104 regexp-flag delimited-flag
2105 case-fold-search backward)
2111 ;; Record whether the match is nonempty, to avoid an infinite loop
2112 ;; repeatedly matching the same empty string.
2113 (setq nonempty-match
2114 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2116 ;; If the match is empty, record that the next one can't be
2119 ;; Otherwise, if matching a regular expression, do the next
2120 ;; match now, since the replacement for this match may
2121 ;; affect whether the next match is adjacent to this one.
2122 ;; If that match is empty, don't use it.
2125 (or (not regexp-flag)
2127 (looking-back search-string)
2128 (looking-at search-string))
2129 (let ((match (match-data)))
2130 (and (/= (nth 0 match) (nth 1 match))
2134 ;; Optionally ignore matches that have a read-only property.
2135 ((not (or (not query-replace-skip-read-only)
2136 (not (text-property-not-all
2137 (nth 0 real-match-data) (nth 1 real-match-data)
2139 (setq skip-read-only-count (1+ skip-read-only-count)))
2140 ;; Optionally filter out matches.
2141 ((not (funcall isearch-filter-predicate
2142 (nth 0 real-match-data) (nth 1 real-match-data)))
2143 (setq skip-filtered-count (1+ skip-filtered-count)))
2144 ;; Optionally ignore invisible matches.
2145 ((not (or (eq search-invisible t)
2146 ;; Don't open overlays for automatic replacements.
2147 (and (not query-flag) search-invisible)
2148 ;; Open hidden overlays for interactive replacements.
2149 (not (isearch-range-invisible
2150 (nth 0 real-match-data) (nth 1 real-match-data)))))
2151 (setq skip-invisible-count (1+ skip-invisible-count)))
2153 ;; Calculate the replacement string, if necessary.
2155 (set-match-data real-match-data)
2156 (setq next-replacement
2157 (funcall (car replacements) (cdr replacements)
2159 (if (not query-flag)
2161 (unless (or literal noedit)
2163 (nth 0 real-match-data) (nth 1 real-match-data)
2164 start end search-string
2165 regexp-flag delimited-flag case-fold-search backward))
2167 (replace-match-maybe-edit
2168 next-replacement nocasify literal
2169 noedit real-match-data backward)
2170 replace-count (1+ replace-count)))
2172 (let (done replaced key def)
2173 ;; Loop reading commands until one of them sets done,
2174 ;; which means it has finished handling this
2175 ;; occurrence. Any command that sets `done' should
2176 ;; leave behind proper match data for the stack.
2177 ;; Commands not setting `done' need to adjust
2178 ;; `real-match-data'.
2180 (set-match-data real-match-data)
2182 (match-beginning 0) (match-end 0)
2183 start end search-string
2184 regexp-flag delimited-flag case-fold-search backward)
2185 ;; Bind message-log-max so we don't fill up the message log
2186 ;; with a bunch of identical messages.
2187 (let ((message-log-max nil)
2188 (replacement-presentation
2189 (if query-replace-show-replacement
2191 (set-match-data real-match-data)
2192 (match-substitute-replacement next-replacement
2196 (query-replace-descr from-string)
2197 (query-replace-descr replacement-presentation)))
2198 (setq key (read-event))
2199 ;; Necessary in case something happens during read-event
2200 ;; that clobbers the match data.
2201 (set-match-data real-match-data)
2202 (setq key (vector key))
2203 (setq def (lookup-key map key))
2204 ;; Restore the match data while we process the command.
2205 (cond ((eq def 'help)
2206 (with-output-to-temp-buffer "*Help*"
2208 (concat "Query replacing "
2210 (or (and (symbolp delimited-flag)
2211 (get delimited-flag 'isearch-message-prefix))
2213 (if regexp-flag "regexp " "")
2214 (if backward "backward " "")
2215 from-string " with "
2216 next-replacement ".\n\n"
2217 (substitute-command-keys
2218 query-replace-help)))
2219 (with-current-buffer standard-output
2222 (setq keep-going nil)
2224 ((eq def 'exit-current)
2225 (setq multi-buffer t keep-going nil done t))
2228 (let ((elt (pop stack)))
2229 (goto-char (nth 0 elt))
2230 (setq replaced (nth 1 elt)
2235 (message "No previous match")
2236 (ding 'no-terminate)
2241 (replace-match-maybe-edit
2242 next-replacement nocasify literal
2243 noedit real-match-data backward)
2244 replace-count (1+ replace-count)))
2245 (setq done t replaced t))
2246 ((eq def 'act-and-exit)
2249 (replace-match-maybe-edit
2250 next-replacement nocasify literal
2251 noedit real-match-data backward)
2252 replace-count (1+ replace-count)))
2253 (setq keep-going nil)
2254 (setq done t replaced t))
2255 ((eq def 'act-and-show)
2258 (replace-match-maybe-edit
2259 next-replacement nocasify literal
2260 noedit real-match-data backward)
2261 replace-count (1+ replace-count)
2262 real-match-data (replace-match-data
2265 ((or (eq def 'automatic) (eq def 'automatic-all))
2268 (replace-match-maybe-edit
2269 next-replacement nocasify literal
2270 noedit real-match-data backward)
2271 replace-count (1+ replace-count)))
2272 (setq done t query-flag nil replaced t)
2273 (if (eq def 'automatic-all) (setq multi-buffer t)))
2277 ;; `this-command' has the value `query-replace',
2278 ;; so we need to bind it to `recenter-top-bottom'
2279 ;; to allow it to detect a sequence of `C-l'.
2280 (let ((this-command 'recenter-top-bottom)
2281 (last-command 'recenter-top-bottom))
2282 (recenter-top-bottom)))
2284 (let ((opos (point-marker)))
2285 (setq real-match-data (replace-match-data
2288 (goto-char (match-beginning 0))
2290 (save-window-excursion
2293 (set-marker opos nil))
2294 ;; Before we make the replacement,
2295 ;; decide whether the search string
2296 ;; can match again just after this match.
2297 (if (and regexp-flag nonempty-match)
2298 (setq match-again (and (looking-at search-string)
2300 ;; Edit replacement.
2301 ((eq def 'edit-replacement)
2302 (setq real-match-data (replace-match-data
2306 (read-string "Edit replacement string: "
2310 (set-match-data real-match-data)
2312 (replace-match-maybe-edit
2313 next-replacement nocasify literal noedit
2314 real-match-data backward)
2318 ((eq def 'delete-and-edit)
2319 (replace-match "" t t)
2320 (setq real-match-data (replace-match-data
2321 nil real-match-data))
2322 (replace-dehighlight)
2323 (save-excursion (recursive-edit))
2325 ;; Note: we do not need to treat `exit-prefix'
2326 ;; specially here, since we reread
2327 ;; any unrecognized character.
2329 (setq this-command 'mode-exited)
2330 (setq keep-going nil)
2331 (setq unread-command-events
2332 (append (listify-key-sequence key)
2333 unread-command-events))
2335 (when query-replace-lazy-highlight
2336 ;; Force lazy rehighlighting only after replacements.
2337 (if (not (memq def '(skip backup)))
2338 (setq isearch-lazy-highlight-last-string nil)))
2339 (unless (eq def 'recenter)
2340 ;; Reset recenter cycling order to initial position.
2341 (setq recenter-last-op nil)))
2342 ;; Record previous position for ^ when we move on.
2343 ;; Change markers to numbers in the match data
2344 ;; since lots of markers slow down editing.
2345 (push (list (point) replaced
2346 ;;; If the replacement has already happened, all we need is the
2347 ;;; current match start and end. We could get this with a trivial
2349 ;;; (save-excursion (goto-char (match-beginning 0))
2350 ;;; (search-forward (match-string 0))
2352 ;;; if we really wanted to avoid manually constructing match data.
2353 ;;; Adding current-buffer is necessary so that match-data calls can
2354 ;;; return markers which are appropriate for editing.
2363 (replace-dehighlight))
2364 (or unread-command-events
2365 (message "Replaced %d occurrence%s%s"
2367 (if (= replace-count 1) "" "s")
2368 (if (> (+ skip-read-only-count
2370 skip-invisible-count) 0)
2371 (format " (skipped %s)"
2375 (if (> skip-read-only-count 0)
2376 (format "%s read-only"
2377 skip-read-only-count))
2378 (if (> skip-invisible-count 0)
2379 (format "%s invisible"
2380 skip-invisible-count))
2381 (if (> skip-filtered-count 0)
2382 (format "%s filtered out"
2383 skip-filtered-count))))
2386 (or (and keep-going stack) multi-buffer)))
2388 ;;; replace.el ends here