; Improve commentary of Info-default-directory-list
[emacs.git] / lisp / replace.el
bloba5024943e64714f822de37133784420d52441382
1 ;;; replace.el --- replace commands for Emacs -*- lexical-binding: t -*-
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2017 Free
4 ;; Software Foundation, Inc.
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Package: emacs
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/>.
24 ;;; Commentary:
26 ;; This package supplies the string and regular-expression replace functions
27 ;; documented in the Emacs user's manual.
29 ;;; Code:
31 (eval-when-compile (require 'cl-lib))
33 (defcustom case-replace t
34 "Non-nil means `query-replace' should preserve case in replacements."
35 :type 'boolean
36 :group 'matching)
38 (defcustom replace-char-fold nil
39 "Non-nil means replacement commands should do character folding in matches.
40 This means, for instance, that \\=' will match a large variety of
41 unicode quotes.
42 This variable affects `query-replace' and `replace-string', but not
43 `replace-regexp'."
44 :type 'boolean
45 :group 'matching
46 :version "25.1")
48 (defcustom replace-lax-whitespace nil
49 "Non-nil means `query-replace' matches a sequence of whitespace chars.
50 When you enter a space or spaces in the strings to be replaced,
51 it will match any sequence matched by the regexp `search-whitespace-regexp'."
52 :type 'boolean
53 :group 'matching
54 :version "24.3")
56 (defcustom replace-regexp-lax-whitespace nil
57 "Non-nil means `query-replace-regexp' matches a sequence of whitespace chars.
58 When you enter a space or spaces in the regexps to be replaced,
59 it will match any sequence matched by the regexp `search-whitespace-regexp'."
60 :type 'boolean
61 :group 'matching
62 :version "24.3")
64 (defvar query-replace-history nil
65 "Default history list for query-replace commands.
66 See `query-replace-from-history-variable' and
67 `query-replace-to-history-variable'.")
69 (defvar query-replace-defaults nil
70 "Default values of FROM-STRING and TO-STRING for `query-replace'.
71 This is a list of cons cells (FROM-STRING . TO-STRING), or nil
72 if there are no default values.")
74 (defvar query-replace-interactive nil
75 "Non-nil means `query-replace' uses the last search string.
76 That becomes the \"string to replace\".")
77 (make-obsolete-variable 'query-replace-interactive
78 "use `M-n' to pull the last incremental search string
79 to the minibuffer that reads the string to replace, or invoke replacements
80 from Isearch by using a key sequence like `C-s C-s M-%'." "24.3")
82 (defcustom query-replace-from-to-separator " → "
83 "String that separates FROM and TO in the history of replacement pairs.
84 When nil, the pair will not be added to the history (same behavior
85 as in emacs 24.5)."
86 :group 'matching
87 :type '(choice
88 (const :tag "Disabled" nil)
89 string)
90 :version "25.1")
92 (defcustom query-replace-from-history-variable 'query-replace-history
93 "History list to use for the FROM argument of `query-replace' commands.
94 The value of this variable should be a symbol; that symbol
95 is used as a variable to hold a history list for the strings
96 or patterns to be replaced."
97 :group 'matching
98 :type 'symbol
99 :version "20.3")
101 (defcustom query-replace-to-history-variable 'query-replace-history
102 "History list to use for the TO argument of `query-replace' commands.
103 The value of this variable should be a symbol; that symbol
104 is used as a variable to hold a history list for replacement
105 strings or patterns."
106 :group 'matching
107 :type 'symbol
108 :version "20.3")
110 (defcustom query-replace-skip-read-only nil
111 "Non-nil means `query-replace' and friends ignore read-only matches."
112 :type 'boolean
113 :group 'matching
114 :version "22.1")
116 (defcustom query-replace-show-replacement t
117 "Non-nil means show substituted replacement text in the minibuffer.
118 This variable affects only `query-replace-regexp'."
119 :type 'boolean
120 :group 'matching
121 :version "23.1")
123 (defcustom query-replace-highlight t
124 "Non-nil means to highlight matches during query replacement."
125 :type 'boolean
126 :group 'matching)
128 (defcustom query-replace-lazy-highlight t
129 "Controls the lazy-highlighting during query replacements.
130 When non-nil, all text in the buffer matching the current match
131 is highlighted lazily using isearch lazy highlighting (see
132 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
133 :type 'boolean
134 :group 'lazy-highlight
135 :group 'matching
136 :version "22.1")
138 (defface query-replace
139 '((t (:inherit isearch)))
140 "Face for highlighting query replacement matches."
141 :group 'matching
142 :version "22.1")
144 (defvar replace-count 0
145 "Number of replacements done so far.
146 See `replace-regexp' and `query-replace-regexp-eval'.")
148 (defun query-replace-descr (string)
149 (mapconcat 'isearch-text-char-description string ""))
151 (defun query-replace--split-string (string)
152 "Split string STRING at a substring with property `separator'."
153 (let* ((length (length string))
154 (split-pos (text-property-any 0 length 'separator t string)))
155 (if (not split-pos)
156 (substring-no-properties string)
157 (cons (substring-no-properties string 0 split-pos)
158 (substring-no-properties
159 string (or (text-property-not-all
160 (1+ split-pos) length 'separator t string)
161 length)
162 length)))))
164 (defun query-replace-read-from (prompt regexp-flag)
165 "Query and return the `from' argument of a query-replace operation.
166 The return value can also be a pair (FROM . TO) indicating that the user
167 wants to replace FROM with TO."
168 (if query-replace-interactive
169 (car (if regexp-flag regexp-search-ring search-ring))
170 (let* ((history-add-new-input nil)
171 (separator-string
172 (when query-replace-from-to-separator
173 ;; Check if the first non-whitespace char is displayable
174 (if (char-displayable-p
175 (string-to-char (replace-regexp-in-string
176 " " "" query-replace-from-to-separator)))
177 query-replace-from-to-separator
178 " -> ")))
179 (separator
180 (when separator-string
181 (propertize separator-string
182 'display separator-string
183 'face 'minibuffer-prompt
184 'separator t)))
185 (minibuffer-history
186 (append
187 (when separator
188 (mapcar (lambda (from-to)
189 (concat (query-replace-descr (car from-to))
190 separator
191 (query-replace-descr (cdr from-to))))
192 query-replace-defaults))
193 (symbol-value query-replace-from-history-variable)))
194 (minibuffer-allow-text-properties t) ; separator uses text-properties
195 (prompt
196 (cond ((and query-replace-defaults separator)
197 (format "%s (default %s): " prompt (car minibuffer-history)))
198 (query-replace-defaults
199 (format "%s (default %s -> %s): " prompt
200 (query-replace-descr (caar query-replace-defaults))
201 (query-replace-descr (cdar query-replace-defaults))))
202 (t (format "%s: " prompt))))
203 (from
204 ;; The save-excursion here is in case the user marks and copies
205 ;; a region in order to specify the minibuffer input.
206 ;; That should not clobber the region for the query-replace itself.
207 (save-excursion
208 (minibuffer-with-setup-hook
209 (lambda ()
210 (setq-local text-property-default-nonsticky
211 (append '((separator . t) (face . t))
212 text-property-default-nonsticky)))
213 (if regexp-flag
214 (read-regexp prompt nil 'minibuffer-history)
215 (read-from-minibuffer
216 prompt nil nil nil nil (car search-ring) t)))))
217 (to))
218 (if (and (zerop (length from)) query-replace-defaults)
219 (cons (caar query-replace-defaults)
220 (query-replace-compile-replacement
221 (cdar query-replace-defaults) regexp-flag))
222 (setq from (query-replace--split-string from))
223 (when (consp from) (setq to (cdr from) from (car from)))
224 (add-to-history query-replace-from-history-variable from nil t)
225 ;; Warn if user types \n or \t, but don't reject the input.
226 (and regexp-flag
227 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
228 (let ((match (match-string 3 from)))
229 (cond
230 ((string= match "\\n")
231 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
232 ((string= match "\\t")
233 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
234 (sit-for 2)))
235 (if (not to)
236 from
237 (add-to-history query-replace-to-history-variable to nil t)
238 (add-to-history 'query-replace-defaults (cons from to) nil t)
239 (cons from (query-replace-compile-replacement to regexp-flag)))))))
241 (defun query-replace-compile-replacement (to regexp-flag)
242 "Maybe convert a regexp replacement TO to Lisp.
243 Returns a list suitable for `perform-replace' if necessary,
244 the original string if not."
245 (if (and regexp-flag
246 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
247 (let (pos list char)
248 (while
249 (progn
250 (setq pos (match-end 0))
251 (push (substring to 0 (- pos 2)) list)
252 (setq char (aref to (1- pos))
253 to (substring to pos))
254 (cond ((eq char ?\#)
255 (push '(number-to-string replace-count) list))
256 ((eq char ?\,)
257 (setq pos (read-from-string to))
258 (push `(replace-quote ,(car pos)) list)
259 (let ((end
260 ;; Swallow a space after a symbol
261 ;; if there is a space.
262 (if (and (or (symbolp (car pos))
263 ;; Swallow a space after 'foo
264 ;; but not after (quote foo).
265 (and (eq (car-safe (car pos)) 'quote)
266 (not (= ?\( (aref to 0)))))
267 (eq (string-match " " to (cdr pos))
268 (cdr pos)))
269 (1+ (cdr pos))
270 (cdr pos))))
271 (setq to (substring to end)))))
272 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
273 (setq to (nreverse (delete "" (cons to list))))
274 (replace-match-string-symbols to)
275 (cons 'replace-eval-replacement
276 (if (cdr to)
277 (cons 'concat to)
278 (car to))))
279 to))
282 (defun query-replace-read-to (from prompt regexp-flag)
283 "Query and return the `to' argument of a query-replace operation."
284 (query-replace-compile-replacement
285 (save-excursion
286 (let* ((history-add-new-input nil)
287 (to (read-from-minibuffer
288 (format "%s %s with: " prompt (query-replace-descr from))
289 nil nil nil
290 query-replace-to-history-variable from t)))
291 (add-to-history query-replace-to-history-variable to nil t)
292 (add-to-history 'query-replace-defaults (cons from to) nil t)
293 to))
294 regexp-flag))
296 (defun query-replace-read-args (prompt regexp-flag &optional noerror)
297 (unless noerror
298 (barf-if-buffer-read-only))
299 (let* ((from (query-replace-read-from prompt regexp-flag))
300 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
301 (query-replace-read-to from prompt regexp-flag))))
302 (list from to
303 (and current-prefix-arg (not (eq current-prefix-arg '-)))
304 (and current-prefix-arg (eq current-prefix-arg '-)))))
306 (defun query-replace (from-string to-string &optional delimited start end backward region-noncontiguous-p)
307 "Replace some occurrences of FROM-STRING with TO-STRING.
308 As each match is found, the user must type a character saying
309 what to do with it. For directions, type \\[help-command] at that time.
311 In Transient Mark mode, if the mark is active, operate on the contents
312 of the region. Otherwise, operate from point to the end of the buffer's
313 accessible portion.
315 In interactive use, the prefix arg (non-nil DELIMITED in
316 non-interactive use), means replace only matches surrounded by
317 word boundaries. A negative prefix arg means replace backward.
319 Use \\<minibuffer-local-map>\\[next-history-element] \
320 to pull the last incremental search string to the minibuffer
321 that reads FROM-STRING, or invoke replacements from
322 incremental search with a key sequence like `C-s C-s M-%'
323 to use its current search string as the string to replace.
325 Matching is independent of case if `case-fold-search' is non-nil and
326 FROM-STRING has no uppercase letters. Replacement transfers the case
327 pattern of the old text to the new text, if `case-replace' and
328 `case-fold-search' are non-nil and FROM-STRING has no uppercase
329 letters. (Transferring the case pattern means that if the old text
330 matched is all caps, or capitalized, then its replacement is upcased
331 or capitalized.)
333 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
334 ignore hidden matches if `search-invisible' is nil, and ignore more
335 matches using `isearch-filter-predicate'.
337 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
338 to be replaced will match a sequence of whitespace chars defined by the
339 regexp in `search-whitespace-regexp'.
341 If `replace-char-fold' is non-nil, matching uses character folding,
342 i.e. it ignores diacritics and other differences between equivalent
343 character strings.
345 Fourth and fifth arg START and END specify the region to operate on.
347 To customize possible responses, change the bindings in `query-replace-map'."
348 (interactive
349 (let ((common
350 (query-replace-read-args
351 (concat "Query replace"
352 (if current-prefix-arg
353 (if (eq current-prefix-arg '-) " backward" " word")
355 (if (use-region-p) " in region" ""))
356 nil)))
357 (list (nth 0 common) (nth 1 common) (nth 2 common)
358 ;; These are done separately here
359 ;; so that command-history will record these expressions
360 ;; rather than the values they had this time.
361 (if (use-region-p) (region-beginning))
362 (if (use-region-p) (region-end))
363 (nth 3 common)
364 (if (use-region-p) (region-noncontiguous-p)))))
365 (perform-replace from-string to-string t nil delimited nil nil start end backward region-noncontiguous-p))
367 (define-key esc-map "%" 'query-replace)
369 (defun query-replace-regexp (regexp to-string &optional delimited start end backward region-noncontiguous-p)
370 "Replace some things after point matching REGEXP with TO-STRING.
371 As each match is found, the user must type a character saying
372 what to do with it. For directions, type \\[help-command] at that time.
374 In Transient Mark mode, if the mark is active, operate on the contents
375 of the region. Otherwise, operate from point to the end of the buffer's
376 accessible portion.
378 Use \\<minibuffer-local-map>\\[next-history-element] \
379 to pull the last incremental search regexp to the minibuffer
380 that reads REGEXP, or invoke replacements from
381 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
382 to use its current search regexp as the regexp to replace.
384 Matching is independent of case if `case-fold-search' is non-nil and
385 REGEXP has no uppercase letters. Replacement transfers the case
386 pattern of the old text to the new text, if `case-replace' and
387 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
388 \(Transferring the case pattern means that if the old text matched is
389 all caps, or capitalized, then its replacement is upcased or
390 capitalized.)
392 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
393 ignore hidden matches if `search-invisible' is nil, and ignore more
394 matches using `isearch-filter-predicate'.
396 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
397 to be replaced will match a sequence of whitespace chars defined by the
398 regexp in `search-whitespace-regexp'.
400 This function is not affected by `replace-char-fold'.
402 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
403 only matches surrounded by word boundaries. A negative prefix arg means
404 replace backward.
406 Fourth and fifth arg START and END specify the region to operate on.
408 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
409 and `\\=\\N' (where N is a digit) stands for whatever matched
410 the Nth `\\(...\\)' (1-based) in REGEXP. The `\\(...\\)' groups are
411 counted from 1.
412 `\\?' lets you edit the replacement text in the minibuffer
413 at the given position for each replacement.
415 In interactive calls, the replacement text can contain `\\,'
416 followed by a Lisp expression. Each
417 replacement evaluates that expression to compute the replacement
418 string. Inside of that expression, `\\&' is a string denoting the
419 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
420 for the whole or a partial match converted to a number with
421 `string-to-number', and `\\#' itself for the number of replacements
422 done so far (starting with zero).
424 If the replacement expression is a symbol, write a space after it
425 to terminate it. One space there, if any, will be discarded.
427 When using those Lisp features interactively in the replacement
428 text, TO-STRING is actually made a list instead of a string.
429 Use \\[repeat-complex-command] after this command for details."
430 (interactive
431 (let ((common
432 (query-replace-read-args
433 (concat "Query replace"
434 (if current-prefix-arg
435 (if (eq current-prefix-arg '-) " backward" " word")
437 " regexp"
438 (if (use-region-p) " in region" ""))
439 t)))
440 (list (nth 0 common) (nth 1 common) (nth 2 common)
441 ;; These are done separately here
442 ;; so that command-history will record these expressions
443 ;; rather than the values they had this time.
444 (if (use-region-p) (region-beginning))
445 (if (use-region-p) (region-end))
446 (nth 3 common)
447 (if (use-region-p) (region-noncontiguous-p)))))
448 (perform-replace regexp to-string t t delimited nil nil start end backward region-noncontiguous-p))
450 (define-key esc-map [?\C-%] 'query-replace-regexp)
452 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
453 "Replace some things after point matching REGEXP with the result of TO-EXPR.
455 Interactive use of this function is deprecated in favor of the
456 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
457 using `search-forward-regexp' and `replace-match' is preferred.
459 As each match is found, the user must type a character saying
460 what to do with it. For directions, type \\[help-command] at that time.
462 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
463 reference `replace-count' to get the number of replacements already made.
464 If the result of TO-EXPR is not a string, it is converted to one using
465 `prin1-to-string' with the NOESCAPE argument (which see).
467 For convenience, when entering TO-EXPR interactively, you can use `\\&'
468 to stand for whatever matched the whole of REGEXP, and `\\N' (where
469 N is a digit) to stand for whatever matched the Nth `\\(...\\)' (1-based)
470 in REGEXP.
472 Use `\\#&' or `\\#N' if you want a number instead of a string.
473 In interactive use, `\\#' in itself stands for `replace-count'.
475 In Transient Mark mode, if the mark is active, operate on the contents
476 of the region. Otherwise, operate from point to the end of the buffer's
477 accessible portion.
479 Use \\<minibuffer-local-map>\\[next-history-element] \
480 to pull the last incremental search regexp to the minibuffer
481 that reads REGEXP.
483 Preserves case in each replacement if `case-replace' and `case-fold-search'
484 are non-nil and REGEXP has no uppercase letters.
486 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
487 ignore hidden matches if `search-invisible' is nil, and ignore more
488 matches using `isearch-filter-predicate'.
490 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
491 to be replaced will match a sequence of whitespace chars defined by the
492 regexp in `search-whitespace-regexp'.
494 This function is not affected by `replace-char-fold'.
496 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
497 only matches that are surrounded by word boundaries.
498 Fourth and fifth arg START and END specify the region to operate on."
499 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
500 for interactive calls, and `search-forward-regexp'/`replace-match'
501 for Lisp calls." "22.1"))
502 (interactive
503 (progn
504 (barf-if-buffer-read-only)
505 (let* ((from
506 ;; Let-bind the history var to disable the "foo -> bar"
507 ;; default. Maybe we shouldn't disable this default, but
508 ;; for now I'll leave it off. --Stef
509 (let ((query-replace-defaults nil))
510 (query-replace-read-from "Query replace regexp" t)))
511 (to (list (read-from-minibuffer
512 (format "Query replace regexp %s with eval: "
513 (query-replace-descr from))
514 nil nil t query-replace-to-history-variable from t))))
515 ;; We make TO a list because replace-match-string-symbols requires one,
516 ;; and the user might enter a single token.
517 (replace-match-string-symbols to)
518 (list from (car to) current-prefix-arg
519 (if (use-region-p) (region-beginning))
520 (if (use-region-p) (region-end))))))
521 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
522 t 'literal delimited nil nil start end))
524 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
525 "Replace some matches for REGEXP with various strings, in rotation.
526 The second argument TO-STRINGS contains the replacement strings, separated
527 by spaces. This command works like `query-replace-regexp' except that
528 each successive replacement uses the next successive replacement string,
529 wrapping around from the last such string to the first.
531 In Transient Mark mode, if the mark is active, operate on the contents
532 of the region. Otherwise, operate from point to the end of the buffer's
533 accessible portion.
535 Non-interactively, TO-STRINGS may be a list of replacement strings.
537 Interactively, reads the regexp using `read-regexp'.
538 Use \\<minibuffer-local-map>\\[next-history-element] \
539 to pull the last incremental search regexp to the minibuffer
540 that reads REGEXP.
542 A prefix argument N says to use each replacement string N times
543 before rotating to the next.
544 Fourth and fifth arg START and END specify the region to operate on."
545 (interactive
546 (let* ((from (read-regexp "Map query replace (regexp): " nil
547 query-replace-from-history-variable))
548 (to (read-from-minibuffer
549 (format "Query replace %s with (space-separated strings): "
550 (query-replace-descr from))
551 nil nil nil
552 query-replace-to-history-variable from t)))
553 (list from to
554 (and current-prefix-arg
555 (prefix-numeric-value current-prefix-arg))
556 (if (use-region-p) (region-beginning))
557 (if (use-region-p) (region-end)))))
558 (let (replacements)
559 (if (listp to-strings)
560 (setq replacements to-strings)
561 (while (/= (length to-strings) 0)
562 (if (string-match " " to-strings)
563 (setq replacements
564 (append replacements
565 (list (substring to-strings 0
566 (string-match " " to-strings))))
567 to-strings (substring to-strings
568 (1+ (string-match " " to-strings))))
569 (setq replacements (append replacements (list to-strings))
570 to-strings ""))))
571 (perform-replace regexp replacements t t nil n nil start end)))
573 (defun replace-string (from-string to-string &optional delimited start end backward)
574 "Replace occurrences of FROM-STRING with TO-STRING.
575 Preserve case in each match if `case-replace' and `case-fold-search'
576 are non-nil and FROM-STRING has no uppercase letters.
577 \(Preserving case means that if the string matched is all caps, or capitalized,
578 then its replacement is upcased or capitalized.)
580 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
581 ignore hidden matches if `search-invisible' is nil, and ignore more
582 matches using `isearch-filter-predicate'.
584 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
585 to be replaced will match a sequence of whitespace chars defined by the
586 regexp in `search-whitespace-regexp'.
588 If `replace-char-fold' is non-nil, matching uses character folding,
589 i.e. it ignores diacritics and other differences between equivalent
590 character strings.
592 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
593 only matches surrounded by word boundaries. A negative prefix arg means
594 replace backward.
596 Operates on the region between START and END (if both are nil, from point
597 to the end of the buffer). Interactively, if Transient Mark mode is
598 enabled and the mark is active, operates on the contents of the region;
599 otherwise from point to the end of the buffer's accessible portion.
601 Use \\<minibuffer-local-map>\\[next-history-element] \
602 to pull the last incremental search string to the minibuffer
603 that reads FROM-STRING.
605 This function is usually the wrong thing to use in a Lisp program.
606 What you probably want is a loop like this:
607 (while (search-forward FROM-STRING nil t)
608 (replace-match TO-STRING nil t))
609 which will run faster and will not set the mark or print anything.
610 \(You may need a more complex loop if FROM-STRING can match the null string
611 and TO-STRING is also null.)"
612 (declare (interactive-only
613 "use `search-forward' and `replace-match' instead."))
614 (interactive
615 (let ((common
616 (query-replace-read-args
617 (concat "Replace"
618 (if current-prefix-arg
619 (if (eq current-prefix-arg '-) " backward" " word")
621 " string"
622 (if (use-region-p) " in region" ""))
623 nil)))
624 (list (nth 0 common) (nth 1 common) (nth 2 common)
625 (if (use-region-p) (region-beginning))
626 (if (use-region-p) (region-end))
627 (nth 3 common))))
628 (perform-replace from-string to-string nil nil delimited nil nil start end backward))
630 (defun replace-regexp (regexp to-string &optional delimited start end backward)
631 "Replace things after point matching REGEXP with TO-STRING.
632 Preserve case in each match if `case-replace' and `case-fold-search'
633 are non-nil and REGEXP has no uppercase letters.
635 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
636 ignore hidden matches if `search-invisible' is nil, and ignore more
637 matches using `isearch-filter-predicate'.
639 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
640 to be replaced will match a sequence of whitespace chars defined by the
641 regexp in `search-whitespace-regexp'.
643 This function is not affected by `replace-char-fold'
645 In Transient Mark mode, if the mark is active, operate on the contents
646 of the region. Otherwise, operate from point to the end of the buffer's
647 accessible portion.
649 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
650 only matches surrounded by word boundaries. A negative prefix arg means
651 replace backward.
653 Fourth and fifth arg START and END specify the region to operate on.
655 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
656 and `\\=\\N' (where N is a digit) stands for whatever matched
657 the Nth `\\(...\\)' (1-based) in REGEXP.
658 `\\?' lets you edit the replacement text in the minibuffer
659 at the given position for each replacement.
661 In interactive calls, the replacement text may contain `\\,'
662 followed by a Lisp expression used as part of the replacement
663 text. Inside of that expression, `\\&' is a string denoting the
664 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
665 numeric values from `string-to-number', and `\\#' itself for
666 `replace-count', the number of replacements occurred so far, starting
667 from zero.
669 If your Lisp expression is an identifier and the next letter in
670 the replacement string would be interpreted as part of it, you
671 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
672 for this particular case you may also enter `\\#' in the
673 replacement text directly.
675 When using those Lisp features interactively in the replacement
676 text, TO-STRING is actually made a list instead of a string.
677 Use \\[repeat-complex-command] after this command for details.
679 Use \\<minibuffer-local-map>\\[next-history-element] \
680 to pull the last incremental search regexp to the minibuffer
681 that reads REGEXP.
683 This function is usually the wrong thing to use in a Lisp program.
684 What you probably want is a loop like this:
685 (while (re-search-forward REGEXP nil t)
686 (replace-match TO-STRING nil nil))
687 which will run faster and will not set the mark or print anything."
688 (declare (interactive-only
689 "use `re-search-forward' and `replace-match' instead."))
690 (interactive
691 (let ((common
692 (query-replace-read-args
693 (concat "Replace"
694 (if current-prefix-arg
695 (if (eq current-prefix-arg '-) " backward" " word")
697 " regexp"
698 (if (use-region-p) " in region" ""))
699 t)))
700 (list (nth 0 common) (nth 1 common) (nth 2 common)
701 (if (use-region-p) (region-beginning))
702 (if (use-region-p) (region-end))
703 (nth 3 common))))
704 (perform-replace regexp to-string nil t delimited nil nil start end backward))
707 (defvar regexp-history nil
708 "History list for some commands that read regular expressions.
710 Maximum length of the history list is determined by the value
711 of `history-length', which see.")
713 (defvar occur-collect-regexp-history '("\\1")
714 "History of regexp for occur's collect operation")
716 (defcustom read-regexp-defaults-function nil
717 "Function that provides default regexp(s) for `read-regexp'.
718 This function should take no arguments and return one of: nil, a
719 regexp, or a list of regexps. Interactively, `read-regexp' uses
720 the return value of this function for its DEFAULT argument.
722 As an example, set this variable to `find-tag-default-as-regexp'
723 to default to the symbol at point.
725 To provide different default regexps for different commands,
726 the function that you set this to can check `this-command'."
727 :type '(choice
728 (const :tag "No default regexp reading function" nil)
729 (const :tag "Latest regexp history" regexp-history-last)
730 (function-item :tag "Tag at point"
731 find-tag-default)
732 (function-item :tag "Tag at point as regexp"
733 find-tag-default-as-regexp)
734 (function-item :tag "Tag at point as symbol regexp"
735 find-tag-default-as-symbol-regexp)
736 (function :tag "Your choice of function"))
737 :group 'matching
738 :version "24.4")
740 (defun read-regexp-suggestions ()
741 "Return a list of standard suggestions for `read-regexp'.
742 By default, the list includes the tag at point, the last isearch regexp,
743 the last isearch string, and the last replacement regexp. `read-regexp'
744 appends the list returned by this function to the end of values available
745 via \\<minibuffer-local-map>\\[next-history-element]."
746 (list
747 (find-tag-default-as-regexp)
748 (find-tag-default-as-symbol-regexp)
749 (car regexp-search-ring)
750 (regexp-quote (or (car search-ring) ""))
751 (car (symbol-value query-replace-from-history-variable))))
753 (defun read-regexp (prompt &optional defaults history)
754 "Read and return a regular expression as a string.
755 Prompt with the string PROMPT. If PROMPT ends in \":\" (followed by
756 optional whitespace), use it as-is. Otherwise, add \": \" to the end,
757 possibly preceded by the default result (see below).
759 The optional argument DEFAULTS can be either: nil, a string, a list
760 of strings, or a symbol. We use DEFAULTS to construct the default
761 return value in case of empty input.
763 If DEFAULTS is a string, we use it as-is.
765 If DEFAULTS is a list of strings, the first element is the
766 default return value, but all the elements are accessible
767 using the history command \\<minibuffer-local-map>\\[next-history-element].
769 If DEFAULTS is a non-nil symbol, then if `read-regexp-defaults-function'
770 is non-nil, we use that in place of DEFAULTS in the following:
771 If DEFAULTS is the symbol `regexp-history-last', we use the first
772 element of HISTORY (if specified) or `regexp-history'.
773 If DEFAULTS is a function, we call it with no arguments and use
774 what it returns, which should be either nil, a string, or a list of strings.
776 We append the standard values from `read-regexp-suggestions' to DEFAULTS
777 before using it.
779 If the first element of DEFAULTS is non-nil (and if PROMPT does not end
780 in \":\", followed by optional whitespace), we add it to the prompt.
782 The optional argument HISTORY is a symbol to use for the history list.
783 If nil, uses `regexp-history'."
784 (let* ((defaults
785 (if (and defaults (symbolp defaults))
786 (cond
787 ((eq (or read-regexp-defaults-function defaults)
788 'regexp-history-last)
789 (car (symbol-value (or history 'regexp-history))))
790 ((functionp (or read-regexp-defaults-function defaults))
791 (funcall (or read-regexp-defaults-function defaults))))
792 defaults))
793 (default (if (consp defaults) (car defaults) defaults))
794 (suggestions (if (listp defaults) defaults (list defaults)))
795 (suggestions (append suggestions (read-regexp-suggestions)))
796 (suggestions (delete-dups (delq nil (delete "" suggestions))))
797 ;; Do not automatically add default to the history for empty input.
798 (history-add-new-input nil)
799 (input (read-from-minibuffer
800 (cond ((string-match-p ":[ \t]*\\'" prompt)
801 prompt)
802 ((and default (> (length default) 0))
803 (format "%s (default %s): " prompt
804 (query-replace-descr default)))
806 (format "%s: " prompt)))
807 nil nil nil (or history 'regexp-history) suggestions t)))
808 (if (equal input "")
809 ;; Return the default value when the user enters empty input.
810 (prog1 (or default input)
811 (when default
812 (add-to-history (or history 'regexp-history) default)))
813 ;; Otherwise, add non-empty input to the history and return input.
814 (prog1 input
815 (add-to-history (or history 'regexp-history) input)))))
818 (defalias 'delete-non-matching-lines 'keep-lines)
819 (defalias 'delete-matching-lines 'flush-lines)
820 (defalias 'count-matches 'how-many)
823 (defun keep-lines-read-args (prompt)
824 "Read arguments for `keep-lines' and friends.
825 Prompt for a regexp with PROMPT.
826 Value is a list, (REGEXP)."
827 (list (read-regexp prompt) nil nil t))
829 (defun keep-lines (regexp &optional rstart rend interactive)
830 "Delete all lines except those containing matches for REGEXP.
831 A match split across lines preserves all the lines it lies in.
832 When called from Lisp (and usually interactively as well, see below)
833 applies to all lines starting after point.
835 If REGEXP contains upper case characters (excluding those preceded by `\\')
836 and `search-upper-case' is non-nil, the matching is case-sensitive.
838 Second and third arg RSTART and REND specify the region to operate on.
839 This command operates on (the accessible part of) all lines whose
840 accessible part is entirely contained in the region determined by RSTART
841 and REND. (A newline ending a line counts as part of that line.)
843 Interactively, in Transient Mark mode when the mark is active, operate
844 on all lines whose accessible part is entirely contained in the region.
845 Otherwise, the command applies to all lines starting after point.
846 When calling this function from Lisp, you can pretend that it was
847 called interactively by passing a non-nil INTERACTIVE argument.
849 This function starts looking for the next match from the end of
850 the previous match. Hence, it ignores matches that overlap
851 a previously found match."
852 (interactive
853 (progn
854 (barf-if-buffer-read-only)
855 (keep-lines-read-args "Keep lines containing match for regexp")))
856 (if rstart
857 (progn
858 (goto-char (min rstart rend))
859 (setq rend
860 (progn
861 (save-excursion
862 (goto-char (max rstart rend))
863 (unless (or (bolp) (eobp))
864 (forward-line 0))
865 (point-marker)))))
866 (if (and interactive (use-region-p))
867 (setq rstart (region-beginning)
868 rend (progn
869 (goto-char (region-end))
870 (unless (or (bolp) (eobp))
871 (forward-line 0))
872 (point-marker)))
873 (setq rstart (point)
874 rend (point-max-marker)))
875 (goto-char rstart))
876 (save-excursion
877 (or (bolp) (forward-line 1))
878 (let ((start (point))
879 (case-fold-search
880 (if (and case-fold-search search-upper-case)
881 (isearch-no-upper-case-p regexp t)
882 case-fold-search)))
883 (while (< (point) rend)
884 ;; Start is first char not preserved by previous match.
885 (if (not (re-search-forward regexp rend 'move))
886 (delete-region start rend)
887 (let ((end (save-excursion (goto-char (match-beginning 0))
888 (forward-line 0)
889 (point))))
890 ;; Now end is first char preserved by the new match.
891 (if (< start end)
892 (delete-region start end))))
894 (setq start (save-excursion (forward-line 1) (point)))
895 ;; If the match was empty, avoid matching again at same place.
896 (and (< (point) rend)
897 (= (match-beginning 0) (match-end 0))
898 (forward-char 1)))))
899 (set-marker rend nil)
900 nil)
903 (defun flush-lines (regexp &optional rstart rend interactive)
904 "Delete lines containing matches for REGEXP.
905 When called from Lisp (and usually when called interactively as
906 well, see below), applies to the part of the buffer after point.
907 The line point is in is deleted if and only if it contains a
908 match for regexp starting after point.
910 If REGEXP contains upper case characters (excluding those preceded by `\\')
911 and `search-upper-case' is non-nil, the matching is case-sensitive.
913 Second and third arg RSTART and REND specify the region to operate on.
914 Lines partially contained in this region are deleted if and only if
915 they contain a match entirely contained in it.
917 Interactively, in Transient Mark mode when the mark is active, operate
918 on the contents of the region. Otherwise, operate from point to the
919 end of (the accessible portion of) the buffer. When calling this function
920 from Lisp, you can pretend that it was called interactively by passing
921 a non-nil INTERACTIVE argument.
923 If a match is split across lines, all the lines it lies in are deleted.
924 They are deleted _before_ looking for the next match. Hence, a match
925 starting on the same line at which another match ended is ignored."
926 (interactive
927 (progn
928 (barf-if-buffer-read-only)
929 (keep-lines-read-args "Flush lines containing match for regexp")))
930 (if rstart
931 (progn
932 (goto-char (min rstart rend))
933 (setq rend (copy-marker (max rstart rend))))
934 (if (and interactive (use-region-p))
935 (setq rstart (region-beginning)
936 rend (copy-marker (region-end)))
937 (setq rstart (point)
938 rend (point-max-marker)))
939 (goto-char rstart))
940 (let ((case-fold-search
941 (if (and case-fold-search search-upper-case)
942 (isearch-no-upper-case-p regexp t)
943 case-fold-search)))
944 (save-excursion
945 (while (and (< (point) rend)
946 (re-search-forward regexp rend t))
947 (delete-region (save-excursion (goto-char (match-beginning 0))
948 (forward-line 0)
949 (point))
950 (progn (forward-line 1) (point))))))
951 (set-marker rend nil)
952 nil)
955 (defun how-many (regexp &optional rstart rend interactive)
956 "Print and return number of matches for REGEXP following point.
957 When called from Lisp and INTERACTIVE is omitted or nil, just return
958 the number, do not print it; if INTERACTIVE is t, the function behaves
959 in all respects as if it had been called interactively.
961 If REGEXP contains upper case characters (excluding those preceded by `\\')
962 and `search-upper-case' is non-nil, the matching is case-sensitive.
964 Second and third arg RSTART and REND specify the region to operate on.
966 Interactively, in Transient Mark mode when the mark is active, operate
967 on the contents of the region. Otherwise, operate from point to the
968 end of (the accessible portion of) the buffer.
970 This function starts looking for the next match from the end of
971 the previous match. Hence, it ignores matches that overlap
972 a previously found match."
973 (interactive
974 (keep-lines-read-args "How many matches for regexp"))
975 (save-excursion
976 (if rstart
977 (if rend
978 (progn
979 (goto-char (min rstart rend))
980 (setq rend (max rstart rend)))
981 (goto-char rstart)
982 (setq rend (point-max)))
983 (if (and interactive (use-region-p))
984 (setq rstart (region-beginning)
985 rend (region-end))
986 (setq rstart (point)
987 rend (point-max)))
988 (goto-char rstart))
989 (let ((count 0)
990 opoint
991 (case-fold-search
992 (if (and case-fold-search search-upper-case)
993 (isearch-no-upper-case-p regexp t)
994 case-fold-search)))
995 (while (and (< (point) rend)
996 (progn (setq opoint (point))
997 (re-search-forward regexp rend t)))
998 (if (= opoint (point))
999 (forward-char 1)
1000 (setq count (1+ count))))
1001 (when interactive (message "%d occurrence%s"
1002 count
1003 (if (= count 1) "" "s")))
1004 count)))
1007 (defvar occur-menu-map
1008 (let ((map (make-sparse-keymap)))
1009 (bindings--define-key map [next-error-follow-minor-mode]
1010 '(menu-item "Auto Occurrence Display"
1011 next-error-follow-minor-mode
1012 :help "Display another occurrence when moving the cursor"
1013 :button (:toggle . (and (boundp 'next-error-follow-minor-mode)
1014 next-error-follow-minor-mode))))
1015 (bindings--define-key map [separator-1] menu-bar-separator)
1016 (bindings--define-key map [kill-this-buffer]
1017 '(menu-item "Kill Occur Buffer" kill-this-buffer
1018 :help "Kill the current *Occur* buffer"))
1019 (bindings--define-key map [quit-window]
1020 '(menu-item "Quit Occur Window" quit-window
1021 :help "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
1022 (bindings--define-key map [revert-buffer]
1023 '(menu-item "Revert Occur Buffer" revert-buffer
1024 :help "Replace the text in the *Occur* buffer with the results of rerunning occur"))
1025 (bindings--define-key map [clone-buffer]
1026 '(menu-item "Clone Occur Buffer" clone-buffer
1027 :help "Create and return a twin copy of the current *Occur* buffer"))
1028 (bindings--define-key map [occur-rename-buffer]
1029 '(menu-item "Rename Occur Buffer" occur-rename-buffer
1030 :help "Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
1031 (bindings--define-key map [occur-edit-buffer]
1032 '(menu-item "Edit Occur Buffer" occur-edit-mode
1033 :help "Edit the *Occur* buffer and apply changes to the original buffers."))
1034 (bindings--define-key map [separator-2] menu-bar-separator)
1035 (bindings--define-key map [occur-mode-goto-occurrence-other-window]
1036 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
1037 :help "Go to the occurrence the current line describes, in another window"))
1038 (bindings--define-key map [occur-mode-goto-occurrence]
1039 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
1040 :help "Go to the occurrence the current line describes"))
1041 (bindings--define-key map [occur-mode-display-occurrence]
1042 '(menu-item "Display Occurrence" occur-mode-display-occurrence
1043 :help "Display in another window the occurrence the current line describes"))
1044 (bindings--define-key map [occur-next]
1045 '(menu-item "Move to Next Match" occur-next
1046 :help "Move to the Nth (default 1) next match in an Occur mode buffer"))
1047 (bindings--define-key map [occur-prev]
1048 '(menu-item "Move to Previous Match" occur-prev
1049 :help "Move to the Nth (default 1) previous match in an Occur mode buffer"))
1050 map)
1051 "Menu keymap for `occur-mode'.")
1053 (defvar occur-mode-map
1054 (let ((map (make-sparse-keymap)))
1055 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
1056 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1057 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
1058 (define-key map "e" 'occur-edit-mode)
1059 (define-key map "\C-m" 'occur-mode-goto-occurrence)
1060 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
1061 (define-key map "\C-o" 'occur-mode-display-occurrence)
1062 (define-key map "\M-n" 'occur-next)
1063 (define-key map "\M-p" 'occur-prev)
1064 (define-key map "r" 'occur-rename-buffer)
1065 (define-key map "c" 'clone-buffer)
1066 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1067 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1068 map)
1069 "Keymap for `occur-mode'.")
1071 (defvar occur-revert-arguments nil
1072 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
1073 See `occur-revert-function'.")
1074 (make-variable-buffer-local 'occur-revert-arguments)
1075 (put 'occur-revert-arguments 'permanent-local t)
1077 (defcustom occur-mode-hook '(turn-on-font-lock)
1078 "Hook run when entering Occur mode."
1079 :type 'hook
1080 :group 'matching)
1082 (defcustom occur-hook nil
1083 "Hook run by Occur when there are any matches."
1084 :type 'hook
1085 :group 'matching)
1087 (defcustom occur-mode-find-occurrence-hook nil
1088 "Hook run by Occur after locating an occurrence.
1089 This will be called with the cursor position at the occurrence. An application
1090 for this is to reveal context in an outline-mode when the occurrence is hidden."
1091 :type 'hook
1092 :group 'matching)
1094 (put 'occur-mode 'mode-class 'special)
1095 (define-derived-mode occur-mode special-mode "Occur"
1096 "Major mode for output from \\[occur].
1097 \\<occur-mode-map>Move point to one of the items in this buffer, then use
1098 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
1099 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
1101 \\{occur-mode-map}"
1102 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
1103 (setq next-error-function 'occur-next-error))
1106 ;;; Occur Edit mode
1108 (defvar occur-edit-mode-map
1109 (let ((map (make-sparse-keymap)))
1110 (set-keymap-parent map text-mode-map)
1111 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1112 (define-key map "\C-c\C-c" 'occur-cease-edit)
1113 (define-key map "\C-o" 'occur-mode-display-occurrence)
1114 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1115 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1116 map)
1117 "Keymap for `occur-edit-mode'.")
1119 (define-derived-mode occur-edit-mode occur-mode "Occur-Edit"
1120 "Major mode for editing *Occur* buffers.
1121 In this mode, changes to the *Occur* buffer are also applied to
1122 the originating buffer.
1124 To return to ordinary Occur mode, use \\[occur-cease-edit]."
1125 (setq buffer-read-only nil)
1126 (add-hook 'after-change-functions 'occur-after-change-function nil t)
1127 (message (substitute-command-keys
1128 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
1130 (defun occur-cease-edit ()
1131 "Switch from Occur Edit mode to Occur mode."
1132 (interactive)
1133 (when (derived-mode-p 'occur-edit-mode)
1134 (occur-mode)
1135 (message "Switching to Occur mode.")))
1137 (defun occur-after-change-function (beg end length)
1138 (save-excursion
1139 (goto-char beg)
1140 (let* ((line-beg (line-beginning-position))
1141 (m (get-text-property line-beg 'occur-target))
1142 (buf (marker-buffer m))
1143 col)
1144 (when (and (get-text-property line-beg 'occur-prefix)
1145 (not (get-text-property end 'occur-prefix)))
1146 (when (= length 0)
1147 ;; Apply occur-target property to inserted (e.g. yanked) text.
1148 (put-text-property beg end 'occur-target m)
1149 ;; Did we insert a newline? Occur Edit mode can't create new
1150 ;; Occur entries; just discard everything after the newline.
1151 (save-excursion
1152 (and (search-forward "\n" end t)
1153 (delete-region (1- (point)) end))))
1154 (let* ((line (- (line-number-at-pos)
1155 (line-number-at-pos (window-start))))
1156 (readonly (with-current-buffer buf buffer-read-only))
1157 (win (or (get-buffer-window buf)
1158 (display-buffer buf
1159 '(nil (inhibit-same-window . t)
1160 (inhibit-switch-frame . t)))))
1161 (line-end (line-end-position))
1162 (text (save-excursion
1163 (goto-char (next-single-property-change
1164 line-beg 'occur-prefix nil
1165 line-end))
1166 (setq col (- (point) line-beg))
1167 (buffer-substring-no-properties (point) line-end))))
1168 (with-selected-window win
1169 (goto-char m)
1170 (recenter line)
1171 (if readonly
1172 (message "Buffer `%s' is read only." buf)
1173 (delete-region (line-beginning-position) (line-end-position))
1174 (insert text))
1175 (move-to-column col)))))))
1178 (defun occur-revert-function (_ignore1 _ignore2)
1179 "Handle `revert-buffer' for Occur mode buffers."
1180 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
1182 (defun occur-mode-find-occurrence ()
1183 (let ((pos (get-text-property (point) 'occur-target)))
1184 (unless pos
1185 (error "No occurrence on this line"))
1186 (unless (buffer-live-p (marker-buffer pos))
1187 (error "Buffer for this occurrence was killed"))
1188 pos))
1190 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
1191 (defun occur-mode-goto-occurrence (&optional event)
1192 "Go to the occurrence on the current line."
1193 (interactive (list last-nonmenu-event))
1194 (let ((pos
1195 (if (null event)
1196 ;; Actually `event-end' works correctly with a nil argument as
1197 ;; well, so we could dispense with this test, but let's not
1198 ;; rely on this undocumented behavior.
1199 (occur-mode-find-occurrence)
1200 (with-current-buffer (window-buffer (posn-window (event-end event)))
1201 (save-excursion
1202 (goto-char (posn-point (event-end event)))
1203 (occur-mode-find-occurrence))))))
1204 (pop-to-buffer (marker-buffer pos))
1205 (goto-char pos)
1206 (run-hooks 'occur-mode-find-occurrence-hook)))
1208 (defun occur-mode-goto-occurrence-other-window ()
1209 "Go to the occurrence the current line describes, in another window."
1210 (interactive)
1211 (let ((pos (occur-mode-find-occurrence)))
1212 (switch-to-buffer-other-window (marker-buffer pos))
1213 (goto-char pos)
1214 (run-hooks 'occur-mode-find-occurrence-hook)))
1216 (defun occur-mode-display-occurrence ()
1217 "Display in another window the occurrence the current line describes."
1218 (interactive)
1219 (let ((pos (occur-mode-find-occurrence))
1220 window)
1221 (setq window (display-buffer (marker-buffer pos) t))
1222 ;; This is the way to set point in the proper window.
1223 (save-selected-window
1224 (select-window window)
1225 (goto-char pos)
1226 (run-hooks 'occur-mode-find-occurrence-hook))))
1228 (defun occur-find-match (n search message)
1229 (if (not n) (setq n 1))
1230 (let ((r))
1231 (while (> n 0)
1232 (setq r (funcall search (point) 'occur-match))
1233 (and r
1234 (get-text-property r 'occur-match)
1235 (setq r (funcall search r 'occur-match)))
1236 (if r
1237 (goto-char r)
1238 (error message))
1239 (setq n (1- n)))))
1241 (defun occur-next (&optional n)
1242 "Move to the Nth (default 1) next match in an Occur mode buffer."
1243 (interactive "p")
1244 (occur-find-match n #'next-single-property-change "No more matches"))
1246 (defun occur-prev (&optional n)
1247 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1248 (interactive "p")
1249 (occur-find-match n #'previous-single-property-change "No earlier matches"))
1251 (defun occur-next-error (&optional argp reset)
1252 "Move to the Nth (default 1) next match in an Occur mode buffer.
1253 Compatibility function for \\[next-error] invocations."
1254 (interactive "p")
1255 ;; we need to run occur-find-match from within the Occur buffer
1256 (with-current-buffer
1257 ;; Choose the buffer and make it current.
1258 (if (next-error-buffer-p (current-buffer))
1259 (current-buffer)
1260 (next-error-find-buffer nil nil
1261 (lambda ()
1262 (eq major-mode 'occur-mode))))
1264 (goto-char (cond (reset (point-min))
1265 ((< argp 0) (line-beginning-position))
1266 ((> argp 0) (line-end-position))
1267 ((point))))
1268 (occur-find-match
1269 (abs argp)
1270 (if (> 0 argp)
1271 #'previous-single-property-change
1272 #'next-single-property-change)
1273 "No more matches")
1274 ;; In case the *Occur* buffer is visible in a nonselected window.
1275 (let ((win (get-buffer-window (current-buffer) t)))
1276 (if win (set-window-point win (point))))
1277 (occur-mode-goto-occurrence)))
1279 (defface match
1280 '((((class color) (min-colors 88) (background light))
1281 :background "yellow1")
1282 (((class color) (min-colors 88) (background dark))
1283 :background "RoyalBlue3")
1284 (((class color) (min-colors 8) (background light))
1285 :background "yellow" :foreground "black")
1286 (((class color) (min-colors 8) (background dark))
1287 :background "blue" :foreground "white")
1288 (((type tty) (class mono))
1289 :inverse-video t)
1290 (t :background "gray"))
1291 "Face used to highlight matches permanently."
1292 :group 'matching
1293 :group 'basic-faces
1294 :version "22.1")
1296 (defcustom list-matching-lines-default-context-lines 0
1297 "Default number of context lines included around `list-matching-lines' matches.
1298 A negative number means to include that many lines before the match.
1299 A positive number means to include that many lines both before and after."
1300 :type 'integer
1301 :group 'matching)
1303 (defalias 'list-matching-lines 'occur)
1305 (defcustom list-matching-lines-face 'match
1306 "Face used by \\[list-matching-lines] to show the text that matches.
1307 If the value is nil, don't highlight the matching portions specially."
1308 :type 'face
1309 :group 'matching)
1311 (defcustom list-matching-lines-buffer-name-face 'underline
1312 "Face used by \\[list-matching-lines] to show the names of buffers.
1313 If the value is nil, don't highlight the buffer names specially."
1314 :type 'face
1315 :group 'matching)
1317 (defcustom list-matching-lines-current-line-face 'lazy-highlight
1318 "Face used by \\[list-matching-lines] to highlight the current line."
1319 :type 'face
1320 :group 'matching
1321 :version "26.1")
1323 (defcustom list-matching-lines-jump-to-current-line nil
1324 "If non-nil, \\[list-matching-lines] shows the current line highlighted.
1325 Set the point right after such line when there are matches after it."
1326 :type 'boolean
1327 :group 'matching
1328 :version "26.1")
1330 (defcustom list-matching-lines-prefix-face 'shadow
1331 "Face used by \\[list-matching-lines] to show the prefix column.
1332 If the face doesn't differ from the default face,
1333 don't highlight the prefix with line numbers specially."
1334 :type 'face
1335 :group 'matching
1336 :version "24.4")
1338 (defcustom occur-excluded-properties
1339 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1340 yank-handler follow-link)
1341 "Text properties to discard when copying lines to the *Occur* buffer.
1342 The value should be a list of text properties to discard or t,
1343 which means to discard all text properties."
1344 :type '(choice (const :tag "All" t) (repeat symbol))
1345 :group 'matching
1346 :version "22.1")
1348 (defun occur-read-primary-args ()
1349 (let* ((perform-collect (consp current-prefix-arg))
1350 (regexp (read-regexp (if perform-collect
1351 "Collect strings matching regexp"
1352 "List lines matching regexp")
1353 'regexp-history-last)))
1354 (list regexp
1355 (if perform-collect
1356 ;; Perform collect operation
1357 (if (zerop (regexp-opt-depth regexp))
1358 ;; No subexpression so collect the entire match.
1359 "\\&"
1360 ;; Get the regexp for collection pattern.
1361 (let ((default (car occur-collect-regexp-history)))
1362 (read-regexp
1363 (format "Regexp to collect (default %s): " default)
1364 default 'occur-collect-regexp-history)))
1365 ;; Otherwise normal occur takes numerical prefix argument.
1366 (when current-prefix-arg
1367 (prefix-numeric-value current-prefix-arg))))))
1369 (defun occur-rename-buffer (&optional unique-p interactive-p)
1370 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1371 Here `original-buffer-name' is the buffer name where Occur was originally run.
1372 When given the prefix argument, or called non-interactively, the renaming
1373 will not clobber the existing buffer(s) of that name, but use
1374 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1375 if you always want a separate *Occur* buffer for each buffer where you
1376 invoke `occur'."
1377 (interactive "P\np")
1378 (with-current-buffer
1379 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1380 (rename-buffer (concat "*Occur: "
1381 (mapconcat #'buffer-name
1382 (car (cddr occur-revert-arguments)) "/")
1383 "*")
1384 (or unique-p (not interactive-p)))))
1386 ;; Region limits when `occur' applies on a region.
1387 (defvar occur--region-start nil)
1388 (defvar occur--region-end nil)
1389 (defvar occur--matches-threshold nil)
1390 (defvar occur--orig-line nil)
1391 (defvar occur--orig-line-str nil)
1392 (defvar occur--final-pos nil)
1394 (defun occur (regexp &optional nlines region)
1395 "Show all lines in the current buffer containing a match for REGEXP.
1396 If a match spreads across multiple lines, all those lines are shown.
1398 Each match is extended to include complete lines. Only non-overlapping
1399 matches are considered. (Note that extending matches to complete
1400 lines could cause some of the matches to overlap; if so, they will not
1401 be shown as separate matches.)
1403 Each line is displayed with NLINES lines before and after, or -NLINES
1404 before if NLINES is negative.
1405 NLINES defaults to `list-matching-lines-default-context-lines'.
1406 Interactively it is the prefix arg.
1408 Optional arg REGION, if non-nil, mean restrict search to the
1409 specified region. Otherwise search the entire buffer.
1410 REGION must be a list of (START . END) positions as returned by
1411 `region-bounds'.
1413 The lines are shown in a buffer named `*Occur*'.
1414 It serves as a menu to find any of the occurrences in this buffer.
1415 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1416 If `list-matching-lines-jump-to-current-line' is non-nil, then show
1417 the current line highlighted with `list-matching-lines-current-line-face'
1418 and set point at the first match after such line.
1420 If REGEXP contains upper case characters (excluding those preceded by `\\')
1421 and `search-upper-case' is non-nil, the matching is case-sensitive.
1423 When NLINES is a string or when the function is called
1424 interactively with prefix argument without a number (`C-u' alone
1425 as prefix) the matching strings are collected into the `*Occur*'
1426 buffer by using NLINES as a replacement regexp. NLINES may
1427 contain \\& and \\N which convention follows `replace-match'.
1428 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1429 \"\\1\" for NLINES collects all the function names in a lisp
1430 program. When there is no parenthesized subexpressions in REGEXP
1431 the entire match is collected. In any case the searched buffer
1432 is not modified."
1433 (interactive
1434 (nconc (occur-read-primary-args)
1435 (and (use-region-p) (list (region-bounds)))))
1436 (let* ((start (and (caar region) (max (caar region) (point-min))))
1437 (end (and (cdar region) (min (cdar region) (point-max))))
1438 (in-region-p (or start end)))
1439 (when in-region-p
1440 (or start (setq start (point-min)))
1441 (or end (setq end (point-max))))
1442 (let ((occur--region-start start)
1443 (occur--region-end end)
1444 (occur--matches-threshold
1445 (and in-region-p
1446 (line-number-at-pos (min start end))))
1447 (occur--orig-line
1448 (line-number-at-pos (point)))
1449 (occur--orig-line-str
1450 (buffer-substring-no-properties
1451 (line-beginning-position)
1452 (line-end-position))))
1453 (save-excursion ; If no matches `occur-1' doesn't restore the point.
1454 (and in-region-p (narrow-to-region start end))
1455 (occur-1 regexp nlines (list (current-buffer)))
1456 (and in-region-p (widen))))))
1458 (defvar ido-ignore-item-temp-list)
1460 (defun multi-occur (bufs regexp &optional nlines)
1461 "Show all lines in buffers BUFS containing a match for REGEXP.
1462 This function acts on multiple buffers; otherwise, it is exactly like
1463 `occur'. When you invoke this command interactively, you must specify
1464 the buffer names that you want, one by one.
1465 See also `multi-occur-in-matching-buffers'."
1466 (interactive
1467 (cons
1468 (let* ((bufs (list (read-buffer "First buffer to search: "
1469 (current-buffer) t)))
1470 (buf nil)
1471 (ido-ignore-item-temp-list bufs))
1472 (while (not (string-equal
1473 (setq buf (read-buffer
1474 (if (eq read-buffer-function #'ido-read-buffer)
1475 "Next buffer to search (C-j to end): "
1476 "Next buffer to search (RET to end): ")
1477 nil t))
1478 ""))
1479 (cl-pushnew buf bufs)
1480 (setq ido-ignore-item-temp-list bufs))
1481 (nreverse (mapcar #'get-buffer bufs)))
1482 (occur-read-primary-args)))
1483 (occur-1 regexp nlines bufs))
1485 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1486 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1487 Normally BUFREGEXP matches against each buffer's visited file name,
1488 but if you specify a prefix argument, it matches against the buffer name.
1489 See also `multi-occur'."
1490 (interactive
1491 (cons
1492 (let* ((default (car regexp-history))
1493 (input
1494 (read-regexp
1495 (if current-prefix-arg
1496 "List lines in buffers whose names match regexp: "
1497 "List lines in buffers whose filenames match regexp: "))))
1498 (if (equal input "")
1499 default
1500 input))
1501 (occur-read-primary-args)))
1502 (when bufregexp
1503 (occur-1 regexp nil
1504 (delq nil
1505 (mapcar (lambda (buf)
1506 (when (if allbufs
1507 (string-match bufregexp
1508 (buffer-name buf))
1509 (and (buffer-file-name buf)
1510 (string-match bufregexp
1511 (buffer-file-name buf))))
1512 buf))
1513 (buffer-list))))))
1515 (defun occur-regexp-descr (regexp)
1516 (format " for %s\"%s\""
1517 (or (get-text-property 0 'isearch-regexp-function-descr regexp)
1519 (if (get-text-property 0 'isearch-string regexp)
1520 (propertize
1521 (query-replace-descr
1522 (get-text-property 0 'isearch-string regexp))
1523 'help-echo regexp)
1524 (query-replace-descr regexp))))
1526 (defun occur-1 (regexp nlines bufs &optional buf-name)
1527 (unless (and regexp (not (equal regexp "")))
1528 (error "Occur doesn't work with the empty regexp"))
1529 (unless buf-name
1530 (setq buf-name "*Occur*"))
1531 (let (occur-buf
1532 (active-bufs (delq nil (mapcar #'(lambda (buf)
1533 (when (buffer-live-p buf) buf))
1534 bufs))))
1535 ;; Handle the case where one of the buffers we're searching is the
1536 ;; output buffer. Just rename it.
1537 (when (member buf-name (mapcar 'buffer-name active-bufs))
1538 (with-current-buffer (get-buffer buf-name)
1539 (rename-uniquely)))
1541 ;; Now find or create the output buffer.
1542 ;; If we just renamed that buffer, we will make a new one here.
1543 (setq occur-buf (get-buffer-create buf-name))
1545 (with-current-buffer occur-buf
1546 (if (stringp nlines)
1547 (fundamental-mode) ;; This is for collect operation.
1548 (occur-mode))
1549 (let ((inhibit-read-only t)
1550 ;; Don't generate undo entries for creation of the initial contents.
1551 (buffer-undo-list t)
1552 (occur--final-pos nil))
1553 (erase-buffer)
1554 (let ((count
1555 (if (stringp nlines)
1556 ;; Treat nlines as a regexp to collect.
1557 (let ((bufs active-bufs)
1558 (count 0))
1559 (while bufs
1560 (with-current-buffer (car bufs)
1561 (save-excursion
1562 (goto-char (point-min))
1563 (while (re-search-forward regexp nil t)
1564 ;; Insert the replacement regexp.
1565 (let ((str (match-substitute-replacement nlines)))
1566 (if str
1567 (with-current-buffer occur-buf
1568 (insert str)
1569 (setq count (1+ count))
1570 (or (zerop (current-column))
1571 (insert "\n"))))))))
1572 (setq bufs (cdr bufs)))
1573 count)
1574 ;; Perform normal occur.
1575 (occur-engine
1576 regexp active-bufs occur-buf
1577 (or nlines list-matching-lines-default-context-lines)
1578 (if (and case-fold-search search-upper-case)
1579 (isearch-no-upper-case-p regexp t)
1580 case-fold-search)
1581 list-matching-lines-buffer-name-face
1582 (if (face-differs-from-default-p list-matching-lines-prefix-face)
1583 list-matching-lines-prefix-face)
1584 list-matching-lines-face
1585 (not (eq occur-excluded-properties t))))))
1586 (let* ((bufcount (length active-bufs))
1587 (diff (- (length bufs) bufcount)))
1588 (message "Searched %d buffer%s%s; %s match%s%s"
1589 bufcount (if (= bufcount 1) "" "s")
1590 (if (zerop diff) "" (format " (%d killed)" diff))
1591 (if (zerop count) "no" (format "%d" count))
1592 (if (= count 1) "" "es")
1593 ;; Don't display regexp if with remaining text
1594 ;; it is longer than window-width.
1595 (if (> (+ (length (or (get-text-property 0 'isearch-string regexp)
1596 regexp))
1598 (window-width))
1599 "" (occur-regexp-descr regexp))))
1600 (setq occur-revert-arguments (list regexp nlines bufs))
1601 (if (= count 0)
1602 (kill-buffer occur-buf)
1603 (display-buffer occur-buf)
1604 (when occur--final-pos
1605 (set-window-point
1606 (get-buffer-window occur-buf 'all-frames)
1607 occur--final-pos))
1608 (setq next-error-last-buffer occur-buf)
1609 (setq buffer-read-only t)
1610 (set-buffer-modified-p nil)
1611 (run-hooks 'occur-hook)))))))
1613 (defun occur-engine (regexp buffers out-buf nlines case-fold
1614 title-face prefix-face match-face keep-props)
1615 (with-current-buffer out-buf
1616 (let ((global-lines 0) ;; total count of matching lines
1617 (global-matches 0) ;; total count of matches
1618 (coding nil)
1619 (case-fold-search case-fold)
1620 (in-region-p (and occur--region-start occur--region-end))
1621 (multi-occur-p (cdr buffers)))
1622 ;; Map over all the buffers
1623 (dolist (buf buffers)
1624 (when (buffer-live-p buf)
1625 (let ((lines 0) ;; count of matching lines
1626 (matches 0) ;; count of matches
1627 (curr-line ;; line count
1628 (or occur--matches-threshold 1))
1629 (orig-line occur--orig-line)
1630 (orig-line-str occur--orig-line-str)
1631 (orig-line-shown-p)
1632 (prev-line nil) ;; line number of prev match endpt
1633 (prev-after-lines nil) ;; context lines of prev match
1634 (matchbeg 0)
1635 (origpt nil)
1636 (begpt nil)
1637 (endpt nil)
1638 (finalpt nil)
1639 (marker nil)
1640 (curstring "")
1641 (ret nil)
1642 (inhibit-field-text-motion t)
1643 (headerpt (with-current-buffer out-buf (point))))
1644 (with-current-buffer buf
1645 (or coding
1646 ;; Set CODING only if the current buffer locally
1647 ;; binds buffer-file-coding-system.
1648 (not (local-variable-p 'buffer-file-coding-system))
1649 (setq coding buffer-file-coding-system))
1650 (save-excursion
1651 (goto-char (point-min)) ;; begin searching in the buffer
1652 (while (not (eobp))
1653 (setq origpt (point))
1654 (when (setq endpt (re-search-forward regexp nil t))
1655 (setq lines (1+ lines)) ;; increment matching lines count
1656 (setq matchbeg (match-beginning 0))
1657 ;; Get beginning of first match line and end of the last.
1658 (save-excursion
1659 (goto-char matchbeg)
1660 (setq begpt (line-beginning-position))
1661 (goto-char endpt)
1662 (setq endpt (line-end-position)))
1663 ;; Sum line numbers up to the first match line.
1664 (setq curr-line (+ curr-line (count-lines origpt begpt)))
1665 (setq marker (make-marker))
1666 (set-marker marker matchbeg)
1667 (setq curstring (occur-engine-line begpt endpt keep-props))
1668 ;; Highlight the matches
1669 (let ((len (length curstring))
1670 (start 0))
1671 ;; Count empty lines that don't use next loop (Bug#22062).
1672 (when (zerop len)
1673 (setq matches (1+ matches)))
1674 (while (and (< start len)
1675 (string-match regexp curstring start))
1676 (setq matches (1+ matches))
1677 (add-text-properties
1678 (match-beginning 0) (match-end 0)
1679 '(occur-match t) curstring)
1680 (when match-face
1681 ;; Add `match-face' to faces copied from the buffer.
1682 (add-face-text-property
1683 (match-beginning 0) (match-end 0)
1684 match-face nil curstring))
1685 ;; Avoid infloop (Bug#7593).
1686 (let ((end (match-end 0)))
1687 (setq start (if (= start end) (1+ start) end)))))
1688 ;; Generate the string to insert for this match
1689 (let* ((match-prefix
1690 ;; Using 7 digits aligns tabs properly.
1691 (apply #'propertize (format "%7d:" curr-line)
1692 (append
1693 (when prefix-face
1694 `(font-lock-face ,prefix-face))
1695 `(occur-prefix t mouse-face (highlight)
1696 ;; Allow insertion of text at
1697 ;; the end of the prefix (for
1698 ;; Occur Edit mode).
1699 front-sticky t rear-nonsticky t
1700 occur-target ,marker follow-link t
1701 help-echo "mouse-2: go to this occurrence"))))
1702 (match-str
1703 ;; We don't put `mouse-face' on the newline,
1704 ;; because that loses. And don't put it
1705 ;; on context lines to reduce flicker.
1706 (propertize curstring 'mouse-face (list 'highlight)
1707 'occur-target marker
1708 'follow-link t
1709 'help-echo
1710 "mouse-2: go to this occurrence"))
1711 (out-line
1712 (concat
1713 match-prefix
1714 ;; Add non-numeric prefix to all non-first lines
1715 ;; of multi-line matches.
1716 (replace-regexp-in-string
1717 "\n"
1718 (if prefix-face
1719 (propertize "\n :" 'font-lock-face prefix-face)
1720 "\n :")
1721 match-str)
1722 ;; Add marker at eol, but no mouse props.
1723 (propertize "\n" 'occur-target marker)))
1724 (data
1725 (if (= nlines 0)
1726 ;; The simple display style
1727 out-line
1728 ;; The complex multi-line display style.
1729 (setq ret (occur-context-lines
1730 out-line nlines keep-props begpt endpt
1731 curr-line prev-line prev-after-lines
1732 prefix-face))
1733 ;; Set first elem of the returned list to `data',
1734 ;; and the second elem to `prev-after-lines'.
1735 (setq prev-after-lines (nth 1 ret))
1736 (nth 0 ret))))
1737 ;; Actually insert the match display data
1738 (with-current-buffer out-buf
1739 (when (and list-matching-lines-jump-to-current-line
1740 (not multi-occur-p)
1741 (not orig-line-shown-p)
1742 (>= curr-line orig-line))
1743 (insert
1744 (concat
1745 (propertize
1746 (format "%7d:%s" orig-line orig-line-str)
1747 'face list-matching-lines-current-line-face
1748 'mouse-face 'mode-line-highlight
1749 'help-echo "Current line") "\n"))
1750 (setq orig-line-shown-p t finalpt (point)))
1751 (insert data)))
1752 (goto-char endpt))
1753 (if endpt
1754 (progn
1755 ;; Sum line numbers between first and last match lines.
1756 (setq curr-line (+ curr-line (count-lines begpt endpt)
1757 ;; Add 1 for empty last match line since
1758 ;; count-lines returns 1 line less.
1759 (if (and (bolp) (eolp)) 1 0)))
1760 ;; On to the next match...
1761 (forward-line 1))
1762 (goto-char (point-max)))
1763 (setq prev-line (1- curr-line)))
1764 ;; Insert original line if haven't done yet.
1765 (when (and list-matching-lines-jump-to-current-line
1766 (not multi-occur-p)
1767 (not orig-line-shown-p))
1768 (with-current-buffer out-buf
1769 (insert
1770 (concat
1771 (propertize
1772 (format "%7d:%s" orig-line orig-line-str)
1773 'face list-matching-lines-current-line-face
1774 'mouse-face 'mode-line-highlight
1775 'help-echo "Current line") "\n"))))
1776 ;; Flush remaining context after-lines.
1777 (when prev-after-lines
1778 (with-current-buffer out-buf
1779 (insert (apply #'concat (occur-engine-add-prefix
1780 prev-after-lines prefix-face)))))))
1781 (when (not (zerop lines)) ;; is the count zero?
1782 (setq global-lines (+ global-lines lines)
1783 global-matches (+ global-matches matches))
1784 (with-current-buffer out-buf
1785 (goto-char headerpt)
1786 (let ((beg (point))
1787 end)
1788 (insert (propertize
1789 (format "%d match%s%s%s in buffer: %s%s\n"
1790 matches (if (= matches 1) "" "es")
1791 ;; Don't display the same number of lines
1792 ;; and matches in case of 1 match per line.
1793 (if (= lines matches)
1794 "" (format " in %d line%s"
1795 lines (if (= lines 1) "" "s")))
1796 ;; Don't display regexp for multi-buffer.
1797 (if (> (length buffers) 1)
1798 "" (occur-regexp-descr regexp))
1799 (buffer-name buf)
1800 (if in-region-p
1801 (format " within region: %d-%d"
1802 occur--region-start
1803 occur--region-end)
1804 ""))
1805 'read-only t))
1806 (setq end (point))
1807 (add-text-properties beg end `(occur-title ,buf))
1808 (when title-face
1809 (add-face-text-property beg end title-face))
1810 (goto-char (if finalpt
1811 (setq occur--final-pos
1812 (cl-incf finalpt (- end beg)))
1813 (point-min)))))))))
1814 ;; Display total match count and regexp for multi-buffer.
1815 (when (and (not (zerop global-lines)) (> (length buffers) 1))
1816 (goto-char (point-min))
1817 (let ((beg (point))
1818 end)
1819 (insert (format "%d match%s%s total%s:\n"
1820 global-matches (if (= global-matches 1) "" "es")
1821 ;; Don't display the same number of lines
1822 ;; and matches in case of 1 match per line.
1823 (if (= global-lines global-matches)
1824 "" (format " in %d line%s"
1825 global-lines (if (= global-lines 1) "" "s")))
1826 (occur-regexp-descr regexp)))
1827 (setq end (point))
1828 (when title-face
1829 (add-face-text-property beg end title-face)))
1830 (goto-char (point-min)))
1831 (if coding
1832 ;; CODING is buffer-file-coding-system of the first buffer
1833 ;; that locally binds it. Let's use it also for the output
1834 ;; buffer.
1835 (set-buffer-file-coding-system coding))
1836 ;; Return the number of matches
1837 global-matches)))
1839 (defun occur-engine-line (beg end &optional keep-props)
1840 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1841 (text-property-not-all beg end 'fontified t))
1842 (if (fboundp 'jit-lock-fontify-now)
1843 (jit-lock-fontify-now beg end)))
1844 (if (and keep-props (not (eq occur-excluded-properties t)))
1845 (let ((str (buffer-substring beg end)))
1846 (remove-list-of-text-properties
1847 0 (length str) occur-excluded-properties str)
1848 str)
1849 (buffer-substring-no-properties beg end)))
1851 (defun occur-engine-add-prefix (lines &optional prefix-face)
1852 (mapcar
1853 #'(lambda (line)
1854 (concat (if prefix-face
1855 (propertize " :" 'font-lock-face prefix-face)
1856 " :")
1857 line "\n"))
1858 lines))
1860 (defun occur-accumulate-lines (count &optional keep-props pt)
1861 (save-excursion
1862 (when pt
1863 (goto-char pt))
1864 (let ((forwardp (> count 0))
1865 result beg end moved)
1866 (while (not (or (zerop count)
1867 (if forwardp
1868 (eobp)
1869 (and (bobp) (not moved)))))
1870 (setq count (+ count (if forwardp -1 1)))
1871 (setq beg (line-beginning-position)
1872 end (line-end-position))
1873 (push (occur-engine-line beg end keep-props) result)
1874 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1875 (nreverse result))))
1877 ;; Generate context display for occur.
1878 ;; OUT-LINE is the line where the match is.
1879 ;; NLINES and KEEP-PROPS are args to occur-engine.
1880 ;; CURR-LINE is line count of the current match,
1881 ;; PREV-LINE is line count of the previous match,
1882 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1883 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1884 ;; then concatenate them all together.
1885 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1886 curr-line prev-line prev-after-lines
1887 &optional prefix-face)
1888 ;; Find after- and before-context lines of the current match.
1889 (let ((before-lines
1890 (nreverse (cdr (occur-accumulate-lines
1891 (- (1+ (abs nlines))) keep-props begpt))))
1892 (after-lines
1893 (cdr (occur-accumulate-lines
1894 (1+ nlines) keep-props endpt)))
1895 separator)
1897 ;; Combine after-lines of the previous match
1898 ;; with before-lines of the current match.
1900 (when prev-after-lines
1901 ;; Don't overlap prev after-lines with current before-lines.
1902 (if (>= (+ prev-line (length prev-after-lines))
1903 (- curr-line (length before-lines)))
1904 (setq prev-after-lines
1905 (butlast prev-after-lines
1906 (- (length prev-after-lines)
1907 (- curr-line prev-line (length before-lines) 1))))
1908 ;; Separate non-overlapping context lines with a dashed line.
1909 (setq separator "-------\n")))
1911 (when prev-line
1912 ;; Don't overlap current before-lines with previous match line.
1913 (if (<= (- curr-line (length before-lines))
1914 prev-line)
1915 (setq before-lines
1916 (nthcdr (- (length before-lines)
1917 (- curr-line prev-line 1))
1918 before-lines))
1919 ;; Separate non-overlapping before-context lines.
1920 (unless (> nlines 0)
1921 (setq separator "-------\n"))))
1923 (list
1924 ;; Return a list where the first element is the output line.
1925 (apply #'concat
1926 (append
1927 (if prev-after-lines
1928 (occur-engine-add-prefix prev-after-lines prefix-face))
1929 (if separator
1930 (list (if prefix-face
1931 (propertize separator 'font-lock-face prefix-face)
1932 separator)))
1933 (occur-engine-add-prefix before-lines prefix-face)
1934 (list out-line)))
1935 ;; And the second element is the list of context after-lines.
1936 (if (> nlines 0) after-lines))))
1939 ;; It would be nice to use \\[...], but there is no reasonable way
1940 ;; to make that display both SPC and Y.
1941 (defconst query-replace-help
1942 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1943 RET or `q' to exit, Period to replace one match and exit,
1944 Comma to replace but not move point immediately,
1945 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1946 C-w to delete match and recursive edit,
1947 C-l to clear the screen, redisplay, and offer same replacement again,
1948 ! to replace all remaining matches in this buffer with no more questions,
1949 ^ to move point back to previous match,
1950 u to undo previous replacement,
1951 U to undo all replacements,
1952 E to edit the replacement string.
1953 In multi-buffer replacements type `Y' to replace all remaining
1954 matches in all remaining buffers with no more questions,
1955 `N' to skip to the next buffer without replacing remaining matches
1956 in the current buffer."
1957 "Help message while in `query-replace'.")
1959 (defvar query-replace-map
1960 (let ((map (make-sparse-keymap)))
1961 (define-key map " " 'act)
1962 (define-key map "\d" 'skip)
1963 (define-key map [delete] 'skip)
1964 (define-key map [backspace] 'skip)
1965 (define-key map "y" 'act)
1966 (define-key map "n" 'skip)
1967 (define-key map "Y" 'act)
1968 (define-key map "N" 'skip)
1969 (define-key map "e" 'edit-replacement)
1970 (define-key map "E" 'edit-replacement)
1971 (define-key map "," 'act-and-show)
1972 (define-key map "q" 'exit)
1973 (define-key map "\r" 'exit)
1974 (define-key map [return] 'exit)
1975 (define-key map "." 'act-and-exit)
1976 (define-key map "\C-r" 'edit)
1977 (define-key map "\C-w" 'delete-and-edit)
1978 (define-key map "\C-l" 'recenter)
1979 (define-key map "!" 'automatic)
1980 (define-key map "^" 'backup)
1981 (define-key map "u" 'undo)
1982 (define-key map "U" 'undo-all)
1983 (define-key map "\C-h" 'help)
1984 (define-key map [f1] 'help)
1985 (define-key map [help] 'help)
1986 (define-key map "?" 'help)
1987 (define-key map "\C-g" 'quit)
1988 (define-key map "\C-]" 'quit)
1989 (define-key map "\C-v" 'scroll-up)
1990 (define-key map "\M-v" 'scroll-down)
1991 (define-key map [next] 'scroll-up)
1992 (define-key map [prior] 'scroll-down)
1993 (define-key map [?\C-\M-v] 'scroll-other-window)
1994 (define-key map [M-next] 'scroll-other-window)
1995 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1996 (define-key map [M-prior] 'scroll-other-window-down)
1997 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1998 ;; should check for ESC specially.
1999 ;; (define-key map "\e" 'exit-prefix)
2000 (define-key map [escape] 'exit-prefix)
2001 map)
2002 "Keymap of responses to questions posed by commands like `query-replace'.
2003 The \"bindings\" in this map are not commands; they are answers.
2004 The valid answers include `act', `skip', `act-and-show',
2005 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
2006 `scroll-down', `scroll-other-window', `scroll-other-window-down',
2007 `edit', `edit-replacement', `delete-and-edit', `automatic',
2008 `backup', `undo', `undo-all', `quit', and `help'.
2010 This keymap is used by `y-or-n-p' as well as `query-replace'.")
2012 (defvar multi-query-replace-map
2013 (let ((map (make-sparse-keymap)))
2014 (set-keymap-parent map query-replace-map)
2015 (define-key map "Y" 'automatic-all)
2016 (define-key map "N" 'exit-current)
2017 map)
2018 "Keymap that defines additional bindings for multi-buffer replacements.
2019 It extends its parent map `query-replace-map' with new bindings to
2020 operate on a set of buffers/files. The difference with its parent map
2021 is the additional answers `automatic-all' to replace all remaining
2022 matches in all remaining buffers with no more questions, and
2023 `exit-current' to skip remaining matches in the current buffer
2024 and to continue with the next buffer in the sequence.")
2026 (defun replace-match-string-symbols (n)
2027 "Process a list (and any sub-lists), expanding certain symbols.
2028 Symbol Expands To
2029 N (match-string N) (where N is a string of digits)
2030 #N (string-to-number (match-string N))
2031 & (match-string 0)
2032 #& (string-to-number (match-string 0))
2033 # replace-count
2035 Note that these symbols must be preceded by a backslash in order to
2036 type them using Lisp syntax."
2037 (while (consp n)
2038 (cond
2039 ((consp (car n))
2040 (replace-match-string-symbols (car n))) ;Process sub-list
2041 ((symbolp (car n))
2042 (let ((name (symbol-name (car n))))
2043 (cond
2044 ((string-match "^[0-9]+$" name)
2045 (setcar n (list 'match-string (string-to-number name))))
2046 ((string-match "^#[0-9]+$" name)
2047 (setcar n (list 'string-to-number
2048 (list 'match-string
2049 (string-to-number (substring name 1))))))
2050 ((string= "&" name)
2051 (setcar n '(match-string 0)))
2052 ((string= "#&" name)
2053 (setcar n '(string-to-number (match-string 0))))
2054 ((string= "#" name)
2055 (setcar n 'replace-count))))))
2056 (setq n (cdr n))))
2058 (defun replace-eval-replacement (expression count)
2059 (let* ((replace-count count)
2060 (replacement
2061 (condition-case err
2062 (eval expression)
2063 (error
2064 (error "Error evaluating replacement expression: %S" err)))))
2065 (if (stringp replacement)
2066 replacement
2067 (prin1-to-string replacement t))))
2069 (defun replace-quote (replacement)
2070 "Quote a replacement string.
2071 This just doubles all backslashes in REPLACEMENT and
2072 returns the resulting string. If REPLACEMENT is not
2073 a string, it is first passed through `prin1-to-string'
2074 with the `noescape' argument set.
2076 `match-data' is preserved across the call."
2077 (save-match-data
2078 (replace-regexp-in-string "\\\\" "\\\\"
2079 (if (stringp replacement)
2080 replacement
2081 (prin1-to-string replacement t))
2082 t t)))
2084 (defun replace-loop-through-replacements (data count)
2085 ;; DATA is a vector containing the following values:
2086 ;; 0 next-rotate-count
2087 ;; 1 repeat-count
2088 ;; 2 next-replacement
2089 ;; 3 replacements
2090 (if (= (aref data 0) count)
2091 (progn
2092 (aset data 0 (+ count (aref data 1)))
2093 (let ((next (cdr (aref data 2))))
2094 (aset data 2 (if (consp next) next (aref data 3))))))
2095 (car (aref data 2)))
2097 (defun replace-match-data (integers reuse &optional new)
2098 "Like `match-data', but markers in REUSE get invalidated.
2099 If NEW is non-nil, it is set and returned instead of fresh data,
2100 but coerced to the correct value of INTEGERS."
2101 (or (and new
2102 (progn
2103 (set-match-data new)
2104 (and (eq new reuse)
2105 (eq (null integers) (markerp (car reuse)))
2106 new)))
2107 (match-data integers reuse t)))
2109 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data
2110 &optional backward)
2111 "Make a replacement with `replace-match', editing `\\?'.
2112 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
2113 After possibly editing it (if `\\?' is present), NEWTEXT is also
2114 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
2115 is made (to save time).
2116 MATCH-DATA is used for the replacement, and is a data structure
2117 as returned from the `match-data' function.
2118 In case editing is done, it is changed to use markers. BACKWARD is
2119 used to reverse the replacement direction.
2121 The return value is non-nil if there has been no `\\?' or NOEDIT was
2122 passed in. If LITERAL is set, no checking is done, anyway."
2123 (unless (or literal noedit)
2124 (setq noedit t)
2125 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
2126 newtext)
2127 (setq newtext
2128 (read-string "Edit replacement string: "
2129 (prog1
2130 (cons
2131 (replace-match "" t t newtext 3)
2132 (1+ (match-beginning 3)))
2133 (setq match-data
2134 (replace-match-data
2135 nil match-data match-data))))
2136 noedit nil)))
2137 (set-match-data match-data)
2138 (replace-match newtext fixedcase literal)
2139 ;; `replace-match' leaves point at the end of the replacement text,
2140 ;; so move point to the beginning when replacing backward.
2141 (when backward (goto-char (nth 0 match-data)))
2142 noedit)
2144 (defvar replace-update-post-hook nil
2145 "Function(s) to call after query-replace has found a match in the buffer.")
2147 (defvar replace-search-function nil
2148 "Function to use when searching for strings to replace.
2149 It is used by `query-replace' and `replace-string', and is called
2150 with three arguments, as if it were `search-forward'.")
2152 (defvar replace-re-search-function nil
2153 "Function to use when searching for regexps to replace.
2154 It is used by `query-replace-regexp', `replace-regexp',
2155 `query-replace-regexp-eval', and `map-query-replace-regexp'.
2156 It is called with three arguments, as if it were
2157 `re-search-forward'.")
2159 (defun replace-search (search-string limit regexp-flag delimited-flag
2160 case-fold &optional backward)
2161 "Search for the next occurrence of SEARCH-STRING to replace."
2162 ;; Let-bind global isearch-* variables to values used
2163 ;; to search the next replacement. These let-bindings
2164 ;; should be effective both at the time of calling
2165 ;; `isearch-search-fun-default' and also at the
2166 ;; time of funcalling `search-function'.
2167 ;; These isearch-* bindings can't be placed higher
2168 ;; outside of this function because then another I-search
2169 ;; used after `recursive-edit' might override them.
2170 (let* ((isearch-regexp regexp-flag)
2171 (isearch-regexp-function (or delimited-flag
2172 (and replace-char-fold
2173 (not regexp-flag)
2174 #'char-fold-to-regexp)))
2175 (isearch-lax-whitespace
2176 replace-lax-whitespace)
2177 (isearch-regexp-lax-whitespace
2178 replace-regexp-lax-whitespace)
2179 (isearch-case-fold-search case-fold)
2180 (isearch-adjusted nil)
2181 (isearch-nonincremental t) ; don't use lax word mode
2182 (isearch-forward (not backward))
2183 (search-function
2184 (or (if regexp-flag
2185 replace-re-search-function
2186 replace-search-function)
2187 (isearch-search-fun-default))))
2188 (funcall search-function search-string limit t)))
2190 (defvar replace-overlay nil)
2192 (defun replace-highlight (match-beg match-end range-beg range-end
2193 search-string regexp-flag delimited-flag
2194 case-fold &optional backward)
2195 (if query-replace-highlight
2196 (if replace-overlay
2197 (move-overlay replace-overlay match-beg match-end (current-buffer))
2198 (setq replace-overlay (make-overlay match-beg match-end))
2199 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2200 (overlay-put replace-overlay 'face 'query-replace)))
2201 (if query-replace-lazy-highlight
2202 (let ((isearch-string search-string)
2203 (isearch-regexp regexp-flag)
2204 (isearch-regexp-function delimited-flag)
2205 (isearch-lax-whitespace
2206 replace-lax-whitespace)
2207 (isearch-regexp-lax-whitespace
2208 replace-regexp-lax-whitespace)
2209 (isearch-case-fold-search case-fold)
2210 (isearch-forward (not backward))
2211 (isearch-other-end match-beg)
2212 (isearch-error nil))
2213 (isearch-lazy-highlight-new-loop range-beg range-end))))
2215 (defun replace-dehighlight ()
2216 (when replace-overlay
2217 (delete-overlay replace-overlay))
2218 (when query-replace-lazy-highlight
2219 (lazy-highlight-cleanup lazy-highlight-cleanup)
2220 (setq isearch-lazy-highlight-last-string nil))
2221 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2222 (isearch-clean-overlays))
2224 (defun perform-replace (from-string replacements
2225 query-flag regexp-flag delimited-flag
2226 &optional repeat-count map start end backward region-noncontiguous-p)
2227 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2228 Don't use this in your own program unless you want to query and set the mark
2229 just as `query-replace' does. Instead, write a simple loop like this:
2231 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2232 (replace-match \"foobar\" nil nil))
2234 which will run faster and probably do exactly what you want. Please
2235 see the documentation of `replace-match' to find out how to simulate
2236 `case-replace'.
2238 This function returns nil if and only if there were no matches to
2239 make, or the user didn't cancel the call.
2241 REPLACEMENTS is either a string, a list of strings, or a cons cell
2242 containing a function and its first argument. The function is
2243 called to generate each replacement like this:
2244 (funcall (car replacements) (cdr replacements) replace-count)
2245 It must return a string."
2246 (or map (setq map query-replace-map))
2247 (and query-flag minibuffer-auto-raise
2248 (raise-frame (window-frame (minibuffer-window))))
2249 (let* ((case-fold-search
2250 (if (and case-fold-search search-upper-case)
2251 (isearch-no-upper-case-p from-string regexp-flag)
2252 case-fold-search))
2253 (nocasify (not (and case-replace case-fold-search)))
2254 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2255 (search-string from-string)
2256 (real-match-data nil) ; The match data for the current match.
2257 (next-replacement nil)
2258 ;; This is non-nil if we know there is nothing for the user
2259 ;; to edit in the replacement.
2260 (noedit nil)
2261 (keep-going t)
2262 (stack nil)
2263 (search-string-replaced nil) ; last string matching `from-string'
2264 (next-replacement-replaced nil) ; replacement string
2265 ; (substituted regexp)
2266 (last-was-undo)
2267 (replace-count 0)
2268 (skip-read-only-count 0)
2269 (skip-filtered-count 0)
2270 (skip-invisible-count 0)
2271 (nonempty-match nil)
2272 (multi-buffer nil)
2273 (recenter-last-op nil) ; Start cycling order with initial position.
2275 ;; If non-nil, it is marker saying where in the buffer to stop.
2276 (limit nil)
2277 ;; Use local binding in add-function below.
2278 (isearch-filter-predicate isearch-filter-predicate)
2279 (region-bounds nil)
2281 ;; Data for the next match. If a cons, it has the same format as
2282 ;; (match-data); otherwise it is t if a match is possible at point.
2283 (match-again t)
2285 (message
2286 (if query-flag
2287 (apply 'propertize
2288 (substitute-command-keys
2289 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2290 minibuffer-prompt-properties))))
2292 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
2293 (when region-noncontiguous-p
2294 (setq region-bounds
2295 (mapcar (lambda (position)
2296 (cons (copy-marker (car position))
2297 (copy-marker (cdr position))))
2298 (funcall region-extract-function 'bounds)))
2299 (add-function :after-while isearch-filter-predicate
2300 (lambda (start end)
2301 (delq nil (mapcar
2302 (lambda (bounds)
2303 (and
2304 (>= start (car bounds))
2305 (<= start (cdr bounds))
2306 (>= end (car bounds))
2307 (<= end (cdr bounds))))
2308 region-bounds)))))
2310 ;; If region is active, in Transient Mark mode, operate on region.
2311 (if backward
2312 (when end
2313 (setq limit (copy-marker (min start end)))
2314 (goto-char (max start end))
2315 (deactivate-mark))
2316 (when start
2317 (setq limit (copy-marker (max start end)))
2318 (goto-char (min start end))
2319 (deactivate-mark)))
2321 ;; If last typed key in previous call of multi-buffer perform-replace
2322 ;; was `automatic-all', don't ask more questions in next files
2323 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2324 (setq query-flag nil multi-buffer t))
2326 (cond
2327 ((stringp replacements)
2328 (setq next-replacement replacements
2329 replacements nil))
2330 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2331 (or repeat-count (setq repeat-count 1))
2332 (setq replacements (cons 'replace-loop-through-replacements
2333 (vector repeat-count repeat-count
2334 replacements replacements)))))
2336 (when query-replace-lazy-highlight
2337 (setq isearch-lazy-highlight-last-string nil))
2339 (push-mark)
2340 (undo-boundary)
2341 (unwind-protect
2342 ;; Loop finding occurrences that perhaps should be replaced.
2343 (while (and keep-going
2344 (if backward
2345 (not (or (bobp) (and limit (<= (point) limit))))
2346 (not (or (eobp) (and limit (>= (point) limit)))))
2347 ;; Use the next match if it is already known;
2348 ;; otherwise, search for a match after moving forward
2349 ;; one char if progress is required.
2350 (setq real-match-data
2351 (cond ((consp match-again)
2352 (goto-char (if backward
2353 (nth 0 match-again)
2354 (nth 1 match-again)))
2355 (replace-match-data
2356 t real-match-data match-again))
2357 ;; MATCH-AGAIN non-nil means accept an
2358 ;; adjacent match.
2359 (match-again
2360 (and
2361 (replace-search search-string limit
2362 regexp-flag delimited-flag
2363 case-fold-search backward)
2364 ;; For speed, use only integers and
2365 ;; reuse the list used last time.
2366 (replace-match-data t real-match-data)))
2367 ((and (if backward
2368 (> (1- (point)) (point-min))
2369 (< (1+ (point)) (point-max)))
2370 (or (null limit)
2371 (if backward
2372 (> (1- (point)) limit)
2373 (< (1+ (point)) limit))))
2374 ;; If not accepting adjacent matches,
2375 ;; move one char to the right before
2376 ;; searching again. Undo the motion
2377 ;; if the search fails.
2378 (let ((opoint (point)))
2379 (forward-char (if backward -1 1))
2380 (if (replace-search search-string limit
2381 regexp-flag delimited-flag
2382 case-fold-search backward)
2383 (replace-match-data
2384 t real-match-data)
2385 (goto-char opoint)
2386 nil))))))
2388 ;; Record whether the match is nonempty, to avoid an infinite loop
2389 ;; repeatedly matching the same empty string.
2390 (setq nonempty-match
2391 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2393 ;; If the match is empty, record that the next one can't be
2394 ;; adjacent.
2396 ;; Otherwise, if matching a regular expression, do the next
2397 ;; match now, since the replacement for this match may
2398 ;; affect whether the next match is adjacent to this one.
2399 ;; If that match is empty, don't use it.
2400 (setq match-again
2401 (and nonempty-match
2402 (or (not regexp-flag)
2403 (and (if backward
2404 (looking-back search-string nil)
2405 (looking-at search-string))
2406 (let ((match (match-data)))
2407 (and (/= (nth 0 match) (nth 1 match))
2408 match))))))
2410 (cond
2411 ;; Optionally ignore matches that have a read-only property.
2412 ((not (or (not query-replace-skip-read-only)
2413 (not (text-property-not-all
2414 (nth 0 real-match-data) (nth 1 real-match-data)
2415 'read-only nil))))
2416 (setq skip-read-only-count (1+ skip-read-only-count)))
2417 ;; Optionally filter out matches.
2418 ((not (funcall isearch-filter-predicate
2419 (nth 0 real-match-data) (nth 1 real-match-data)))
2420 (setq skip-filtered-count (1+ skip-filtered-count)))
2421 ;; Optionally ignore invisible matches.
2422 ((not (or (eq search-invisible t)
2423 ;; Don't open overlays for automatic replacements.
2424 (and (not query-flag) search-invisible)
2425 ;; Open hidden overlays for interactive replacements.
2426 (not (isearch-range-invisible
2427 (nth 0 real-match-data) (nth 1 real-match-data)))))
2428 (setq skip-invisible-count (1+ skip-invisible-count)))
2430 ;; Calculate the replacement string, if necessary.
2431 (when replacements
2432 (set-match-data real-match-data)
2433 (setq next-replacement
2434 (funcall (car replacements) (cdr replacements)
2435 replace-count)))
2436 (if (not query-flag)
2437 (progn
2438 (unless (or literal noedit)
2439 (replace-highlight
2440 (nth 0 real-match-data) (nth 1 real-match-data)
2441 start end search-string
2442 regexp-flag delimited-flag case-fold-search backward))
2443 (setq noedit
2444 (replace-match-maybe-edit
2445 next-replacement nocasify literal
2446 noedit real-match-data backward)
2447 replace-count (1+ replace-count)))
2448 (undo-boundary)
2449 (let (done replaced key def)
2450 ;; Loop reading commands until one of them sets done,
2451 ;; which means it has finished handling this
2452 ;; occurrence. Any command that sets `done' should
2453 ;; leave behind proper match data for the stack.
2454 ;; Commands not setting `done' need to adjust
2455 ;; `real-match-data'.
2456 (while (not done)
2457 (set-match-data real-match-data)
2458 (run-hooks 'replace-update-post-hook) ; Before `replace-highlight'.
2459 (replace-highlight
2460 (match-beginning 0) (match-end 0)
2461 start end search-string
2462 regexp-flag delimited-flag case-fold-search backward)
2463 ;; Obtain the matched groups: needed only when
2464 ;; regexp-flag non nil.
2465 (when (and last-was-undo regexp-flag)
2466 (setq last-was-undo nil
2467 real-match-data
2468 (save-excursion
2469 (goto-char (match-beginning 0))
2470 (looking-at search-string)
2471 (match-data t real-match-data))))
2472 ;; Matched string and next-replacement-replaced
2473 ;; stored in stack.
2474 (setq search-string-replaced (buffer-substring-no-properties
2475 (match-beginning 0)
2476 (match-end 0))
2477 next-replacement-replaced
2478 (query-replace-descr
2479 (save-match-data
2480 (set-match-data real-match-data)
2481 (match-substitute-replacement
2482 next-replacement nocasify literal))))
2483 ;; Bind message-log-max so we don't fill up the
2484 ;; message log with a bunch of identical messages.
2485 (let ((message-log-max nil)
2486 (replacement-presentation
2487 (if query-replace-show-replacement
2488 (save-match-data
2489 (set-match-data real-match-data)
2490 (match-substitute-replacement next-replacement
2491 nocasify literal))
2492 next-replacement)))
2493 (message message
2494 (query-replace-descr from-string)
2495 (query-replace-descr replacement-presentation)))
2496 (setq key (read-event))
2497 ;; Necessary in case something happens during
2498 ;; read-event that clobbers the match data.
2499 (set-match-data real-match-data)
2500 (setq key (vector key))
2501 (setq def (lookup-key map key))
2502 ;; Restore the match data while we process the command.
2503 (cond ((eq def 'help)
2504 (with-output-to-temp-buffer "*Help*"
2505 (princ
2506 (concat "Query replacing "
2507 (if delimited-flag
2508 (or (and (symbolp delimited-flag)
2509 (get delimited-flag
2510 'isearch-message-prefix))
2511 "word ") "")
2512 (if regexp-flag "regexp " "")
2513 (if backward "backward " "")
2514 from-string " with "
2515 next-replacement ".\n\n"
2516 (substitute-command-keys
2517 query-replace-help)))
2518 (with-current-buffer standard-output
2519 (help-mode))))
2520 ((eq def 'exit)
2521 (setq keep-going nil)
2522 (setq done t))
2523 ((eq def 'exit-current)
2524 (setq multi-buffer t keep-going nil done t))
2525 ((eq def 'backup)
2526 (if stack
2527 (let ((elt (pop stack)))
2528 (goto-char (nth 0 elt))
2529 (setq replaced (nth 1 elt)
2530 real-match-data
2531 (replace-match-data
2532 t real-match-data
2533 (nth 2 elt))))
2534 (message "No previous match")
2535 (ding 'no-terminate)
2536 (sit-for 1)))
2537 ((or (eq def 'undo) (eq def 'undo-all))
2538 (if (null stack)
2539 (progn
2540 (message "Nothing to undo")
2541 (ding 'no-terminate)
2542 (sit-for 1))
2543 (let ((stack-idx 0)
2544 (stack-len (length stack))
2545 (num-replacements 0)
2546 search-string
2547 next-replacement)
2548 (while (and (< stack-idx stack-len)
2549 stack
2550 (null replaced))
2551 (let* ((elt (nth stack-idx stack)))
2552 (setq
2553 stack-idx (1+ stack-idx)
2554 replaced (nth 1 elt)
2555 ;; Bind swapped values
2556 ;; (search-string <--> replacement)
2557 search-string (nth (if replaced 4 3) elt)
2558 next-replacement (nth (if replaced 3 4) elt)
2559 search-string-replaced search-string
2560 next-replacement-replaced next-replacement)
2562 (when (and (= stack-idx stack-len)
2563 (null replaced)
2564 (zerop num-replacements))
2565 (message "Nothing to undo")
2566 (ding 'no-terminate)
2567 (sit-for 1))
2569 (when replaced
2570 (setq stack (nthcdr stack-idx stack))
2571 (goto-char (nth 0 elt))
2572 (set-match-data (nth 2 elt))
2573 (setq real-match-data
2574 (save-excursion
2575 (goto-char (match-beginning 0))
2576 (looking-at search-string)
2577 (match-data t (nth 2 elt)))
2578 noedit
2579 (replace-match-maybe-edit
2580 next-replacement nocasify literal
2581 noedit real-match-data backward)
2582 replace-count (1- replace-count)
2583 real-match-data
2584 (save-excursion
2585 (goto-char (match-beginning 0))
2586 (looking-at next-replacement)
2587 (match-data t (nth 2 elt))))
2588 ;; Set replaced nil to keep in loop
2589 (when (eq def 'undo-all)
2590 (setq replaced nil
2591 stack-len (- stack-len stack-idx)
2592 stack-idx 0
2593 num-replacements
2594 (1+ num-replacements))))))
2595 (when (and (eq def 'undo-all)
2596 (null (zerop num-replacements)))
2597 (message "Undid %d %s" num-replacements
2598 (if (= num-replacements 1)
2599 "replacement"
2600 "replacements"))
2601 (ding 'no-terminate)
2602 (sit-for 1)))
2603 (setq replaced nil last-was-undo t)))
2604 ((eq def 'act)
2605 (or replaced
2606 (setq noedit
2607 (replace-match-maybe-edit
2608 next-replacement nocasify literal
2609 noedit real-match-data backward)
2610 replace-count (1+ replace-count)))
2611 (setq done t replaced t))
2612 ((eq def 'act-and-exit)
2613 (or replaced
2614 (setq noedit
2615 (replace-match-maybe-edit
2616 next-replacement nocasify literal
2617 noedit real-match-data backward)
2618 replace-count (1+ replace-count)))
2619 (setq keep-going nil)
2620 (setq done t replaced t))
2621 ((eq def 'act-and-show)
2622 (if (not replaced)
2623 (setq noedit
2624 (replace-match-maybe-edit
2625 next-replacement nocasify literal
2626 noedit real-match-data backward)
2627 replace-count (1+ replace-count)
2628 real-match-data (replace-match-data
2629 t real-match-data)
2630 replaced t)))
2631 ((or (eq def 'automatic) (eq def 'automatic-all))
2632 (or replaced
2633 (setq noedit
2634 (replace-match-maybe-edit
2635 next-replacement nocasify literal
2636 noedit real-match-data backward)
2637 replace-count (1+ replace-count)))
2638 (setq done t query-flag nil replaced t)
2639 (if (eq def 'automatic-all) (setq multi-buffer t)))
2640 ((eq def 'skip)
2641 (setq done t))
2642 ((eq def 'recenter)
2643 ;; `this-command' has the value `query-replace',
2644 ;; so we need to bind it to `recenter-top-bottom'
2645 ;; to allow it to detect a sequence of `C-l'.
2646 (let ((this-command 'recenter-top-bottom)
2647 (last-command 'recenter-top-bottom))
2648 (recenter-top-bottom)))
2649 ((eq def 'edit)
2650 (let ((opos (point-marker)))
2651 (setq real-match-data (replace-match-data
2652 nil real-match-data
2653 real-match-data))
2654 (goto-char (match-beginning 0))
2655 (save-excursion
2656 (save-window-excursion
2657 (recursive-edit)))
2658 (goto-char opos)
2659 (set-marker opos nil))
2660 ;; Before we make the replacement,
2661 ;; decide whether the search string
2662 ;; can match again just after this match.
2663 (if (and regexp-flag nonempty-match)
2664 (setq match-again (and (looking-at search-string)
2665 (match-data)))))
2666 ;; Edit replacement.
2667 ((eq def 'edit-replacement)
2668 (setq real-match-data (replace-match-data
2669 nil real-match-data
2670 real-match-data)
2671 next-replacement
2672 (read-string "Edit replacement string: "
2673 next-replacement)
2674 noedit nil)
2675 (if replaced
2676 (set-match-data real-match-data)
2677 (setq noedit
2678 (replace-match-maybe-edit
2679 next-replacement nocasify literal noedit
2680 real-match-data backward)
2681 replaced t))
2682 (setq done t))
2684 ((eq def 'delete-and-edit)
2685 (replace-match "" t t)
2686 (setq real-match-data (replace-match-data
2687 nil real-match-data))
2688 (replace-dehighlight)
2689 (save-excursion (recursive-edit))
2690 (setq replaced t))
2691 ;; Note: we do not need to treat `exit-prefix'
2692 ;; specially here, since we reread
2693 ;; any unrecognized character.
2695 (setq this-command 'mode-exited)
2696 (setq keep-going nil)
2697 (setq unread-command-events
2698 (append (listify-key-sequence key)
2699 unread-command-events))
2700 (setq done t)))
2701 (when query-replace-lazy-highlight
2702 ;; Force lazy rehighlighting only after replacements.
2703 (if (not (memq def '(skip backup)))
2704 (setq isearch-lazy-highlight-last-string nil)))
2705 (unless (eq def 'recenter)
2706 ;; Reset recenter cycling order to initial position.
2707 (setq recenter-last-op nil)))
2708 ;; Record previous position for ^ when we move on.
2709 ;; Change markers to numbers in the match data
2710 ;; since lots of markers slow down editing.
2711 (push (list (point) replaced
2712 ;;; If the replacement has already happened, all we need is the
2713 ;;; current match start and end. We could get this with a trivial
2714 ;;; match like
2715 ;;; (save-excursion (goto-char (match-beginning 0))
2716 ;;; (search-forward (match-string 0))
2717 ;;; (match-data t))
2718 ;;; if we really wanted to avoid manually constructing match data.
2719 ;;; Adding current-buffer is necessary so that match-data calls can
2720 ;;; return markers which are appropriate for editing.
2721 (if replaced
2722 (list
2723 (match-beginning 0)
2724 (match-end 0)
2725 (current-buffer))
2726 (match-data t))
2727 search-string-replaced
2728 next-replacement-replaced)
2729 stack)
2730 (setq next-replacement-replaced nil
2731 search-string-replaced nil))))))
2732 (replace-dehighlight))
2733 (or unread-command-events
2734 (message "Replaced %d occurrence%s%s"
2735 replace-count
2736 (if (= replace-count 1) "" "s")
2737 (if (> (+ skip-read-only-count
2738 skip-filtered-count
2739 skip-invisible-count) 0)
2740 (format " (skipped %s)"
2741 (mapconcat
2742 'identity
2743 (delq nil (list
2744 (if (> skip-read-only-count 0)
2745 (format "%s read-only"
2746 skip-read-only-count))
2747 (if (> skip-invisible-count 0)
2748 (format "%s invisible"
2749 skip-invisible-count))
2750 (if (> skip-filtered-count 0)
2751 (format "%s filtered out"
2752 skip-filtered-count))))
2753 ", "))
2754 "")))
2755 (or (and keep-going stack) multi-buffer)))
2757 (provide 'replace)
2759 ;;; replace.el ends here