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
))))
229 (list from to current-prefix-arg
)))
231 (defun query-replace (from-string to-string
&optional delimited start end
)
232 "Replace some occurrences of FROM-STRING with TO-STRING.
233 As each match is found, the user must type a character saying
234 what to do with it. For directions, type \\[help-command] at that time.
236 In Transient Mark mode, if the mark is active, operate on the contents
237 of the region. Otherwise, operate from point to the end of the buffer.
239 Use \\<minibuffer-local-map>\\[next-history-element] \
240 to pull the last incremental search string to the minibuffer
241 that reads FROM-STRING, or invoke replacements from
242 incremental search with a key sequence like `C-s C-s M-%'
243 to use its current search string as the string to replace.
245 Matching is independent of case if `case-fold-search' is non-nil and
246 FROM-STRING has no uppercase letters. Replacement transfers the case
247 pattern of the old text to the new text, if `case-replace' and
248 `case-fold-search' are non-nil and FROM-STRING has no uppercase
249 letters. (Transferring the case pattern means that if the old text
250 matched is all caps, or capitalized, then its replacement is upcased
253 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
254 ignore hidden matches if `search-invisible' is nil, and ignore more
255 matches using `isearch-filter-predicate'.
257 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
258 to be replaced will match a sequence of whitespace chars defined by the
259 regexp in `search-whitespace-regexp'.
261 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
262 only matches surrounded by word boundaries.
263 Fourth and fifth arg START and END specify the region to operate on.
265 To customize possible responses, change the \"bindings\" in `query-replace-map'."
268 (query-replace-read-args
269 (concat "Query replace"
270 (if current-prefix-arg
" word" "")
271 (if (and transient-mark-mode mark-active
) " in region" ""))
273 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
274 ;; These are done separately here
275 ;; so that command-history will record these expressions
276 ;; rather than the values they had this time.
277 (if (and transient-mark-mode mark-active
)
279 (if (and transient-mark-mode mark-active
)
281 (perform-replace from-string to-string t nil delimited nil nil start end
))
283 (define-key esc-map
"%" 'query-replace
)
285 (defun query-replace-regexp (regexp to-string
&optional delimited start end
)
286 "Replace some things after point matching REGEXP with TO-STRING.
287 As each match is found, the user must type a character saying
288 what to do with it. For directions, type \\[help-command] at that time.
290 In Transient Mark mode, if the mark is active, operate on the contents
291 of the region. Otherwise, operate from point to the end of the buffer.
293 Use \\<minibuffer-local-map>\\[next-history-element] \
294 to pull the last incremental search regexp to the minibuffer
295 that reads REGEXP, or invoke replacements from
296 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
297 to use its current search regexp as the regexp to replace.
299 Matching is independent of case if `case-fold-search' is non-nil and
300 REGEXP has no uppercase letters. Replacement transfers the case
301 pattern of the old text to the new text, if `case-replace' and
302 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
303 \(Transferring the case pattern means that if the old text matched is
304 all caps, or capitalized, then its replacement is upcased or
307 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
308 ignore hidden matches if `search-invisible' is nil, and ignore more
309 matches using `isearch-filter-predicate'.
311 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
312 to be replaced will match a sequence of whitespace chars defined by the
313 regexp in `search-whitespace-regexp'.
315 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
316 only matches surrounded by word boundaries.
317 Fourth and fifth arg START and END specify the region to operate on.
319 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
320 and `\\=\\N' (where N is a digit) stands for
321 whatever what matched the Nth `\\(...\\)' in REGEXP.
322 `\\?' lets you edit the replacement text in the minibuffer
323 at the given position for each replacement.
325 In interactive calls, the replacement text can contain `\\,'
326 followed by a Lisp expression. Each
327 replacement evaluates that expression to compute the replacement
328 string. Inside of that expression, `\\&' is a string denoting the
329 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
330 for the whole or a partial match converted to a number with
331 `string-to-number', and `\\#' itself for the number of replacements
332 done so far (starting with zero).
334 If the replacement expression is a symbol, write a space after it
335 to terminate it. One space there, if any, will be discarded.
337 When using those Lisp features interactively in the replacement
338 text, TO-STRING is actually made a list instead of a string.
339 Use \\[repeat-complex-command] after this command for details."
342 (query-replace-read-args
343 (concat "Query replace"
344 (if current-prefix-arg
" word" "")
346 (if (and transient-mark-mode mark-active
) " in region" ""))
348 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
349 ;; These are done separately here
350 ;; so that command-history will record these expressions
351 ;; rather than the values they had this time.
352 (if (and transient-mark-mode mark-active
)
354 (if (and transient-mark-mode mark-active
)
356 (perform-replace regexp to-string t t delimited nil nil start end
))
358 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
360 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
361 "Replace some things after point matching REGEXP with the result of TO-EXPR.
363 Interactive use of this function is deprecated in favor of the
364 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
365 using `search-forward-regexp' and `replace-match' is preferred.
367 As each match is found, the user must type a character saying
368 what to do with it. For directions, type \\[help-command] at that time.
370 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
371 reference `replace-count' to get the number of replacements already made.
372 If the result of TO-EXPR is not a string, it is converted to one using
373 `prin1-to-string' with the NOESCAPE argument (which see).
375 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
376 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
377 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
378 Use `\\#&' or `\\#N' if you want a number instead of a string.
379 In interactive use, `\\#' in itself stands for `replace-count'.
381 In Transient Mark mode, if the mark is active, operate on the contents
382 of the region. Otherwise, operate from point to the end of the buffer.
384 Use \\<minibuffer-local-map>\\[next-history-element] \
385 to pull the last incremental search regexp to the minibuffer
388 Preserves case in each replacement if `case-replace' and `case-fold-search'
389 are non-nil and REGEXP has no uppercase letters.
391 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
392 ignore hidden matches if `search-invisible' is nil, and ignore more
393 matches using `isearch-filter-predicate'.
395 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
396 to be replaced will match a sequence of whitespace chars defined by the
397 regexp in `search-whitespace-regexp'.
399 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
400 only matches that are surrounded by word boundaries.
401 Fourth and fifth arg START and END specify the region to operate on."
402 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
403 for interactive calls, and `search-forward-regexp'/`replace-match'
404 for Lisp calls." "22.1"))
407 (barf-if-buffer-read-only)
409 ;; Let-bind the history var to disable the "foo -> bar"
410 ;; default. Maybe we shouldn't disable this default, but
411 ;; for now I'll leave it off. --Stef
412 (let ((query-replace-to-history-variable nil
))
413 (query-replace-read-from "Query replace regexp" t
)))
414 (to (list (read-from-minibuffer
415 (format "Query replace regexp %s with eval: "
416 (query-replace-descr from
))
417 nil nil t query-replace-to-history-variable from t
))))
418 ;; We make TO a list because replace-match-string-symbols requires one,
419 ;; and the user might enter a single token.
420 (replace-match-string-symbols to
)
421 (list from
(car to
) current-prefix-arg
422 (if (and transient-mark-mode mark-active
)
424 (if (and transient-mark-mode mark-active
)
426 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
427 t
'literal delimited nil nil start end
))
429 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
430 "Replace some matches for REGEXP with various strings, in rotation.
431 The second argument TO-STRINGS contains the replacement strings, separated
432 by spaces. This command works like `query-replace-regexp' except that
433 each successive replacement uses the next successive replacement string,
434 wrapping around from the last such string to the first.
436 In Transient Mark mode, if the mark is active, operate on the contents
437 of the region. Otherwise, operate from point to the end of the buffer.
439 Non-interactively, TO-STRINGS may be a list of replacement strings.
441 Use \\<minibuffer-local-map>\\[next-history-element] \
442 to pull the last incremental search regexp to the minibuffer
445 A prefix argument N says to use each replacement string N times
446 before rotating to the next.
447 Fourth and fifth arg START and END specify the region to operate on."
449 (let* ((from (read-regexp "Map query replace (regexp): " nil
450 query-replace-from-history-variable
))
451 (to (read-from-minibuffer
452 (format "Query replace %s with (space-separated strings): "
453 (query-replace-descr from
))
455 query-replace-to-history-variable from t
)))
457 (and current-prefix-arg
458 (prefix-numeric-value current-prefix-arg
))
459 (if (and transient-mark-mode mark-active
)
461 (if (and transient-mark-mode mark-active
)
464 (if (listp to-strings
)
465 (setq replacements to-strings
)
466 (while (/= (length to-strings
) 0)
467 (if (string-match " " to-strings
)
470 (list (substring to-strings
0
471 (string-match " " to-strings
))))
472 to-strings
(substring to-strings
473 (1+ (string-match " " to-strings
))))
474 (setq replacements
(append replacements
(list to-strings
))
476 (perform-replace regexp replacements t t nil n nil start end
)))
478 (defun replace-string (from-string to-string
&optional delimited start end
)
479 "Replace occurrences of FROM-STRING with TO-STRING.
480 Preserve case in each match if `case-replace' and `case-fold-search'
481 are non-nil and FROM-STRING has no uppercase letters.
482 \(Preserving case means that if the string matched is all caps, or capitalized,
483 then its replacement is upcased or capitalized.)
485 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
486 ignore hidden matches if `search-invisible' is nil, and ignore more
487 matches using `isearch-filter-predicate'.
489 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
490 to be replaced will match a sequence of whitespace chars defined by the
491 regexp in `search-whitespace-regexp'.
493 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
494 only matches surrounded by word boundaries.
496 Operates on the region between START and END (if both are nil, from point
497 to the end of the buffer). Interactively, if Transient Mark mode is
498 enabled and the mark is active, operates on the contents of the region;
499 otherwise from point to the end of the buffer.
501 Use \\<minibuffer-local-map>\\[next-history-element] \
502 to pull the last incremental search string to the minibuffer
503 that reads FROM-STRING.
505 This function is usually the wrong thing to use in a Lisp program.
506 What you probably want is a loop like this:
507 (while (search-forward FROM-STRING nil t)
508 (replace-match TO-STRING nil t))
509 which will run faster and will not set the mark or print anything.
510 \(You may need a more complex loop if FROM-STRING can match the null string
511 and TO-STRING is also null.)"
514 (query-replace-read-args
516 (if current-prefix-arg
" word" "")
518 (if (and transient-mark-mode mark-active
) " in region" ""))
520 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
521 (if (and transient-mark-mode mark-active
)
523 (if (and transient-mark-mode mark-active
)
525 (perform-replace from-string to-string nil nil delimited nil nil start end
))
526 (put 'replace-string
'interactive-only
527 "use `search-forward' and `replace-match' instead.")
529 (defun replace-regexp (regexp to-string
&optional delimited start end
)
530 "Replace things after point matching REGEXP with TO-STRING.
531 Preserve case in each match if `case-replace' and `case-fold-search'
532 are non-nil and REGEXP has no uppercase letters.
534 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
535 ignore hidden matches if `search-invisible' is nil, and ignore more
536 matches using `isearch-filter-predicate'.
538 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
539 to be replaced will match a sequence of whitespace chars defined by the
540 regexp in `search-whitespace-regexp'.
542 In Transient Mark mode, if the mark is active, operate on the contents
543 of the region. Otherwise, operate from point to the end of the buffer.
545 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
546 only matches surrounded by word boundaries.
547 Fourth and fifth arg START and END specify the region to operate on.
549 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
550 and `\\=\\N' (where N is a digit) stands for
551 whatever what matched the Nth `\\(...\\)' in REGEXP.
552 `\\?' lets you edit the replacement text in the minibuffer
553 at the given position for each replacement.
555 In interactive calls, the replacement text may contain `\\,'
556 followed by a Lisp expression used as part of the replacement
557 text. Inside of that expression, `\\&' is a string denoting the
558 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
559 numeric values from `string-to-number', and `\\#' itself for
560 `replace-count', the number of replacements occurred so far.
562 If your Lisp expression is an identifier and the next letter in
563 the replacement string would be interpreted as part of it, you
564 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
565 for this particular case you may also enter `\\#' in the
566 replacement text directly.
568 When using those Lisp features interactively in the replacement
569 text, TO-STRING is actually made a list instead of a string.
570 Use \\[repeat-complex-command] after this command for details.
572 Use \\<minibuffer-local-map>\\[next-history-element] \
573 to pull the last incremental search regexp to the minibuffer
576 This function is usually the wrong thing to use in a Lisp program.
577 What you probably want is a loop like this:
578 (while (re-search-forward REGEXP nil t)
579 (replace-match TO-STRING nil nil))
580 which will run faster and will not set the mark or print anything."
583 (query-replace-read-args
585 (if current-prefix-arg
" word" "")
587 (if (and transient-mark-mode mark-active
) " in region" ""))
589 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
590 (if (and transient-mark-mode mark-active
)
592 (if (and transient-mark-mode mark-active
)
594 (perform-replace regexp to-string nil t delimited nil nil start end
))
595 (put 'replace-regexp
'interactive-only
596 "use `re-search-forward' and `replace-match' instead.")
599 (defvar regexp-history nil
600 "History list for some commands that read regular expressions.
602 Maximum length of the history list is determined by the value
603 of `history-length', which see.")
605 (defvar occur-collect-regexp-history
'("\\1")
606 "History of regexp for occur's collect operation")
608 (defun read-regexp (prompt &optional defaults history
)
609 "Read and return a regular expression as a string.
610 When PROMPT doesn't end with a colon and space, it adds a final \": \".
611 If the first element of DEFAULTS is non-nil, it's added to the prompt.
613 Optional arg DEFAULTS has the form (DEFAULT . SUGGESTIONS)
614 or simply DEFAULT where DEFAULT, if non-nil, should be a string that
615 is returned as the default value when the user enters empty input.
616 SUGGESTIONS is a list of strings that can be inserted into
617 the minibuffer using \\<minibuffer-local-map>\\[next-history-element]. \
618 The values supplied in SUGGESTIONS
619 are prepended to the list of standard suggestions that include
620 the tag at point, the last isearch regexp, the last isearch string,
621 and the last replacement regexp.
623 Optional arg HISTORY is a symbol to use for the history list.
624 If HISTORY is nil, `regexp-history' is used."
625 (let* ((default (if (consp defaults
) (car defaults
) defaults
))
626 (suggestions (if (listp defaults
) defaults
(list defaults
)))
631 (find-tag-default-as-regexp)
632 (car regexp-search-ring
)
633 (regexp-quote (or (car search-ring
) ""))
634 (car (symbol-value query-replace-from-history-variable
)))))
635 (suggestions (delete-dups (delq nil
(delete "" suggestions
))))
636 ;; Do not automatically add default to the history for empty input.
637 (history-add-new-input nil
)
638 (input (read-from-minibuffer
639 (cond ((string-match-p ":[ \t]*\\'" prompt
)
642 (format "%s (default %s): " prompt
643 (query-replace-descr default
)))
645 (format "%s: " prompt
)))
646 nil nil nil
(or history
'regexp-history
) suggestions t
)))
648 ;; Return the default value when the user enters empty input.
650 ;; Otherwise, add non-empty input to the history and return input.
652 (add-to-history (or history
'regexp-history
) input
)))))
655 (defalias 'delete-non-matching-lines
'keep-lines
)
656 (defalias 'delete-matching-lines
'flush-lines
)
657 (defalias 'count-matches
'how-many
)
660 (defun keep-lines-read-args (prompt)
661 "Read arguments for `keep-lines' and friends.
662 Prompt for a regexp with PROMPT.
663 Value is a list, (REGEXP)."
664 (list (read-regexp prompt
) nil nil t
))
666 (defun keep-lines (regexp &optional rstart rend interactive
)
667 "Delete all lines except those containing matches for REGEXP.
668 A match split across lines preserves all the lines it lies in.
669 When called from Lisp (and usually interactively as well, see below)
670 applies to all lines starting after point.
672 If REGEXP contains upper case characters (excluding those preceded by `\\')
673 and `search-upper-case' is non-nil, the matching is case-sensitive.
675 Second and third arg RSTART and REND specify the region to operate on.
676 This command operates on (the accessible part of) all lines whose
677 accessible part is entirely contained in the region determined by RSTART
678 and REND. (A newline ending a line counts as part of that line.)
680 Interactively, in Transient Mark mode when the mark is active, operate
681 on all lines whose accessible part is entirely contained in the region.
682 Otherwise, the command applies to all lines starting after point.
683 When calling this function from Lisp, you can pretend that it was
684 called interactively by passing a non-nil INTERACTIVE argument.
686 This function starts looking for the next match from the end of
687 the previous match. Hence, it ignores matches that overlap
688 a previously found match."
692 (barf-if-buffer-read-only)
693 (keep-lines-read-args "Keep lines containing match for regexp")))
696 (goto-char (min rstart rend
))
700 (goto-char (max rstart rend
))
701 (unless (or (bolp) (eobp))
704 (if (and interactive transient-mark-mode mark-active
)
705 (setq rstart
(region-beginning)
707 (goto-char (region-end))
708 (unless (or (bolp) (eobp))
712 rend
(point-max-marker)))
715 (or (bolp) (forward-line 1))
716 (let ((start (point))
718 (if (and case-fold-search search-upper-case
)
719 (isearch-no-upper-case-p regexp t
)
721 (while (< (point) rend
)
722 ;; Start is first char not preserved by previous match.
723 (if (not (re-search-forward regexp rend
'move
))
724 (delete-region start rend
)
725 (let ((end (save-excursion (goto-char (match-beginning 0))
728 ;; Now end is first char preserved by the new match.
730 (delete-region start end
))))
732 (setq start
(save-excursion (forward-line 1) (point)))
733 ;; If the match was empty, avoid matching again at same place.
734 (and (< (point) rend
)
735 (= (match-beginning 0) (match-end 0))
737 (set-marker rend nil
)
741 (defun flush-lines (regexp &optional rstart rend interactive
)
742 "Delete lines containing matches for REGEXP.
743 When called from Lisp (and usually when called interactively as
744 well, see below), applies to the part of the buffer after point.
745 The line point is in is deleted if and only if it contains a
746 match for regexp starting after point.
748 If REGEXP contains upper case characters (excluding those preceded by `\\')
749 and `search-upper-case' is non-nil, the matching is case-sensitive.
751 Second and third arg RSTART and REND specify the region to operate on.
752 Lines partially contained in this region are deleted if and only if
753 they contain a match entirely contained in it.
755 Interactively, in Transient Mark mode when the mark is active, operate
756 on the contents of the region. Otherwise, operate from point to the
757 end of (the accessible portion of) the buffer. When calling this function
758 from Lisp, you can pretend that it was called interactively by passing
759 a non-nil INTERACTIVE argument.
761 If a match is split across lines, all the lines it lies in are deleted.
762 They are deleted _before_ looking for the next match. Hence, a match
763 starting on the same line at which another match ended is ignored."
767 (barf-if-buffer-read-only)
768 (keep-lines-read-args "Flush lines containing match for regexp")))
771 (goto-char (min rstart rend
))
772 (setq rend
(copy-marker (max rstart rend
))))
773 (if (and interactive transient-mark-mode mark-active
)
774 (setq rstart
(region-beginning)
775 rend
(copy-marker (region-end)))
777 rend
(point-max-marker)))
779 (let ((case-fold-search
780 (if (and case-fold-search search-upper-case
)
781 (isearch-no-upper-case-p regexp t
)
784 (while (and (< (point) rend
)
785 (re-search-forward regexp rend t
))
786 (delete-region (save-excursion (goto-char (match-beginning 0))
789 (progn (forward-line 1) (point))))))
790 (set-marker rend nil
)
794 (defun how-many (regexp &optional rstart rend interactive
)
795 "Print and return number of matches for REGEXP following point.
796 When called from Lisp and INTERACTIVE is omitted or nil, just return
797 the number, do not print it; if INTERACTIVE is t, the function behaves
798 in all respects as if it had been called interactively.
800 If REGEXP contains upper case characters (excluding those preceded by `\\')
801 and `search-upper-case' is non-nil, the matching is case-sensitive.
803 Second and third arg RSTART and REND specify the region to operate on.
805 Interactively, in Transient Mark mode when the mark is active, operate
806 on the contents of the region. Otherwise, operate from point to the
807 end of (the accessible portion of) the buffer.
809 This function starts looking for the next match from the end of
810 the previous match. Hence, it ignores matches that overlap
811 a previously found match."
814 (keep-lines-read-args "How many matches for regexp"))
819 (goto-char (min rstart rend
))
820 (setq rend
(max rstart rend
)))
822 (setq rend
(point-max)))
823 (if (and interactive transient-mark-mode mark-active
)
824 (setq rstart
(region-beginning)
832 (if (and case-fold-search search-upper-case
)
833 (isearch-no-upper-case-p regexp t
)
835 (while (and (< (point) rend
)
836 (progn (setq opoint
(point))
837 (re-search-forward regexp rend t
)))
838 (if (= opoint
(point))
840 (setq count
(1+ count
))))
841 (when interactive
(message "%d occurrence%s"
843 (if (= count
1) "" "s")))
847 (defvar occur-menu-map
848 (let ((map (make-sparse-keymap)))
849 (bindings--define-key map
[next-error-follow-minor-mode
]
850 '(menu-item "Auto Occurrence Display"
851 next-error-follow-minor-mode
852 :help
"Display another occurrence when moving the cursor"
853 :button
(:toggle .
(and (boundp 'next-error-follow-minor-mode
)
854 next-error-follow-minor-mode
))))
855 (bindings--define-key map
[separator-1
] menu-bar-separator
)
856 (bindings--define-key map
[kill-this-buffer
]
857 '(menu-item "Kill Occur Buffer" kill-this-buffer
858 :help
"Kill the current *Occur* buffer"))
859 (bindings--define-key map
[quit-window
]
860 '(menu-item "Quit Occur Window" quit-window
861 :help
"Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
862 (bindings--define-key map
[revert-buffer
]
863 '(menu-item "Revert Occur Buffer" revert-buffer
864 :help
"Replace the text in the *Occur* buffer with the results of rerunning occur"))
865 (bindings--define-key map
[clone-buffer
]
866 '(menu-item "Clone Occur Buffer" clone-buffer
867 :help
"Create and return a twin copy of the current *Occur* buffer"))
868 (bindings--define-key map
[occur-rename-buffer
]
869 '(menu-item "Rename Occur Buffer" occur-rename-buffer
870 :help
"Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
871 (bindings--define-key map
[occur-edit-buffer
]
872 '(menu-item "Edit Occur Buffer" occur-edit-mode
873 :help
"Edit the *Occur* buffer and apply changes to the original buffers."))
874 (bindings--define-key map
[separator-2
] menu-bar-separator
)
875 (bindings--define-key map
[occur-mode-goto-occurrence-other-window
]
876 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
877 :help
"Go to the occurrence the current line describes, in another window"))
878 (bindings--define-key map
[occur-mode-goto-occurrence
]
879 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
880 :help
"Go to the occurrence the current line describes"))
881 (bindings--define-key map
[occur-mode-display-occurrence
]
882 '(menu-item "Display Occurrence" occur-mode-display-occurrence
883 :help
"Display in another window the occurrence the current line describes"))
884 (bindings--define-key map
[occur-next
]
885 '(menu-item "Move to Next Match" occur-next
886 :help
"Move to the Nth (default 1) next match in an Occur mode buffer"))
887 (bindings--define-key map
[occur-prev
]
888 '(menu-item "Move to Previous Match" occur-prev
889 :help
"Move to the Nth (default 1) previous match in an Occur mode buffer"))
891 "Menu keymap for `occur-mode'.")
893 (defvar occur-mode-map
894 (let ((map (make-sparse-keymap)))
895 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
896 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
897 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
898 (define-key map
"e" 'occur-edit-mode
)
899 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
900 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
901 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
902 (define-key map
"\M-n" 'occur-next
)
903 (define-key map
"\M-p" 'occur-prev
)
904 (define-key map
"r" 'occur-rename-buffer
)
905 (define-key map
"c" 'clone-buffer
)
906 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
907 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
909 "Keymap for `occur-mode'.")
911 (defvar occur-revert-arguments nil
912 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
913 See `occur-revert-function'.")
914 (make-variable-buffer-local 'occur-revert-arguments
)
915 (put 'occur-revert-arguments
'permanent-local t
)
917 (defcustom occur-mode-hook
'(turn-on-font-lock)
918 "Hook run when entering Occur mode."
922 (defcustom occur-hook nil
923 "Hook run by Occur when there are any matches."
927 (defcustom occur-mode-find-occurrence-hook nil
928 "Hook run by Occur after locating an occurrence.
929 This will be called with the cursor position at the occurrence. An application
930 for this is to reveal context in an outline-mode when the occurrence is hidden."
934 (put 'occur-mode
'mode-class
'special
)
935 (define-derived-mode occur-mode special-mode
"Occur"
936 "Major mode for output from \\[occur].
937 \\<occur-mode-map>Move point to one of the items in this buffer, then use
938 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
939 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
942 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
943 (setq next-error-function
'occur-next-error
))
948 (defvar occur-edit-mode-map
949 (let ((map (make-sparse-keymap)))
950 (set-keymap-parent map text-mode-map
)
951 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
952 (define-key map
"\C-c\C-c" 'occur-cease-edit
)
953 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
954 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
955 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
957 "Keymap for `occur-edit-mode'.")
959 (define-derived-mode occur-edit-mode occur-mode
"Occur-Edit"
960 "Major mode for editing *Occur* buffers.
961 In this mode, changes to the *Occur* buffer are also applied to
962 the originating buffer.
964 To return to ordinary Occur mode, use \\[occur-cease-edit]."
965 (setq buffer-read-only nil
)
966 (add-hook 'after-change-functions
'occur-after-change-function nil t
)
967 (message (substitute-command-keys
968 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
970 (defun occur-cease-edit ()
971 "Switch from Occur Edit mode to Occur mode."
973 (when (derived-mode-p 'occur-edit-mode
)
975 (message "Switching to Occur mode.")))
977 (defun occur-after-change-function (beg end length
)
980 (let* ((line-beg (line-beginning-position))
981 (m (get-text-property line-beg
'occur-target
))
982 (buf (marker-buffer m
))
984 (when (and (get-text-property line-beg
'occur-prefix
)
985 (not (get-text-property end
'occur-prefix
)))
987 ;; Apply occur-target property to inserted (e.g. yanked) text.
988 (put-text-property beg end
'occur-target m
)
989 ;; Did we insert a newline? Occur Edit mode can't create new
990 ;; Occur entries; just discard everything after the newline.
992 (and (search-forward "\n" end t
)
993 (delete-region (1- (point)) end
))))
994 (let* ((line (- (line-number-at-pos)
995 (line-number-at-pos (window-start))))
996 (readonly (with-current-buffer buf buffer-read-only
))
997 (win (or (get-buffer-window buf
)
999 '(nil (inhibit-same-window . t
)
1000 (inhibit-switch-frame . t
)))))
1001 (line-end (line-end-position))
1002 (text (save-excursion
1003 (goto-char (next-single-property-change
1004 line-beg
'occur-prefix nil
1006 (setq col
(- (point) line-beg
))
1007 (buffer-substring-no-properties (point) line-end
))))
1008 (with-selected-window win
1012 (message "Buffer `%s' is read only." buf
)
1013 (delete-region (line-beginning-position) (line-end-position))
1015 (move-to-column col
)))))))
1018 (defun occur-revert-function (_ignore1 _ignore2
)
1019 "Handle `revert-buffer' for Occur mode buffers."
1020 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
1022 (defun occur-mode-find-occurrence ()
1023 (let ((pos (get-text-property (point) 'occur-target
)))
1025 (error "No occurrence on this line"))
1026 (unless (buffer-live-p (marker-buffer pos
))
1027 (error "Buffer for this occurrence was killed"))
1030 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
1031 (defun occur-mode-goto-occurrence (&optional event
)
1032 "Go to the occurrence on the current line."
1033 (interactive (list last-nonmenu-event
))
1036 ;; Actually `event-end' works correctly with a nil argument as
1037 ;; well, so we could dispense with this test, but let's not
1038 ;; rely on this undocumented behavior.
1039 (occur-mode-find-occurrence)
1040 (with-current-buffer (window-buffer (posn-window (event-end event
)))
1042 (goto-char (posn-point (event-end event
)))
1043 (occur-mode-find-occurrence))))))
1044 (pop-to-buffer (marker-buffer pos
))
1046 (run-hooks 'occur-mode-find-occurrence-hook
)))
1048 (defun occur-mode-goto-occurrence-other-window ()
1049 "Go to the occurrence the current line describes, in another window."
1051 (let ((pos (occur-mode-find-occurrence)))
1052 (switch-to-buffer-other-window (marker-buffer pos
))
1054 (run-hooks 'occur-mode-find-occurrence-hook
)))
1056 (defun occur-mode-display-occurrence ()
1057 "Display in another window the occurrence the current line describes."
1059 (let ((pos (occur-mode-find-occurrence))
1061 (setq window
(display-buffer (marker-buffer pos
) t
))
1062 ;; This is the way to set point in the proper window.
1063 (save-selected-window
1064 (select-window window
)
1066 (run-hooks 'occur-mode-find-occurrence-hook
))))
1068 (defun occur-find-match (n search message
)
1069 (if (not n
) (setq n
1))
1072 (setq r
(funcall search
(point) 'occur-match
))
1074 (get-text-property r
'occur-match
)
1075 (setq r
(funcall search r
'occur-match
)))
1081 (defun occur-next (&optional n
)
1082 "Move to the Nth (default 1) next match in an Occur mode buffer."
1084 (occur-find-match n
#'next-single-property-change
"No more matches"))
1086 (defun occur-prev (&optional n
)
1087 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1089 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
1091 (defun occur-next-error (&optional argp reset
)
1092 "Move to the Nth (default 1) next match in an Occur mode buffer.
1093 Compatibility function for \\[next-error] invocations."
1095 ;; we need to run occur-find-match from within the Occur buffer
1096 (with-current-buffer
1097 ;; Choose the buffer and make it current.
1098 (if (next-error-buffer-p (current-buffer))
1100 (next-error-find-buffer nil nil
1102 (eq major-mode
'occur-mode
))))
1104 (goto-char (cond (reset (point-min))
1105 ((< argp
0) (line-beginning-position))
1106 ((> argp
0) (line-end-position))
1111 #'previous-single-property-change
1112 #'next-single-property-change
)
1114 ;; In case the *Occur* buffer is visible in a nonselected window.
1115 (let ((win (get-buffer-window (current-buffer) t
)))
1116 (if win
(set-window-point win
(point))))
1117 (occur-mode-goto-occurrence)))
1120 '((((class color
) (min-colors 88) (background light
))
1121 :background
"yellow1")
1122 (((class color
) (min-colors 88) (background dark
))
1123 :background
"RoyalBlue3")
1124 (((class color
) (min-colors 8) (background light
))
1125 :background
"yellow" :foreground
"black")
1126 (((class color
) (min-colors 8) (background dark
))
1127 :background
"blue" :foreground
"white")
1128 (((type tty
) (class mono
))
1130 (t :background
"gray"))
1131 "Face used to highlight matches permanently."
1135 (defcustom list-matching-lines-default-context-lines
0
1136 "Default number of context lines included around `list-matching-lines' matches.
1137 A negative number means to include that many lines before the match.
1138 A positive number means to include that many lines both before and after."
1142 (defalias 'list-matching-lines
'occur
)
1144 (defcustom list-matching-lines-face
'match
1145 "Face used by \\[list-matching-lines] to show the text that matches.
1146 If the value is nil, don't highlight the matching portions specially."
1150 (defcustom list-matching-lines-buffer-name-face
'underline
1151 "Face used by \\[list-matching-lines] to show the names of buffers.
1152 If the value is nil, don't highlight the buffer names specially."
1156 (defcustom list-matching-lines-prefix-face
'shadow
1157 "Face used by \\[list-matching-lines] to show the prefix column.
1158 If the face doesn't differ from the default face,
1159 don't highlight the prefix with line numbers specially."
1164 (defcustom occur-excluded-properties
1165 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1166 yank-handler follow-link
)
1167 "Text properties to discard when copying lines to the *Occur* buffer.
1168 The value should be a list of text properties to discard or t,
1169 which means to discard all text properties."
1170 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
1174 (defvar occur-read-regexp-defaults-function
1175 'occur-read-regexp-defaults
1176 "Function that provides default regexp(s) for occur commands.
1177 This function should take no arguments and return one of nil, a
1178 regexp or a list of regexps for use with occur commands -
1179 `occur', `multi-occur' and `multi-occur-in-matching-buffers'.
1180 The return value of this function is used as DEFAULTS param of
1181 `read-regexp' while executing the occur command. This function
1182 is called only during interactive use.
1184 For example, to check for occurrence of symbol at point use
1186 (setq occur-read-regexp-defaults-function
1187 'find-tag-default-as-regexp).")
1189 (defun occur-read-regexp-defaults ()
1190 "Return the latest regexp from `regexp-history'.
1191 See `occur-read-regexp-defaults-function' for details."
1192 (car regexp-history
))
1194 (defun occur-read-primary-args ()
1195 (let* ((perform-collect (consp current-prefix-arg
))
1196 (regexp (read-regexp (if perform-collect
1197 "Collect strings matching regexp"
1198 "List lines matching regexp")
1199 (funcall occur-read-regexp-defaults-function
))))
1202 ;; Perform collect operation
1203 (if (zerop (regexp-opt-depth regexp
))
1204 ;; No subexpression so collect the entire match.
1206 ;; Get the regexp for collection pattern.
1207 (let ((default (car occur-collect-regexp-history
)))
1209 (format "Regexp to collect (default %s): " default
)
1210 default
'occur-collect-regexp-history
)))
1211 ;; Otherwise normal occur takes numerical prefix argument.
1212 (when current-prefix-arg
1213 (prefix-numeric-value current-prefix-arg
))))))
1215 (defun occur-rename-buffer (&optional unique-p interactive-p
)
1216 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1217 Here `original-buffer-name' is the buffer name where Occur was originally run.
1218 When given the prefix argument, or called non-interactively, the renaming
1219 will not clobber the existing buffer(s) of that name, but use
1220 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1221 if you always want a separate *Occur* buffer for each buffer where you
1223 (interactive "P\np")
1224 (with-current-buffer
1225 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
1226 (rename-buffer (concat "*Occur: "
1227 (mapconcat #'buffer-name
1228 (car (cddr occur-revert-arguments
)) "/")
1230 (or unique-p
(not interactive-p
)))))
1232 (defun occur (regexp &optional nlines
)
1233 "Show all lines in the current buffer containing a match for REGEXP.
1234 If a match spreads across multiple lines, all those lines are shown.
1236 Each line is displayed with NLINES lines before and after, or -NLINES
1237 before if NLINES is negative.
1238 NLINES defaults to `list-matching-lines-default-context-lines'.
1239 Interactively it is the prefix arg.
1241 The lines are shown in a buffer named `*Occur*'.
1242 It serves as a menu to find any of the occurrences in this buffer.
1243 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1245 If REGEXP contains upper case characters (excluding those preceded by `\\')
1246 and `search-upper-case' is non-nil, the matching is case-sensitive.
1248 When NLINES is a string or when the function is called
1249 interactively with prefix argument without a number (`C-u' alone
1250 as prefix) the matching strings are collected into the `*Occur*'
1251 buffer by using NLINES as a replacement regexp. NLINES may
1252 contain \\& and \\N which convention follows `replace-match'.
1253 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1254 \"\\1\" for NLINES collects all the function names in a lisp
1255 program. When there is no parenthesized subexpressions in REGEXP
1256 the entire match is collected. In any case the searched buffer
1258 (interactive (occur-read-primary-args))
1259 (occur-1 regexp nlines
(list (current-buffer))))
1261 (defvar ido-ignore-item-temp-list
)
1263 (defun multi-occur (bufs regexp
&optional nlines
)
1264 "Show all lines in buffers BUFS containing a match for REGEXP.
1265 This function acts on multiple buffers; otherwise, it is exactly like
1266 `occur'. When you invoke this command interactively, you must specify
1267 the buffer names that you want, one by one.
1268 See also `multi-occur-in-matching-buffers'."
1271 (let* ((bufs (list (read-buffer "First buffer to search: "
1272 (current-buffer) t
)))
1274 (ido-ignore-item-temp-list bufs
))
1275 (while (not (string-equal
1276 (setq buf
(read-buffer
1277 (if (eq read-buffer-function
'ido-read-buffer
)
1278 "Next buffer to search (C-j to end): "
1279 "Next buffer to search (RET to end): ")
1282 (add-to-list 'bufs buf
)
1283 (setq ido-ignore-item-temp-list bufs
))
1284 (nreverse (mapcar #'get-buffer bufs
)))
1285 (occur-read-primary-args)))
1286 (occur-1 regexp nlines bufs
))
1288 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1289 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1290 Normally BUFREGEXP matches against each buffer's visited file name,
1291 but if you specify a prefix argument, it matches against the buffer name.
1292 See also `multi-occur'."
1295 (let* ((default (car regexp-history
))
1298 (if current-prefix-arg
1299 "List lines in buffers whose names match regexp: "
1300 "List lines in buffers whose filenames match regexp: "))))
1301 (if (equal input
"")
1304 (occur-read-primary-args)))
1308 (mapcar (lambda (buf)
1310 (string-match bufregexp
1312 (and (buffer-file-name buf
)
1313 (string-match bufregexp
1314 (buffer-file-name buf
))))
1318 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1319 (unless (and regexp
(not (equal regexp
"")))
1320 (error "Occur doesn't work with the empty regexp"))
1322 (setq buf-name
"*Occur*"))
1324 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1325 (when (buffer-live-p buf
) buf
))
1327 ;; Handle the case where one of the buffers we're searching is the
1328 ;; output buffer. Just rename it.
1329 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1330 (with-current-buffer (get-buffer buf-name
)
1333 ;; Now find or create the output buffer.
1334 ;; If we just renamed that buffer, we will make a new one here.
1335 (setq occur-buf
(get-buffer-create buf-name
))
1337 (with-current-buffer occur-buf
1338 (if (stringp nlines
)
1339 (fundamental-mode) ;; This is for collect operation.
1341 (let ((inhibit-read-only t
)
1342 ;; Don't generate undo entries for creation of the initial contents.
1343 (buffer-undo-list t
))
1346 (if (stringp nlines
)
1347 ;; Treat nlines as a regexp to collect.
1348 (let ((bufs active-bufs
)
1351 (with-current-buffer (car bufs
)
1353 (goto-char (point-min))
1354 (while (re-search-forward regexp nil t
)
1355 ;; Insert the replacement regexp.
1356 (let ((str (match-substitute-replacement nlines
)))
1358 (with-current-buffer occur-buf
1360 (setq count
(1+ count
))
1361 (or (zerop (current-column))
1362 (insert "\n"))))))))
1363 (setq bufs
(cdr bufs
)))
1365 ;; Perform normal occur.
1367 regexp active-bufs occur-buf
1368 (or nlines list-matching-lines-default-context-lines
)
1369 (if (and case-fold-search search-upper-case
)
1370 (isearch-no-upper-case-p regexp t
)
1372 list-matching-lines-buffer-name-face
1373 (if (face-differs-from-default-p list-matching-lines-prefix-face
)
1374 list-matching-lines-prefix-face
)
1375 list-matching-lines-face
1376 (not (eq occur-excluded-properties t
))))))
1377 (let* ((bufcount (length active-bufs
))
1378 (diff (- (length bufs
) bufcount
)))
1379 (message "Searched %d buffer%s%s; %s match%s%s"
1380 bufcount
(if (= bufcount
1) "" "s")
1381 (if (zerop diff
) "" (format " (%d killed)" diff
))
1382 (if (zerop count
) "no" (format "%d" count
))
1383 (if (= count
1) "" "es")
1384 ;; Don't display regexp if with remaining text
1385 ;; it is longer than window-width.
1386 (if (> (+ (length regexp
) 42) (window-width))
1387 "" (format " for `%s'" (query-replace-descr regexp
)))))
1388 (setq occur-revert-arguments
(list regexp nlines bufs
))
1390 (kill-buffer occur-buf
)
1391 (display-buffer occur-buf
)
1392 (setq next-error-last-buffer occur-buf
)
1393 (setq buffer-read-only t
)
1394 (set-buffer-modified-p nil
)
1395 (run-hooks 'occur-hook
)))))))
1397 (defun occur-engine (regexp buffers out-buf nlines case-fold
1398 title-face prefix-face match-face keep-props
)
1399 (with-current-buffer out-buf
1400 (let ((global-lines 0) ;; total count of matching lines
1401 (global-matches 0) ;; total count of matches
1403 (case-fold-search case-fold
))
1404 ;; Map over all the buffers
1405 (dolist (buf buffers
)
1406 (when (buffer-live-p buf
)
1407 (let ((lines 0) ;; count of matching lines
1408 (matches 0) ;; count of matches
1409 (curr-line 1) ;; line count
1410 (prev-line nil
) ;; line number of prev match endpt
1411 (prev-after-lines nil
) ;; context lines of prev match
1419 (inhibit-field-text-motion t
)
1420 (headerpt (with-current-buffer out-buf
(point))))
1421 (with-current-buffer buf
1423 ;; Set CODING only if the current buffer locally
1424 ;; binds buffer-file-coding-system.
1425 (not (local-variable-p 'buffer-file-coding-system
))
1426 (setq coding buffer-file-coding-system
))
1428 (goto-char (point-min)) ;; begin searching in the buffer
1430 (setq origpt
(point))
1431 (when (setq endpt
(re-search-forward regexp nil t
))
1432 (setq lines
(1+ lines
)) ;; increment matching lines count
1433 (setq matchbeg
(match-beginning 0))
1434 ;; Get beginning of first match line and end of the last.
1436 (goto-char matchbeg
)
1437 (setq begpt
(line-beginning-position))
1439 (setq endpt
(line-end-position)))
1440 ;; Sum line numbers up to the first match line.
1441 (setq curr-line
(+ curr-line
(count-lines origpt begpt
)))
1442 (setq marker
(make-marker))
1443 (set-marker marker matchbeg
)
1444 (setq curstring
(occur-engine-line begpt endpt keep-props
))
1445 ;; Highlight the matches
1446 (let ((len (length curstring
))
1448 (while (and (< start len
)
1449 (string-match regexp curstring start
))
1450 (setq matches
(1+ matches
))
1451 (add-text-properties
1452 (match-beginning 0) (match-end 0)
1456 ;; Use `face' rather than `font-lock-face' here
1457 ;; so as to override faces copied from the buffer.
1458 `(face ,match-face
)))
1460 (setq start
(match-end 0))))
1461 ;; Generate the string to insert for this match
1462 (let* ((match-prefix
1463 ;; Using 7 digits aligns tabs properly.
1464 (apply #'propertize
(format "%7d:" curr-line
)
1467 `(font-lock-face ,prefix-face
))
1468 `(occur-prefix t mouse-face
(highlight)
1469 ;; Allow insertion of text at
1470 ;; the end of the prefix (for
1471 ;; Occur Edit mode).
1472 front-sticky t rear-nonsticky t
1473 occur-target
,marker follow-link t
1474 help-echo
"mouse-2: go to this occurrence"))))
1476 ;; We don't put `mouse-face' on the newline,
1477 ;; because that loses. And don't put it
1478 ;; on context lines to reduce flicker.
1479 (propertize curstring
'mouse-face
(list 'highlight
)
1480 'occur-target marker
1483 "mouse-2: go to this occurrence"))
1487 ;; Add non-numeric prefix to all non-first lines
1488 ;; of multi-line matches.
1489 (replace-regexp-in-string
1492 (propertize "\n :" 'font-lock-face prefix-face
)
1495 ;; Add marker at eol, but no mouse props.
1496 (propertize "\n" 'occur-target marker
)))
1499 ;; The simple display style
1501 ;; The complex multi-line display style.
1502 (setq ret
(occur-context-lines
1503 out-line nlines keep-props begpt endpt
1504 curr-line prev-line prev-after-lines
1506 ;; Set first elem of the returned list to `data',
1507 ;; and the second elem to `prev-after-lines'.
1508 (setq prev-after-lines
(nth 1 ret
))
1510 ;; Actually insert the match display data
1511 (with-current-buffer out-buf
1516 ;; Sum line numbers between first and last match lines.
1517 (setq curr-line
(+ curr-line
(count-lines begpt endpt
)
1518 ;; Add 1 for empty last match line since
1519 ;; count-lines returns 1 line less.
1520 (if (and (bolp) (eolp)) 1 0)))
1521 ;; On to the next match...
1523 (goto-char (point-max)))
1524 (setq prev-line
(1- curr-line
)))
1525 ;; Flush remaining context after-lines.
1526 (when prev-after-lines
1527 (with-current-buffer out-buf
1528 (insert (apply #'concat
(occur-engine-add-prefix
1529 prev-after-lines prefix-face
)))))))
1530 (when (not (zerop lines
)) ;; is the count zero?
1531 (setq global-lines
(+ global-lines lines
)
1532 global-matches
(+ global-matches matches
))
1533 (with-current-buffer out-buf
1534 (goto-char headerpt
)
1538 (format "%d match%s%s%s in buffer: %s\n"
1539 matches
(if (= matches
1) "" "es")
1540 ;; Don't display the same number of lines
1541 ;; and matches in case of 1 match per line.
1542 (if (= lines matches
)
1543 "" (format " in %d line%s"
1544 lines
(if (= lines
1) "" "s")))
1545 ;; Don't display regexp for multi-buffer.
1546 (if (> (length buffers
) 1)
1547 "" (format " for \"%s\""
1548 (query-replace-descr regexp
)))
1552 (add-text-properties beg end
1555 `(font-lock-face ,title-face
))
1556 `(occur-title ,buf
))))
1557 (goto-char (point-min)))))))
1558 ;; Display total match count and regexp for multi-buffer.
1559 (when (and (not (zerop global-lines
)) (> (length buffers
) 1))
1560 (goto-char (point-min))
1563 (insert (format "%d match%s%s total for \"%s\":\n"
1564 global-matches
(if (= global-matches
1) "" "es")
1565 ;; Don't display the same number of lines
1566 ;; and matches in case of 1 match per line.
1567 (if (= global-lines global-matches
)
1568 "" (format " in %d line%s"
1569 global-lines
(if (= global-lines
1) "" "s")))
1570 (query-replace-descr regexp
)))
1572 (add-text-properties beg end
(when title-face
1573 `(font-lock-face ,title-face
))))
1574 (goto-char (point-min)))
1576 ;; CODING is buffer-file-coding-system of the first buffer
1577 ;; that locally binds it. Let's use it also for the output
1579 (set-buffer-file-coding-system coding
))
1580 ;; Return the number of matches
1583 (defun occur-engine-line (beg end
&optional keep-props
)
1584 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
1585 (text-property-not-all beg end
'fontified t
))
1586 (if (fboundp 'jit-lock-fontify-now
)
1587 (jit-lock-fontify-now beg end
)))
1588 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1589 (let ((str (buffer-substring beg end
)))
1590 (remove-list-of-text-properties
1591 0 (length str
) occur-excluded-properties str
)
1593 (buffer-substring-no-properties beg end
)))
1595 (defun occur-engine-add-prefix (lines &optional prefix-face
)
1598 (concat (if prefix-face
1599 (propertize " :" 'font-lock-face prefix-face
)
1604 (defun occur-accumulate-lines (count &optional keep-props pt
)
1608 (let ((forwardp (> count
0))
1609 result beg end moved
)
1610 (while (not (or (zerop count
)
1613 (and (bobp) (not moved
)))))
1614 (setq count
(+ count
(if forwardp -
1 1)))
1615 (setq beg
(line-beginning-position)
1616 end
(line-end-position))
1617 (push (occur-engine-line beg end keep-props
) result
)
1618 (setq moved
(= 0 (forward-line (if forwardp
1 -
1)))))
1619 (nreverse result
))))
1621 ;; Generate context display for occur.
1622 ;; OUT-LINE is the line where the match is.
1623 ;; NLINES and KEEP-PROPS are args to occur-engine.
1624 ;; CURR-LINE is line count of the current match,
1625 ;; PREV-LINE is line count of the previous match,
1626 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1627 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1628 ;; then concatenate them all together.
1629 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1630 curr-line prev-line prev-after-lines
1631 &optional prefix-face
)
1632 ;; Find after- and before-context lines of the current match.
1634 (nreverse (cdr (occur-accumulate-lines
1635 (- (1+ (abs nlines
))) keep-props begpt
))))
1637 (cdr (occur-accumulate-lines
1638 (1+ nlines
) keep-props endpt
)))
1641 ;; Combine after-lines of the previous match
1642 ;; with before-lines of the current match.
1644 (when prev-after-lines
1645 ;; Don't overlap prev after-lines with current before-lines.
1646 (if (>= (+ prev-line
(length prev-after-lines
))
1647 (- curr-line
(length before-lines
)))
1648 (setq prev-after-lines
1649 (butlast prev-after-lines
1650 (- (length prev-after-lines
)
1651 (- curr-line prev-line
(length before-lines
) 1))))
1652 ;; Separate non-overlapping context lines with a dashed line.
1653 (setq separator
"-------\n")))
1656 ;; Don't overlap current before-lines with previous match line.
1657 (if (<= (- curr-line
(length before-lines
))
1660 (nthcdr (- (length before-lines
)
1661 (- curr-line prev-line
1))
1663 ;; Separate non-overlapping before-context lines.
1664 (unless (> nlines
0)
1665 (setq separator
"-------\n"))))
1668 ;; Return a list where the first element is the output line.
1671 (if prev-after-lines
1672 (occur-engine-add-prefix prev-after-lines prefix-face
))
1674 (list (if prefix-face
1675 (propertize separator
'font-lock-face prefix-face
)
1677 (occur-engine-add-prefix before-lines prefix-face
)
1679 ;; And the second element is the list of context after-lines.
1680 (if (> nlines
0) after-lines
))))
1683 ;; It would be nice to use \\[...], but there is no reasonable way
1684 ;; to make that display both SPC and Y.
1685 (defconst query-replace-help
1686 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1687 RET or `q' to exit, Period to replace one match and exit,
1688 Comma to replace but not move point immediately,
1689 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1690 C-w to delete match and recursive edit,
1691 C-l to clear the screen, redisplay, and offer same replacement again,
1692 ! to replace all remaining matches in this buffer with no more questions,
1693 ^ to move point back to previous match,
1694 E to edit the replacement string.
1695 In multi-buffer replacements type `Y' to replace all remaining
1696 matches in all remaining buffers with no more questions,
1697 `N' to skip to the next buffer without replacing remaining matches
1698 in the current buffer."
1699 "Help message while in `query-replace'.")
1701 (defvar query-replace-map
1702 (let ((map (make-sparse-keymap)))
1703 (define-key map
" " 'act
)
1704 (define-key map
"\d" 'skip
)
1705 (define-key map
[delete] 'skip)
1706 (define-key map [backspace] 'skip)
1707 (define-key map "y" 'act)
1708 (define-key map "n" 'skip)
1709 (define-key map "Y" 'act)
1710 (define-key map "N" 'skip)
1711 (define-key map "e" 'edit-replacement)
1712 (define-key map "E" 'edit-replacement)
1713 (define-key map "," 'act-and-show)
1714 (define-key map "q" 'exit)
1715 (define-key map "\r" 'exit)
1716 (define-key map [return] 'exit)
1717 (define-key map "." 'act-and-exit)
1718 (define-key map "\C-r" 'edit)
1719 (define-key map "\C-w" 'delete-and-edit)
1720 (define-key map "\C-l" 'recenter)
1721 (define-key map "!" 'automatic)
1722 (define-key map "^" 'backup)
1723 (define-key map "\C-h" 'help)
1724 (define-key map [f1] 'help)
1725 (define-key map [help] 'help)
1726 (define-key map "?" 'help)
1727 (define-key map "\C-g" 'quit)
1728 (define-key map "\C-]" 'quit)
1729 (define-key map "\C-v" 'scroll-up)
1730 (define-key map "\M-v" 'scroll-down)
1731 (define-key map [next] 'scroll-up)
1732 (define-key map [prior] 'scroll-down)
1733 (define-key map [?\C-\M-v] 'scroll-other-window)
1734 (define-key map [M-next] 'scroll-other-window)
1735 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1736 (define-key map [M-prior] 'scroll-other-window-down)
1737 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1738 ;; should check for ESC specially.
1739 ;; (define-key map "\e" 'exit-prefix)
1740 (define-key map [escape] 'exit-prefix)
1742 "Keymap of responses to questions posed by commands like `query-replace'.
1743 The \"bindings\" in this map are not commands; they are answers.
1744 The valid answers include `act', `skip', `act-and-show',
1745 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1746 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1747 `edit', `edit-replacement', `delete-and-edit', `automatic',
1748 `backup', `quit', and `help'.
1750 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1752 (defvar multi-query-replace-map
1753 (let ((map (make-sparse-keymap)))
1754 (set-keymap-parent map query-replace-map)
1755 (define-key map "Y" 'automatic-all)
1756 (define-key map "N" 'exit-current)
1758 "Keymap that defines additional bindings for multi-buffer replacements.
1759 It extends its parent map `query-replace-map' with new bindings to
1760 operate on a set of buffers/files. The difference with its parent map
1761 is the additional answers `automatic-all' to replace all remaining
1762 matches in all remaining buffers with no more questions, and
1763 `exit-current' to skip remaining matches in the current buffer
1764 and to continue with the next buffer in the sequence.")
1766 (defun replace-match-string-symbols (n)
1767 "Process a list (and any sub-lists), expanding certain symbols.
1769 N (match-string N) (where N is a string of digits)
1770 #N (string-to-number (match-string N))
1772 #& (string-to-number (match-string 0))
1775 Note that these symbols must be preceded by a backslash in order to
1776 type them using Lisp syntax."
1780 (replace-match-string-symbols (car n))) ;Process sub-list
1782 (let ((name (symbol-name (car n))))
1784 ((string-match "^[0-9]+$" name)
1785 (setcar n (list 'match-string (string-to-number name))))
1786 ((string-match "^#[0-9]+$" name)
1787 (setcar n (list 'string-to-number
1789 (string-to-number (substring name 1))))))
1791 (setcar n '(match-string 0)))
1792 ((string= "#&" name)
1793 (setcar n '(string-to-number (match-string 0))))
1795 (setcar n 'replace-count))))))
1798 (defun replace-eval-replacement (expression count)
1799 (let* ((replace-count count)
1805 (error "Error evaluating replacement expression: %S" err)))))
1806 (if (stringp replacement)
1808 (prin1-to-string replacement t))))
1810 (defun replace-quote (replacement)
1811 "Quote a replacement string.
1812 This just doubles all backslashes in REPLACEMENT and
1813 returns the resulting string. If REPLACEMENT is not
1814 a string, it is first passed through `prin1-to-string'
1815 with the `noescape' argument set.
1817 `match-data' is preserved across the call."
1819 (replace-regexp-in-string "\\\\" "\\\\"
1820 (if (stringp replacement)
1822 (prin1-to-string replacement t))
1825 (defun replace-loop-through-replacements (data count)
1826 ;; DATA is a vector containing the following values:
1827 ;; 0 next-rotate-count
1829 ;; 2 next-replacement
1831 (if (= (aref data 0) count)
1833 (aset data 0 (+ count (aref data 1)))
1834 (let ((next (cdr (aref data 2))))
1835 (aset data 2 (if (consp next) next (aref data 3))))))
1836 (car (aref data 2)))
1838 (defun replace-match-data (integers reuse &optional new)
1839 "Like `match-data', but markers in REUSE get invalidated.
1840 If NEW is non-nil, it is set and returned instead of fresh data,
1841 but coerced to the correct value of INTEGERS."
1844 (set-match-data new)
1846 (eq (null integers) (markerp (car reuse)))
1848 (match-data integers reuse t)))
1850 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1851 "Make a replacement with `replace-match', editing `\\?'.
1852 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1853 check for `\\?' is made to save time. MATCH-DATA is used for the
1854 replacement. In case editing is done, it is changed to use markers.
1856 The return value is non-nil if there has been no `\\?' or NOEDIT was
1857 passed in. If LITERAL is set, no checking is done, anyway."
1858 (unless (or literal noedit)
1860 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1863 (read-string "Edit replacement string: "
1866 (replace-match "" t t newtext 3)
1867 (1+ (match-beginning 3)))
1870 nil match-data match-data))))
1872 (set-match-data match-data)
1873 (replace-match newtext fixedcase literal)
1876 (defvar replace-search-function nil
1877 "Function to use when searching for strings to replace.
1878 It is used by `query-replace' and `replace-string', and is called
1879 with three arguments, as if it were `search-forward'.")
1881 (defvar replace-re-search-function nil
1882 "Function to use when searching for regexps to replace.
1883 It is used by `query-replace-regexp', `replace-regexp',
1884 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1885 It is called with three arguments, as if it were
1886 `re-search-forward'.")
1888 (defun replace-search (search-string limit regexp-flag delimited-flag
1890 "Search for the next occurrence of SEARCH-STRING to replace."
1891 ;; Let-bind global isearch-* variables to values used
1892 ;; to search the next replacement. These let-bindings
1893 ;; should be effective both at the time of calling
1894 ;; `isearch-search-fun-default' and also at the
1895 ;; time of funcalling `search-function'.
1896 ;; These isearch-* bindings can't be placed higher
1897 ;; outside of this function because then another I-search
1898 ;; used after `recursive-edit' might override them.
1899 (let* ((isearch-regexp regexp-flag)
1900 (isearch-word delimited-flag)
1901 (isearch-lax-whitespace
1902 replace-lax-whitespace)
1903 (isearch-regexp-lax-whitespace
1904 replace-regexp-lax-whitespace)
1905 (isearch-case-fold-search case-fold-search)
1906 (isearch-adjusted nil)
1907 (isearch-nonincremental t) ; don't use lax word mode
1911 replace-re-search-function
1912 replace-search-function)
1913 (isearch-search-fun-default))))
1914 (funcall search-function search-string limit t)))
1916 (defvar replace-overlay nil)
1918 (defun replace-highlight (match-beg match-end range-beg range-end
1919 search-string regexp-flag delimited-flag
1921 (if query-replace-highlight
1923 (move-overlay replace-overlay match-beg match-end (current-buffer))
1924 (setq replace-overlay (make-overlay match-beg match-end))
1925 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
1926 (overlay-put replace-overlay 'face 'query-replace)))
1927 (if query-replace-lazy-highlight
1928 (let ((isearch-string search-string)
1929 (isearch-regexp regexp-flag)
1930 (isearch-word delimited-flag)
1931 (isearch-lax-whitespace
1932 replace-lax-whitespace)
1933 (isearch-regexp-lax-whitespace
1934 replace-regexp-lax-whitespace)
1935 (isearch-case-fold-search case-fold-search)
1937 (isearch-other-end match-beg)
1938 (isearch-error nil))
1939 (isearch-lazy-highlight-new-loop range-beg range-end))))
1941 (defun replace-dehighlight ()
1942 (when replace-overlay
1943 (delete-overlay replace-overlay))
1944 (when query-replace-lazy-highlight
1945 (lazy-highlight-cleanup lazy-highlight-cleanup)
1946 (setq isearch-lazy-highlight-last-string nil))
1947 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
1948 (isearch-clean-overlays))
1950 (defun perform-replace (from-string replacements
1951 query-flag regexp-flag delimited-flag
1952 &optional repeat-count map start end)
1953 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1954 Don't use this in your own program unless you want to query and set the mark
1955 just as `query-replace' does. Instead, write a simple loop like this:
1957 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1958 (replace-match \"foobar\" nil nil))
1960 which will run faster and probably do exactly what you want. Please
1961 see the documentation of `replace-match' to find out how to simulate
1964 This function returns nil if and only if there were no matches to
1965 make, or the user didn't cancel the call."
1966 (or map (setq map query-replace-map))
1967 (and query-flag minibuffer-auto-raise
1968 (raise-frame (window-frame (minibuffer-window))))
1969 (let* ((case-fold-search
1970 (if (and case-fold-search search-upper-case)
1971 (isearch-no-upper-case-p from-string regexp-flag)
1973 (nocasify (not (and case-replace case-fold-search)))
1974 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1975 (search-string from-string)
1976 (real-match-data nil) ; The match data for the current match.
1977 (next-replacement nil)
1978 ;; This is non-nil if we know there is nothing for the user
1979 ;; to edit in the replacement.
1984 (skip-read-only-count 0)
1985 (skip-filtered-count 0)
1986 (skip-invisible-count 0)
1987 (nonempty-match nil)
1989 (recenter-last-op nil) ; Start cycling order with initial position.
1991 ;; If non-nil, it is marker saying where in the buffer to stop.
1994 ;; Data for the next match. If a cons, it has the same format as
1995 ;; (match-data); otherwise it is t if a match is possible at point.
2001 (substitute-command-keys
2002 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2003 minibuffer-prompt-properties))))
2005 ;; If region is active, in Transient Mark mode, operate on region.
2007 (setq limit (copy-marker (max start end)))
2008 (goto-char (min start end))
2011 ;; If last typed key in previous call of multi-buffer perform-replace
2012 ;; was `automatic-all', don't ask more questions in next files
2013 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2014 (setq query-flag nil multi-buffer t))
2016 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
2017 ;; containing a function and its first argument. The function is
2018 ;; called to generate each replacement like this:
2019 ;; (funcall (car replacements) (cdr replacements) replace-count)
2020 ;; It must return a string.
2022 ((stringp replacements)
2023 (setq next-replacement replacements
2025 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2026 (or repeat-count (setq repeat-count 1))
2027 (setq replacements (cons 'replace-loop-through-replacements
2028 (vector repeat-count repeat-count
2029 replacements replacements)))))
2031 (when query-replace-lazy-highlight
2032 (setq isearch-lazy-highlight-last-string nil))
2037 ;; Loop finding occurrences that perhaps should be replaced.
2038 (while (and keep-going
2039 (not (or (eobp) (and limit (>= (point) limit))))
2040 ;; Use the next match if it is already known;
2041 ;; otherwise, search for a match after moving forward
2042 ;; one char if progress is required.
2043 (setq real-match-data
2044 (cond ((consp match-again)
2045 (goto-char (nth 1 match-again))
2047 t real-match-data match-again))
2048 ;; MATCH-AGAIN non-nil means accept an
2052 (replace-search search-string limit
2053 regexp-flag delimited-flag
2055 ;; For speed, use only integers and
2056 ;; reuse the list used last time.
2057 (replace-match-data t real-match-data)))
2058 ((and (< (1+ (point)) (point-max))
2060 (< (1+ (point)) limit)))
2061 ;; If not accepting adjacent matches,
2062 ;; move one char to the right before
2063 ;; searching again. Undo the motion
2064 ;; if the search fails.
2065 (let ((opoint (point)))
2067 (if (replace-search search-string limit
2068 regexp-flag delimited-flag
2075 ;; Record whether the match is nonempty, to avoid an infinite loop
2076 ;; repeatedly matching the same empty string.
2077 (setq nonempty-match
2078 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2080 ;; If the match is empty, record that the next one can't be
2083 ;; Otherwise, if matching a regular expression, do the next
2084 ;; match now, since the replacement for this match may
2085 ;; affect whether the next match is adjacent to this one.
2086 ;; If that match is empty, don't use it.
2089 (or (not regexp-flag)
2090 (and (looking-at search-string)
2091 (let ((match (match-data)))
2092 (and (/= (nth 0 match) (nth 1 match))
2096 ;; Optionally ignore matches that have a read-only property.
2097 ((not (or (not query-replace-skip-read-only)
2098 (not (text-property-not-all
2099 (nth 0 real-match-data) (nth 1 real-match-data)
2101 (setq skip-read-only-count (1+ skip-read-only-count)))
2102 ;; Optionally filter out matches.
2103 ((not (funcall isearch-filter-predicate
2104 (nth 0 real-match-data) (nth 1 real-match-data)))
2105 (setq skip-filtered-count (1+ skip-filtered-count)))
2106 ;; Optionally ignore invisible matches.
2107 ((not (or (eq search-invisible t)
2108 ;; Don't open overlays for automatic replacements.
2109 (and (not query-flag) search-invisible)
2110 ;; Open hidden overlays for interactive replacements.
2111 (not (isearch-range-invisible
2112 (nth 0 real-match-data) (nth 1 real-match-data)))))
2113 (setq skip-invisible-count (1+ skip-invisible-count)))
2115 ;; Calculate the replacement string, if necessary.
2117 (set-match-data real-match-data)
2118 (setq next-replacement
2119 (funcall (car replacements) (cdr replacements)
2121 (if (not query-flag)
2123 (unless (or literal noedit)
2125 (nth 0 real-match-data) (nth 1 real-match-data)
2126 start end search-string
2127 regexp-flag delimited-flag case-fold-search))
2129 (replace-match-maybe-edit
2130 next-replacement nocasify literal
2131 noedit real-match-data)
2132 replace-count (1+ replace-count)))
2134 (let (done replaced key def)
2135 ;; Loop reading commands until one of them sets done,
2136 ;; which means it has finished handling this
2137 ;; occurrence. Any command that sets `done' should
2138 ;; leave behind proper match data for the stack.
2139 ;; Commands not setting `done' need to adjust
2140 ;; `real-match-data'.
2142 (set-match-data real-match-data)
2144 (match-beginning 0) (match-end 0)
2145 start end search-string
2146 regexp-flag delimited-flag case-fold-search)
2147 ;; Bind message-log-max so we don't fill up the message log
2148 ;; with a bunch of identical messages.
2149 (let ((message-log-max nil)
2150 (replacement-presentation
2151 (if query-replace-show-replacement
2153 (set-match-data real-match-data)
2154 (match-substitute-replacement next-replacement
2158 (query-replace-descr from-string)
2159 (query-replace-descr replacement-presentation)))
2160 (setq key (read-event))
2161 ;; Necessary in case something happens during read-event
2162 ;; that clobbers the match data.
2163 (set-match-data real-match-data)
2164 (setq key (vector key))
2165 (setq def (lookup-key map key))
2166 ;; Restore the match data while we process the command.
2167 (cond ((eq def 'help)
2168 (with-output-to-temp-buffer "*Help*"
2170 (concat "Query replacing "
2172 (or (and (symbolp delimited-flag)
2173 (get delimited-flag 'isearch-message-prefix))
2175 (if regexp-flag "regexp " "")
2176 from-string " with "
2177 next-replacement ".\n\n"
2178 (substitute-command-keys
2179 query-replace-help)))
2180 (with-current-buffer standard-output
2183 (setq keep-going nil)
2185 ((eq def 'exit-current)
2186 (setq multi-buffer t keep-going nil done t))
2189 (let ((elt (pop stack)))
2190 (goto-char (nth 0 elt))
2191 (setq replaced (nth 1 elt)
2196 (message "No previous match")
2197 (ding 'no-terminate)
2202 (replace-match-maybe-edit
2203 next-replacement nocasify literal
2204 noedit real-match-data)
2205 replace-count (1+ replace-count)))
2206 (setq done t replaced t))
2207 ((eq def 'act-and-exit)
2210 (replace-match-maybe-edit
2211 next-replacement nocasify literal
2212 noedit real-match-data)
2213 replace-count (1+ replace-count)))
2214 (setq keep-going nil)
2215 (setq done t replaced t))
2216 ((eq def 'act-and-show)
2219 (replace-match-maybe-edit
2220 next-replacement nocasify literal
2221 noedit real-match-data)
2222 replace-count (1+ replace-count)
2223 real-match-data (replace-match-data
2226 ((or (eq def 'automatic) (eq def 'automatic-all))
2229 (replace-match-maybe-edit
2230 next-replacement nocasify literal
2231 noedit real-match-data)
2232 replace-count (1+ replace-count)))
2233 (setq done t query-flag nil replaced t)
2234 (if (eq def 'automatic-all) (setq multi-buffer t)))
2238 ;; `this-command' has the value `query-replace',
2239 ;; so we need to bind it to `recenter-top-bottom'
2240 ;; to allow it to detect a sequence of `C-l'.
2241 (let ((this-command 'recenter-top-bottom)
2242 (last-command 'recenter-top-bottom))
2243 (recenter-top-bottom)))
2245 (let ((opos (point-marker)))
2246 (setq real-match-data (replace-match-data
2249 (goto-char (match-beginning 0))
2251 (save-window-excursion
2254 (set-marker opos nil))
2255 ;; Before we make the replacement,
2256 ;; decide whether the search string
2257 ;; can match again just after this match.
2258 (if (and regexp-flag nonempty-match)
2259 (setq match-again (and (looking-at search-string)
2261 ;; Edit replacement.
2262 ((eq def 'edit-replacement)
2263 (setq real-match-data (replace-match-data
2267 (read-string "Edit replacement string: "
2271 (set-match-data real-match-data)
2273 (replace-match-maybe-edit
2274 next-replacement nocasify literal noedit
2279 ((eq def 'delete-and-edit)
2280 (replace-match "" t t)
2281 (setq real-match-data (replace-match-data
2282 nil real-match-data))
2283 (replace-dehighlight)
2284 (save-excursion (recursive-edit))
2286 ;; Note: we do not need to treat `exit-prefix'
2287 ;; specially here, since we reread
2288 ;; any unrecognized character.
2290 (setq this-command 'mode-exited)
2291 (setq keep-going nil)
2292 (setq unread-command-events
2293 (append (listify-key-sequence key)
2294 unread-command-events))
2296 (when query-replace-lazy-highlight
2297 ;; Force lazy rehighlighting only after replacements.
2298 (if (not (memq def '(skip backup)))
2299 (setq isearch-lazy-highlight-last-string nil)))
2300 (unless (eq def 'recenter)
2301 ;; Reset recenter cycling order to initial position.
2302 (setq recenter-last-op nil)))
2303 ;; Record previous position for ^ when we move on.
2304 ;; Change markers to numbers in the match data
2305 ;; since lots of markers slow down editing.
2306 (push (list (point) replaced
2307 ;;; If the replacement has already happened, all we need is the
2308 ;;; current match start and end. We could get this with a trivial
2310 ;;; (save-excursion (goto-char (match-beginning 0))
2311 ;;; (search-forward (match-string 0))
2313 ;;; if we really wanted to avoid manually constructing match data.
2314 ;;; Adding current-buffer is necessary so that match-data calls can
2315 ;;; return markers which are appropriate for editing.
2324 (replace-dehighlight))
2325 (or unread-command-events
2326 (message "Replaced %d occurrence%s%s"
2328 (if (= replace-count 1) "" "s")
2329 (if (> (+ skip-read-only-count
2331 skip-invisible-count) 0)
2332 (format " (skipped %s)"
2336 (if (> skip-read-only-count 0)
2337 (format "%s read-only"
2338 skip-read-only-count))
2339 (if (> skip-invisible-count 0)
2340 (format "%s invisible"
2341 skip-invisible-count))
2342 (if (> skip-filtered-count 0)
2343 (format "%s filtered out"
2344 skip-filtered-count))))
2347 (or (and keep-going stack) multi-buffer)))
2349 ;;; replace.el ends here