Fix imenu--sort-by-position for non-pairs parameters (bug#26457)
[emacs.git] / lisp / replace.el
bloba7b8ae6a347f4c2b29abb5a45520956230a43435
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, `\\&' or `\\0' stands for whatever matched the whole of
409 REGEXP, 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 `\\&' or
468 `\\0' 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, `\\&' or `\\0' stands for whatever matched the whole of
656 REGEXP, and `\\=\\N' (where N is a digit) stands for
657 whatever matched 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.
668 If your Lisp expression is an identifier and the next letter in
669 the replacement string would be interpreted as part of it, you
670 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
671 for this particular case you may also enter `\\#' in the
672 replacement text directly.
674 When using those Lisp features interactively in the replacement
675 text, TO-STRING is actually made a list instead of a string.
676 Use \\[repeat-complex-command] after this command for details.
678 Use \\<minibuffer-local-map>\\[next-history-element] \
679 to pull the last incremental search regexp to the minibuffer
680 that reads REGEXP.
682 This function is usually the wrong thing to use in a Lisp program.
683 What you probably want is a loop like this:
684 (while (re-search-forward REGEXP nil t)
685 (replace-match TO-STRING nil nil))
686 which will run faster and will not set the mark or print anything."
687 (declare (interactive-only
688 "use `re-search-forward' and `replace-match' instead."))
689 (interactive
690 (let ((common
691 (query-replace-read-args
692 (concat "Replace"
693 (if current-prefix-arg
694 (if (eq current-prefix-arg '-) " backward" " word")
696 " regexp"
697 (if (use-region-p) " in region" ""))
698 t)))
699 (list (nth 0 common) (nth 1 common) (nth 2 common)
700 (if (use-region-p) (region-beginning))
701 (if (use-region-p) (region-end))
702 (nth 3 common))))
703 (perform-replace regexp to-string nil t delimited nil nil start end backward))
706 (defvar regexp-history nil
707 "History list for some commands that read regular expressions.
709 Maximum length of the history list is determined by the value
710 of `history-length', which see.")
712 (defvar occur-collect-regexp-history '("\\1")
713 "History of regexp for occur's collect operation")
715 (defcustom read-regexp-defaults-function nil
716 "Function that provides default regexp(s) for `read-regexp'.
717 This function should take no arguments and return one of: nil, a
718 regexp, or a list of regexps. Interactively, `read-regexp' uses
719 the return value of this function for its DEFAULT argument.
721 As an example, set this variable to `find-tag-default-as-regexp'
722 to default to the symbol at point.
724 To provide different default regexps for different commands,
725 the function that you set this to can check `this-command'."
726 :type '(choice
727 (const :tag "No default regexp reading function" nil)
728 (const :tag "Latest regexp history" regexp-history-last)
729 (function-item :tag "Tag at point"
730 find-tag-default)
731 (function-item :tag "Tag at point as regexp"
732 find-tag-default-as-regexp)
733 (function-item :tag "Tag at point as symbol regexp"
734 find-tag-default-as-symbol-regexp)
735 (function :tag "Your choice of function"))
736 :group 'matching
737 :version "24.4")
739 (defun read-regexp-suggestions ()
740 "Return a list of standard suggestions for `read-regexp'.
741 By default, the list includes the tag at point, the last isearch regexp,
742 the last isearch string, and the last replacement regexp. `read-regexp'
743 appends the list returned by this function to the end of values available
744 via \\<minibuffer-local-map>\\[next-history-element]."
745 (list
746 (find-tag-default-as-regexp)
747 (find-tag-default-as-symbol-regexp)
748 (car regexp-search-ring)
749 (regexp-quote (or (car search-ring) ""))
750 (car (symbol-value query-replace-from-history-variable))))
752 (defun read-regexp (prompt &optional defaults history)
753 "Read and return a regular expression as a string.
754 Prompt with the string PROMPT. If PROMPT ends in \":\" (followed by
755 optional whitespace), use it as-is. Otherwise, add \": \" to the end,
756 possibly preceded by the default result (see below).
758 The optional argument DEFAULTS can be either: nil, a string, a list
759 of strings, or a symbol. We use DEFAULTS to construct the default
760 return value in case of empty input.
762 If DEFAULTS is a string, we use it as-is.
764 If DEFAULTS is a list of strings, the first element is the
765 default return value, but all the elements are accessible
766 using the history command \\<minibuffer-local-map>\\[next-history-element].
768 If DEFAULTS is a non-nil symbol, then if `read-regexp-defaults-function'
769 is non-nil, we use that in place of DEFAULTS in the following:
770 If DEFAULTS is the symbol `regexp-history-last', we use the first
771 element of HISTORY (if specified) or `regexp-history'.
772 If DEFAULTS is a function, we call it with no arguments and use
773 what it returns, which should be either nil, a string, or a list of strings.
775 We append the standard values from `read-regexp-suggestions' to DEFAULTS
776 before using it.
778 If the first element of DEFAULTS is non-nil (and if PROMPT does not end
779 in \":\", followed by optional whitespace), we add it to the prompt.
781 The optional argument HISTORY is a symbol to use for the history list.
782 If nil, uses `regexp-history'."
783 (let* ((defaults
784 (if (and defaults (symbolp defaults))
785 (cond
786 ((eq (or read-regexp-defaults-function defaults)
787 'regexp-history-last)
788 (car (symbol-value (or history 'regexp-history))))
789 ((functionp (or read-regexp-defaults-function defaults))
790 (funcall (or read-regexp-defaults-function defaults))))
791 defaults))
792 (default (if (consp defaults) (car defaults) defaults))
793 (suggestions (if (listp defaults) defaults (list defaults)))
794 (suggestions (append suggestions (read-regexp-suggestions)))
795 (suggestions (delete-dups (delq nil (delete "" suggestions))))
796 ;; Do not automatically add default to the history for empty input.
797 (history-add-new-input nil)
798 (input (read-from-minibuffer
799 (cond ((string-match-p ":[ \t]*\\'" prompt)
800 prompt)
801 ((and default (> (length default) 0))
802 (format "%s (default %s): " prompt
803 (query-replace-descr default)))
805 (format "%s: " prompt)))
806 nil nil nil (or history 'regexp-history) suggestions t)))
807 (if (equal input "")
808 ;; Return the default value when the user enters empty input.
809 (prog1 (or default input)
810 (when default
811 (add-to-history (or history 'regexp-history) default)))
812 ;; Otherwise, add non-empty input to the history and return input.
813 (prog1 input
814 (add-to-history (or history 'regexp-history) input)))))
817 (defalias 'delete-non-matching-lines 'keep-lines)
818 (defalias 'delete-matching-lines 'flush-lines)
819 (defalias 'count-matches 'how-many)
822 (defun keep-lines-read-args (prompt)
823 "Read arguments for `keep-lines' and friends.
824 Prompt for a regexp with PROMPT.
825 Value is a list, (REGEXP)."
826 (list (read-regexp prompt) nil nil t))
828 (defun keep-lines (regexp &optional rstart rend interactive)
829 "Delete all lines except those containing matches for REGEXP.
830 A match split across lines preserves all the lines it lies in.
831 When called from Lisp (and usually interactively as well, see below)
832 applies to all lines starting after point.
834 If REGEXP contains upper case characters (excluding those preceded by `\\')
835 and `search-upper-case' is non-nil, the matching is case-sensitive.
837 Second and third arg RSTART and REND specify the region to operate on.
838 This command operates on (the accessible part of) all lines whose
839 accessible part is entirely contained in the region determined by RSTART
840 and REND. (A newline ending a line counts as part of that line.)
842 Interactively, in Transient Mark mode when the mark is active, operate
843 on all lines whose accessible part is entirely contained in the region.
844 Otherwise, the command applies to all lines starting after point.
845 When calling this function from Lisp, you can pretend that it was
846 called interactively by passing a non-nil INTERACTIVE argument.
848 This function starts looking for the next match from the end of
849 the previous match. Hence, it ignores matches that overlap
850 a previously found match."
851 (interactive
852 (progn
853 (barf-if-buffer-read-only)
854 (keep-lines-read-args "Keep lines containing match for regexp")))
855 (if rstart
856 (progn
857 (goto-char (min rstart rend))
858 (setq rend
859 (progn
860 (save-excursion
861 (goto-char (max rstart rend))
862 (unless (or (bolp) (eobp))
863 (forward-line 0))
864 (point-marker)))))
865 (if (and interactive (use-region-p))
866 (setq rstart (region-beginning)
867 rend (progn
868 (goto-char (region-end))
869 (unless (or (bolp) (eobp))
870 (forward-line 0))
871 (point-marker)))
872 (setq rstart (point)
873 rend (point-max-marker)))
874 (goto-char rstart))
875 (save-excursion
876 (or (bolp) (forward-line 1))
877 (let ((start (point))
878 (case-fold-search
879 (if (and case-fold-search search-upper-case)
880 (isearch-no-upper-case-p regexp t)
881 case-fold-search)))
882 (while (< (point) rend)
883 ;; Start is first char not preserved by previous match.
884 (if (not (re-search-forward regexp rend 'move))
885 (delete-region start rend)
886 (let ((end (save-excursion (goto-char (match-beginning 0))
887 (forward-line 0)
888 (point))))
889 ;; Now end is first char preserved by the new match.
890 (if (< start end)
891 (delete-region start end))))
893 (setq start (save-excursion (forward-line 1) (point)))
894 ;; If the match was empty, avoid matching again at same place.
895 (and (< (point) rend)
896 (= (match-beginning 0) (match-end 0))
897 (forward-char 1)))))
898 (set-marker rend nil)
899 nil)
902 (defun flush-lines (regexp &optional rstart rend interactive)
903 "Delete lines containing matches for REGEXP.
904 When called from Lisp (and usually when called interactively as
905 well, see below), applies to the part of the buffer after point.
906 The line point is in is deleted if and only if it contains a
907 match for regexp starting after point.
909 If REGEXP contains upper case characters (excluding those preceded by `\\')
910 and `search-upper-case' is non-nil, the matching is case-sensitive.
912 Second and third arg RSTART and REND specify the region to operate on.
913 Lines partially contained in this region are deleted if and only if
914 they contain a match entirely contained in it.
916 Interactively, in Transient Mark mode when the mark is active, operate
917 on the contents of the region. Otherwise, operate from point to the
918 end of (the accessible portion of) the buffer. When calling this function
919 from Lisp, you can pretend that it was called interactively by passing
920 a non-nil INTERACTIVE argument.
922 If a match is split across lines, all the lines it lies in are deleted.
923 They are deleted _before_ looking for the next match. Hence, a match
924 starting on the same line at which another match ended is ignored."
925 (interactive
926 (progn
927 (barf-if-buffer-read-only)
928 (keep-lines-read-args "Flush lines containing match for regexp")))
929 (if rstart
930 (progn
931 (goto-char (min rstart rend))
932 (setq rend (copy-marker (max rstart rend))))
933 (if (and interactive (use-region-p))
934 (setq rstart (region-beginning)
935 rend (copy-marker (region-end)))
936 (setq rstart (point)
937 rend (point-max-marker)))
938 (goto-char rstart))
939 (let ((case-fold-search
940 (if (and case-fold-search search-upper-case)
941 (isearch-no-upper-case-p regexp t)
942 case-fold-search)))
943 (save-excursion
944 (while (and (< (point) rend)
945 (re-search-forward regexp rend t))
946 (delete-region (save-excursion (goto-char (match-beginning 0))
947 (forward-line 0)
948 (point))
949 (progn (forward-line 1) (point))))))
950 (set-marker rend nil)
951 nil)
954 (defun how-many (regexp &optional rstart rend interactive)
955 "Print and return number of matches for REGEXP following point.
956 When called from Lisp and INTERACTIVE is omitted or nil, just return
957 the number, do not print it; if INTERACTIVE is t, the function behaves
958 in all respects as if it had been called interactively.
960 If REGEXP contains upper case characters (excluding those preceded by `\\')
961 and `search-upper-case' is non-nil, the matching is case-sensitive.
963 Second and third arg RSTART and REND specify the region to operate on.
965 Interactively, in Transient Mark mode when the mark is active, operate
966 on the contents of the region. Otherwise, operate from point to the
967 end of (the accessible portion of) the buffer.
969 This function starts looking for the next match from the end of
970 the previous match. Hence, it ignores matches that overlap
971 a previously found match."
972 (interactive
973 (keep-lines-read-args "How many matches for regexp"))
974 (save-excursion
975 (if rstart
976 (if rend
977 (progn
978 (goto-char (min rstart rend))
979 (setq rend (max rstart rend)))
980 (goto-char rstart)
981 (setq rend (point-max)))
982 (if (and interactive (use-region-p))
983 (setq rstart (region-beginning)
984 rend (region-end))
985 (setq rstart (point)
986 rend (point-max)))
987 (goto-char rstart))
988 (let ((count 0)
989 opoint
990 (case-fold-search
991 (if (and case-fold-search search-upper-case)
992 (isearch-no-upper-case-p regexp t)
993 case-fold-search)))
994 (while (and (< (point) rend)
995 (progn (setq opoint (point))
996 (re-search-forward regexp rend t)))
997 (if (= opoint (point))
998 (forward-char 1)
999 (setq count (1+ count))))
1000 (when interactive (message "%d occurrence%s"
1001 count
1002 (if (= count 1) "" "s")))
1003 count)))
1006 (defvar occur-menu-map
1007 (let ((map (make-sparse-keymap)))
1008 (bindings--define-key map [next-error-follow-minor-mode]
1009 '(menu-item "Auto Occurrence Display"
1010 next-error-follow-minor-mode
1011 :help "Display another occurrence when moving the cursor"
1012 :button (:toggle . (and (boundp 'next-error-follow-minor-mode)
1013 next-error-follow-minor-mode))))
1014 (bindings--define-key map [separator-1] menu-bar-separator)
1015 (bindings--define-key map [kill-this-buffer]
1016 '(menu-item "Kill Occur Buffer" kill-this-buffer
1017 :help "Kill the current *Occur* buffer"))
1018 (bindings--define-key map [quit-window]
1019 '(menu-item "Quit Occur Window" quit-window
1020 :help "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
1021 (bindings--define-key map [revert-buffer]
1022 '(menu-item "Revert Occur Buffer" revert-buffer
1023 :help "Replace the text in the *Occur* buffer with the results of rerunning occur"))
1024 (bindings--define-key map [clone-buffer]
1025 '(menu-item "Clone Occur Buffer" clone-buffer
1026 :help "Create and return a twin copy of the current *Occur* buffer"))
1027 (bindings--define-key map [occur-rename-buffer]
1028 '(menu-item "Rename Occur Buffer" occur-rename-buffer
1029 :help "Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
1030 (bindings--define-key map [occur-edit-buffer]
1031 '(menu-item "Edit Occur Buffer" occur-edit-mode
1032 :help "Edit the *Occur* buffer and apply changes to the original buffers."))
1033 (bindings--define-key map [separator-2] menu-bar-separator)
1034 (bindings--define-key map [occur-mode-goto-occurrence-other-window]
1035 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
1036 :help "Go to the occurrence the current line describes, in another window"))
1037 (bindings--define-key map [occur-mode-goto-occurrence]
1038 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
1039 :help "Go to the occurrence the current line describes"))
1040 (bindings--define-key map [occur-mode-display-occurrence]
1041 '(menu-item "Display Occurrence" occur-mode-display-occurrence
1042 :help "Display in another window the occurrence the current line describes"))
1043 (bindings--define-key map [occur-next]
1044 '(menu-item "Move to Next Match" occur-next
1045 :help "Move to the Nth (default 1) next match in an Occur mode buffer"))
1046 (bindings--define-key map [occur-prev]
1047 '(menu-item "Move to Previous Match" occur-prev
1048 :help "Move to the Nth (default 1) previous match in an Occur mode buffer"))
1049 map)
1050 "Menu keymap for `occur-mode'.")
1052 (defvar occur-mode-map
1053 (let ((map (make-sparse-keymap)))
1054 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
1055 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1056 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
1057 (define-key map "e" 'occur-edit-mode)
1058 (define-key map "\C-m" 'occur-mode-goto-occurrence)
1059 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
1060 (define-key map "\C-o" 'occur-mode-display-occurrence)
1061 (define-key map "\M-n" 'occur-next)
1062 (define-key map "\M-p" 'occur-prev)
1063 (define-key map "r" 'occur-rename-buffer)
1064 (define-key map "c" 'clone-buffer)
1065 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1066 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1067 map)
1068 "Keymap for `occur-mode'.")
1070 (defvar occur-revert-arguments nil
1071 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
1072 See `occur-revert-function'.")
1073 (make-variable-buffer-local 'occur-revert-arguments)
1074 (put 'occur-revert-arguments 'permanent-local t)
1076 (defcustom occur-mode-hook '(turn-on-font-lock)
1077 "Hook run when entering Occur mode."
1078 :type 'hook
1079 :group 'matching)
1081 (defcustom occur-hook nil
1082 "Hook run by Occur when there are any matches."
1083 :type 'hook
1084 :group 'matching)
1086 (defcustom occur-mode-find-occurrence-hook nil
1087 "Hook run by Occur after locating an occurrence.
1088 This will be called with the cursor position at the occurrence. An application
1089 for this is to reveal context in an outline-mode when the occurrence is hidden."
1090 :type 'hook
1091 :group 'matching)
1093 (put 'occur-mode 'mode-class 'special)
1094 (define-derived-mode occur-mode special-mode "Occur"
1095 "Major mode for output from \\[occur].
1096 \\<occur-mode-map>Move point to one of the items in this buffer, then use
1097 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
1098 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
1100 \\{occur-mode-map}"
1101 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
1102 (setq next-error-function 'occur-next-error))
1105 ;;; Occur Edit mode
1107 (defvar occur-edit-mode-map
1108 (let ((map (make-sparse-keymap)))
1109 (set-keymap-parent map text-mode-map)
1110 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1111 (define-key map "\C-c\C-c" 'occur-cease-edit)
1112 (define-key map "\C-o" 'occur-mode-display-occurrence)
1113 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1114 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1115 map)
1116 "Keymap for `occur-edit-mode'.")
1118 (define-derived-mode occur-edit-mode occur-mode "Occur-Edit"
1119 "Major mode for editing *Occur* buffers.
1120 In this mode, changes to the *Occur* buffer are also applied to
1121 the originating buffer.
1123 To return to ordinary Occur mode, use \\[occur-cease-edit]."
1124 (setq buffer-read-only nil)
1125 (add-hook 'after-change-functions 'occur-after-change-function nil t)
1126 (message (substitute-command-keys
1127 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
1129 (defun occur-cease-edit ()
1130 "Switch from Occur Edit mode to Occur mode."
1131 (interactive)
1132 (when (derived-mode-p 'occur-edit-mode)
1133 (occur-mode)
1134 (message "Switching to Occur mode.")))
1136 (defun occur-after-change-function (beg end length)
1137 (save-excursion
1138 (goto-char beg)
1139 (let* ((line-beg (line-beginning-position))
1140 (m (get-text-property line-beg 'occur-target))
1141 (buf (marker-buffer m))
1142 col)
1143 (when (and (get-text-property line-beg 'occur-prefix)
1144 (not (get-text-property end 'occur-prefix)))
1145 (when (= length 0)
1146 ;; Apply occur-target property to inserted (e.g. yanked) text.
1147 (put-text-property beg end 'occur-target m)
1148 ;; Did we insert a newline? Occur Edit mode can't create new
1149 ;; Occur entries; just discard everything after the newline.
1150 (save-excursion
1151 (and (search-forward "\n" end t)
1152 (delete-region (1- (point)) end))))
1153 (let* ((line (- (line-number-at-pos)
1154 (line-number-at-pos (window-start))))
1155 (readonly (with-current-buffer buf buffer-read-only))
1156 (win (or (get-buffer-window buf)
1157 (display-buffer buf
1158 '(nil (inhibit-same-window . t)
1159 (inhibit-switch-frame . t)))))
1160 (line-end (line-end-position))
1161 (text (save-excursion
1162 (goto-char (next-single-property-change
1163 line-beg 'occur-prefix nil
1164 line-end))
1165 (setq col (- (point) line-beg))
1166 (buffer-substring-no-properties (point) line-end))))
1167 (with-selected-window win
1168 (goto-char m)
1169 (recenter line)
1170 (if readonly
1171 (message "Buffer `%s' is read only." buf)
1172 (delete-region (line-beginning-position) (line-end-position))
1173 (insert text))
1174 (move-to-column col)))))))
1177 (defun occur-revert-function (_ignore1 _ignore2)
1178 "Handle `revert-buffer' for Occur mode buffers."
1179 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
1181 (defun occur-mode-find-occurrence ()
1182 (let ((pos (get-text-property (point) 'occur-target)))
1183 (unless pos
1184 (error "No occurrence on this line"))
1185 (unless (buffer-live-p (marker-buffer pos))
1186 (error "Buffer for this occurrence was killed"))
1187 pos))
1189 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
1190 (defun occur-mode-goto-occurrence (&optional event)
1191 "Go to the occurrence on the current line."
1192 (interactive (list last-nonmenu-event))
1193 (let ((pos
1194 (if (null event)
1195 ;; Actually `event-end' works correctly with a nil argument as
1196 ;; well, so we could dispense with this test, but let's not
1197 ;; rely on this undocumented behavior.
1198 (occur-mode-find-occurrence)
1199 (with-current-buffer (window-buffer (posn-window (event-end event)))
1200 (save-excursion
1201 (goto-char (posn-point (event-end event)))
1202 (occur-mode-find-occurrence))))))
1203 (pop-to-buffer (marker-buffer pos))
1204 (goto-char pos)
1205 (run-hooks 'occur-mode-find-occurrence-hook)))
1207 (defun occur-mode-goto-occurrence-other-window ()
1208 "Go to the occurrence the current line describes, in another window."
1209 (interactive)
1210 (let ((pos (occur-mode-find-occurrence)))
1211 (switch-to-buffer-other-window (marker-buffer pos))
1212 (goto-char pos)
1213 (run-hooks 'occur-mode-find-occurrence-hook)))
1215 (defun occur-mode-display-occurrence ()
1216 "Display in another window the occurrence the current line describes."
1217 (interactive)
1218 (let ((pos (occur-mode-find-occurrence))
1219 window)
1220 (setq window (display-buffer (marker-buffer pos) t))
1221 ;; This is the way to set point in the proper window.
1222 (save-selected-window
1223 (select-window window)
1224 (goto-char pos)
1225 (run-hooks 'occur-mode-find-occurrence-hook))))
1227 (defun occur-find-match (n search message)
1228 (if (not n) (setq n 1))
1229 (let ((r))
1230 (while (> n 0)
1231 (setq r (funcall search (point) 'occur-match))
1232 (and r
1233 (get-text-property r 'occur-match)
1234 (setq r (funcall search r 'occur-match)))
1235 (if r
1236 (goto-char r)
1237 (error message))
1238 (setq n (1- n)))))
1240 (defun occur-next (&optional n)
1241 "Move to the Nth (default 1) next match in an Occur mode buffer."
1242 (interactive "p")
1243 (occur-find-match n #'next-single-property-change "No more matches"))
1245 (defun occur-prev (&optional n)
1246 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1247 (interactive "p")
1248 (occur-find-match n #'previous-single-property-change "No earlier matches"))
1250 (defun occur-next-error (&optional argp reset)
1251 "Move to the Nth (default 1) next match in an Occur mode buffer.
1252 Compatibility function for \\[next-error] invocations."
1253 (interactive "p")
1254 ;; we need to run occur-find-match from within the Occur buffer
1255 (with-current-buffer
1256 ;; Choose the buffer and make it current.
1257 (if (next-error-buffer-p (current-buffer))
1258 (current-buffer)
1259 (next-error-find-buffer nil nil
1260 (lambda ()
1261 (eq major-mode 'occur-mode))))
1263 (goto-char (cond (reset (point-min))
1264 ((< argp 0) (line-beginning-position))
1265 ((> argp 0) (line-end-position))
1266 ((point))))
1267 (occur-find-match
1268 (abs argp)
1269 (if (> 0 argp)
1270 #'previous-single-property-change
1271 #'next-single-property-change)
1272 "No more matches")
1273 ;; In case the *Occur* buffer is visible in a nonselected window.
1274 (let ((win (get-buffer-window (current-buffer) t)))
1275 (if win (set-window-point win (point))))
1276 (occur-mode-goto-occurrence)))
1278 (defface match
1279 '((((class color) (min-colors 88) (background light))
1280 :background "yellow1")
1281 (((class color) (min-colors 88) (background dark))
1282 :background "RoyalBlue3")
1283 (((class color) (min-colors 8) (background light))
1284 :background "yellow" :foreground "black")
1285 (((class color) (min-colors 8) (background dark))
1286 :background "blue" :foreground "white")
1287 (((type tty) (class mono))
1288 :inverse-video t)
1289 (t :background "gray"))
1290 "Face used to highlight matches permanently."
1291 :group 'matching
1292 :group 'basic-faces
1293 :version "22.1")
1295 (defcustom list-matching-lines-default-context-lines 0
1296 "Default number of context lines included around `list-matching-lines' matches.
1297 A negative number means to include that many lines before the match.
1298 A positive number means to include that many lines both before and after."
1299 :type 'integer
1300 :group 'matching)
1302 (defalias 'list-matching-lines 'occur)
1304 (defcustom list-matching-lines-face 'match
1305 "Face used by \\[list-matching-lines] to show the text that matches.
1306 If the value is nil, don't highlight the matching portions specially."
1307 :type 'face
1308 :group 'matching)
1310 (defcustom list-matching-lines-buffer-name-face 'underline
1311 "Face used by \\[list-matching-lines] to show the names of buffers.
1312 If the value is nil, don't highlight the buffer names specially."
1313 :type 'face
1314 :group 'matching)
1316 (defcustom list-matching-lines-current-line-face 'lazy-highlight
1317 "Face used by \\[list-matching-lines] to highlight the current line."
1318 :type 'face
1319 :group 'matching
1320 :version "26.1")
1322 (defcustom list-matching-lines-jump-to-current-line nil
1323 "If non-nil, \\[list-matching-lines] shows the current line highlighted.
1324 Set the point right after such line when there are matches after it."
1325 :type 'boolean
1326 :group 'matching
1327 :version "26.1")
1329 (defcustom list-matching-lines-prefix-face 'shadow
1330 "Face used by \\[list-matching-lines] to show the prefix column.
1331 If the face doesn't differ from the default face,
1332 don't highlight the prefix with line numbers specially."
1333 :type 'face
1334 :group 'matching
1335 :version "24.4")
1337 (defcustom occur-excluded-properties
1338 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1339 yank-handler follow-link)
1340 "Text properties to discard when copying lines to the *Occur* buffer.
1341 The value should be a list of text properties to discard or t,
1342 which means to discard all text properties."
1343 :type '(choice (const :tag "All" t) (repeat symbol))
1344 :group 'matching
1345 :version "22.1")
1347 (defun occur-read-primary-args ()
1348 (let* ((perform-collect (consp current-prefix-arg))
1349 (regexp (read-regexp (if perform-collect
1350 "Collect strings matching regexp"
1351 "List lines matching regexp")
1352 'regexp-history-last)))
1353 (list regexp
1354 (if perform-collect
1355 ;; Perform collect operation
1356 (if (zerop (regexp-opt-depth regexp))
1357 ;; No subexpression so collect the entire match.
1358 "\\&"
1359 ;; Get the regexp for collection pattern.
1360 (let ((default (car occur-collect-regexp-history)))
1361 (read-regexp
1362 (format "Regexp to collect (default %s): " default)
1363 default 'occur-collect-regexp-history)))
1364 ;; Otherwise normal occur takes numerical prefix argument.
1365 (when current-prefix-arg
1366 (prefix-numeric-value current-prefix-arg))))))
1368 (defun occur-rename-buffer (&optional unique-p interactive-p)
1369 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1370 Here `original-buffer-name' is the buffer name where Occur was originally run.
1371 When given the prefix argument, or called non-interactively, the renaming
1372 will not clobber the existing buffer(s) of that name, but use
1373 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1374 if you always want a separate *Occur* buffer for each buffer where you
1375 invoke `occur'."
1376 (interactive "P\np")
1377 (with-current-buffer
1378 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1379 (rename-buffer (concat "*Occur: "
1380 (mapconcat #'buffer-name
1381 (car (cddr occur-revert-arguments)) "/")
1382 "*")
1383 (or unique-p (not interactive-p)))))
1385 ;; Region limits when `occur' applies on a region.
1386 (defvar occur--region-start nil)
1387 (defvar occur--region-end nil)
1388 (defvar occur--matches-threshold nil)
1389 (defvar occur--orig-line nil)
1390 (defvar occur--orig-line-str nil)
1391 (defvar occur--final-pos nil)
1393 (defun occur (regexp &optional nlines region)
1394 "Show all lines in the current buffer containing a match for REGEXP.
1395 If a match spreads across multiple lines, all those lines are shown.
1397 Each line is displayed with NLINES lines before and after, or -NLINES
1398 before if NLINES is negative.
1399 NLINES defaults to `list-matching-lines-default-context-lines'.
1400 Interactively it is the prefix arg.
1402 Optional arg REGION, if non-nil, mean restrict search to the
1403 specified region. Otherwise search the entire buffer.
1404 REGION must be a list of (START . END) positions as returned by
1405 `region-bounds'.
1407 The lines are shown in a buffer named `*Occur*'.
1408 It serves as a menu to find any of the occurrences in this buffer.
1409 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1410 If `list-matching-lines-jump-to-current-line' is non-nil, then show
1411 the current line highlighted with `list-matching-lines-current-line-face'
1412 and set point at the first match after such line.
1414 If REGEXP contains upper case characters (excluding those preceded by `\\')
1415 and `search-upper-case' is non-nil, the matching is case-sensitive.
1417 When NLINES is a string or when the function is called
1418 interactively with prefix argument without a number (`C-u' alone
1419 as prefix) the matching strings are collected into the `*Occur*'
1420 buffer by using NLINES as a replacement regexp. NLINES may
1421 contain \\& and \\N which convention follows `replace-match'.
1422 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1423 \"\\1\" for NLINES collects all the function names in a lisp
1424 program. When there is no parenthesized subexpressions in REGEXP
1425 the entire match is collected. In any case the searched buffer
1426 is not modified."
1427 (interactive
1428 (nconc (occur-read-primary-args)
1429 (and (use-region-p) (list (region-bounds)))))
1430 (let* ((start (and (caar region) (max (caar region) (point-min))))
1431 (end (and (cdar region) (min (cdar region) (point-max))))
1432 (in-region-p (or start end)))
1433 (when in-region-p
1434 (or start (setq start (point-min)))
1435 (or end (setq end (point-max))))
1436 (let ((occur--region-start start)
1437 (occur--region-end end)
1438 (occur--matches-threshold
1439 (and in-region-p
1440 (line-number-at-pos (min start end))))
1441 (occur--orig-line
1442 (line-number-at-pos (point)))
1443 (occur--orig-line-str
1444 (buffer-substring-no-properties
1445 (line-beginning-position)
1446 (line-end-position))))
1447 (save-excursion ; If no matches `occur-1' doesn't restore the point.
1448 (and in-region-p (narrow-to-region start end))
1449 (occur-1 regexp nlines (list (current-buffer)))
1450 (and in-region-p (widen))))))
1452 (defvar ido-ignore-item-temp-list)
1454 (defun multi-occur (bufs regexp &optional nlines)
1455 "Show all lines in buffers BUFS containing a match for REGEXP.
1456 This function acts on multiple buffers; otherwise, it is exactly like
1457 `occur'. When you invoke this command interactively, you must specify
1458 the buffer names that you want, one by one.
1459 See also `multi-occur-in-matching-buffers'."
1460 (interactive
1461 (cons
1462 (let* ((bufs (list (read-buffer "First buffer to search: "
1463 (current-buffer) t)))
1464 (buf nil)
1465 (ido-ignore-item-temp-list bufs))
1466 (while (not (string-equal
1467 (setq buf (read-buffer
1468 (if (eq read-buffer-function #'ido-read-buffer)
1469 "Next buffer to search (C-j to end): "
1470 "Next buffer to search (RET to end): ")
1471 nil t))
1472 ""))
1473 (cl-pushnew buf bufs)
1474 (setq ido-ignore-item-temp-list bufs))
1475 (nreverse (mapcar #'get-buffer bufs)))
1476 (occur-read-primary-args)))
1477 (occur-1 regexp nlines bufs))
1479 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1480 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1481 Normally BUFREGEXP matches against each buffer's visited file name,
1482 but if you specify a prefix argument, it matches against the buffer name.
1483 See also `multi-occur'."
1484 (interactive
1485 (cons
1486 (let* ((default (car regexp-history))
1487 (input
1488 (read-regexp
1489 (if current-prefix-arg
1490 "List lines in buffers whose names match regexp: "
1491 "List lines in buffers whose filenames match regexp: "))))
1492 (if (equal input "")
1493 default
1494 input))
1495 (occur-read-primary-args)))
1496 (when bufregexp
1497 (occur-1 regexp nil
1498 (delq nil
1499 (mapcar (lambda (buf)
1500 (when (if allbufs
1501 (string-match bufregexp
1502 (buffer-name buf))
1503 (and (buffer-file-name buf)
1504 (string-match bufregexp
1505 (buffer-file-name buf))))
1506 buf))
1507 (buffer-list))))))
1509 (defun occur-regexp-descr (regexp)
1510 (format " for %s\"%s\""
1511 (or (get-text-property 0 'isearch-regexp-function-descr regexp)
1513 (if (get-text-property 0 'isearch-string regexp)
1514 (propertize
1515 (query-replace-descr
1516 (get-text-property 0 'isearch-string regexp))
1517 'help-echo regexp)
1518 (query-replace-descr regexp))))
1520 (defun occur-1 (regexp nlines bufs &optional buf-name)
1521 (unless (and regexp (not (equal regexp "")))
1522 (error "Occur doesn't work with the empty regexp"))
1523 (unless buf-name
1524 (setq buf-name "*Occur*"))
1525 (let (occur-buf
1526 (active-bufs (delq nil (mapcar #'(lambda (buf)
1527 (when (buffer-live-p buf) buf))
1528 bufs))))
1529 ;; Handle the case where one of the buffers we're searching is the
1530 ;; output buffer. Just rename it.
1531 (when (member buf-name (mapcar 'buffer-name active-bufs))
1532 (with-current-buffer (get-buffer buf-name)
1533 (rename-uniquely)))
1535 ;; Now find or create the output buffer.
1536 ;; If we just renamed that buffer, we will make a new one here.
1537 (setq occur-buf (get-buffer-create buf-name))
1539 (with-current-buffer occur-buf
1540 (if (stringp nlines)
1541 (fundamental-mode) ;; This is for collect operation.
1542 (occur-mode))
1543 (let ((inhibit-read-only t)
1544 ;; Don't generate undo entries for creation of the initial contents.
1545 (buffer-undo-list t)
1546 (occur--final-pos nil))
1547 (erase-buffer)
1548 (let ((count
1549 (if (stringp nlines)
1550 ;; Treat nlines as a regexp to collect.
1551 (let ((bufs active-bufs)
1552 (count 0))
1553 (while bufs
1554 (with-current-buffer (car bufs)
1555 (save-excursion
1556 (goto-char (point-min))
1557 (while (re-search-forward regexp nil t)
1558 ;; Insert the replacement regexp.
1559 (let ((str (match-substitute-replacement nlines)))
1560 (if str
1561 (with-current-buffer occur-buf
1562 (insert str)
1563 (setq count (1+ count))
1564 (or (zerop (current-column))
1565 (insert "\n"))))))))
1566 (setq bufs (cdr bufs)))
1567 count)
1568 ;; Perform normal occur.
1569 (occur-engine
1570 regexp active-bufs occur-buf
1571 (or nlines list-matching-lines-default-context-lines)
1572 (if (and case-fold-search search-upper-case)
1573 (isearch-no-upper-case-p regexp t)
1574 case-fold-search)
1575 list-matching-lines-buffer-name-face
1576 (if (face-differs-from-default-p list-matching-lines-prefix-face)
1577 list-matching-lines-prefix-face)
1578 list-matching-lines-face
1579 (not (eq occur-excluded-properties t))))))
1580 (let* ((bufcount (length active-bufs))
1581 (diff (- (length bufs) bufcount)))
1582 (message "Searched %d buffer%s%s; %s match%s%s"
1583 bufcount (if (= bufcount 1) "" "s")
1584 (if (zerop diff) "" (format " (%d killed)" diff))
1585 (if (zerop count) "no" (format "%d" count))
1586 (if (= count 1) "" "es")
1587 ;; Don't display regexp if with remaining text
1588 ;; it is longer than window-width.
1589 (if (> (+ (length (or (get-text-property 0 'isearch-string regexp)
1590 regexp))
1592 (window-width))
1593 "" (occur-regexp-descr regexp))))
1594 (setq occur-revert-arguments (list regexp nlines bufs))
1595 (if (= count 0)
1596 (kill-buffer occur-buf)
1597 (display-buffer occur-buf)
1598 (when occur--final-pos
1599 (set-window-point
1600 (get-buffer-window occur-buf 'all-frames)
1601 occur--final-pos))
1602 (setq next-error-last-buffer occur-buf)
1603 (setq buffer-read-only t)
1604 (set-buffer-modified-p nil)
1605 (run-hooks 'occur-hook)))))))
1607 (defun occur-engine (regexp buffers out-buf nlines case-fold
1608 title-face prefix-face match-face keep-props)
1609 (with-current-buffer out-buf
1610 (let ((global-lines 0) ;; total count of matching lines
1611 (global-matches 0) ;; total count of matches
1612 (coding nil)
1613 (case-fold-search case-fold)
1614 (in-region-p (and occur--region-start occur--region-end))
1615 (multi-occur-p (cdr buffers)))
1616 ;; Map over all the buffers
1617 (dolist (buf buffers)
1618 (when (buffer-live-p buf)
1619 (let ((lines 0) ;; count of matching lines
1620 (matches 0) ;; count of matches
1621 (curr-line ;; line count
1622 (or occur--matches-threshold 1))
1623 (orig-line occur--orig-line)
1624 (orig-line-str occur--orig-line-str)
1625 (orig-line-shown-p)
1626 (prev-line nil) ;; line number of prev match endpt
1627 (prev-after-lines nil) ;; context lines of prev match
1628 (matchbeg 0)
1629 (origpt nil)
1630 (begpt nil)
1631 (endpt nil)
1632 (finalpt nil)
1633 (marker nil)
1634 (curstring "")
1635 (ret nil)
1636 (inhibit-field-text-motion t)
1637 (headerpt (with-current-buffer out-buf (point))))
1638 (with-current-buffer buf
1639 (or coding
1640 ;; Set CODING only if the current buffer locally
1641 ;; binds buffer-file-coding-system.
1642 (not (local-variable-p 'buffer-file-coding-system))
1643 (setq coding buffer-file-coding-system))
1644 (save-excursion
1645 (goto-char (point-min)) ;; begin searching in the buffer
1646 (while (not (eobp))
1647 (setq origpt (point))
1648 (when (setq endpt (re-search-forward regexp nil t))
1649 (setq lines (1+ lines)) ;; increment matching lines count
1650 (setq matchbeg (match-beginning 0))
1651 ;; Get beginning of first match line and end of the last.
1652 (save-excursion
1653 (goto-char matchbeg)
1654 (setq begpt (line-beginning-position))
1655 (goto-char endpt)
1656 (setq endpt (line-end-position)))
1657 ;; Sum line numbers up to the first match line.
1658 (setq curr-line (+ curr-line (count-lines origpt begpt)))
1659 (setq marker (make-marker))
1660 (set-marker marker matchbeg)
1661 (setq curstring (occur-engine-line begpt endpt keep-props))
1662 ;; Highlight the matches
1663 (let ((len (length curstring))
1664 (start 0))
1665 ;; Count empty lines that don't use next loop (Bug#22062).
1666 (when (zerop len)
1667 (setq matches (1+ matches)))
1668 (while (and (< start len)
1669 (string-match regexp curstring start))
1670 (setq matches (1+ matches))
1671 (add-text-properties
1672 (match-beginning 0) (match-end 0)
1673 '(occur-match t) curstring)
1674 (when match-face
1675 ;; Add `match-face' to faces copied from the buffer.
1676 (add-face-text-property
1677 (match-beginning 0) (match-end 0)
1678 match-face nil curstring))
1679 ;; Avoid infloop (Bug#7593).
1680 (let ((end (match-end 0)))
1681 (setq start (if (= start end) (1+ start) end)))))
1682 ;; Generate the string to insert for this match
1683 (let* ((match-prefix
1684 ;; Using 7 digits aligns tabs properly.
1685 (apply #'propertize (format "%7d:" curr-line)
1686 (append
1687 (when prefix-face
1688 `(font-lock-face ,prefix-face))
1689 `(occur-prefix t mouse-face (highlight)
1690 ;; Allow insertion of text at
1691 ;; the end of the prefix (for
1692 ;; Occur Edit mode).
1693 front-sticky t rear-nonsticky t
1694 occur-target ,marker follow-link t
1695 help-echo "mouse-2: go to this occurrence"))))
1696 (match-str
1697 ;; We don't put `mouse-face' on the newline,
1698 ;; because that loses. And don't put it
1699 ;; on context lines to reduce flicker.
1700 (propertize curstring 'mouse-face (list 'highlight)
1701 'occur-target marker
1702 'follow-link t
1703 'help-echo
1704 "mouse-2: go to this occurrence"))
1705 (out-line
1706 (concat
1707 match-prefix
1708 ;; Add non-numeric prefix to all non-first lines
1709 ;; of multi-line matches.
1710 (replace-regexp-in-string
1711 "\n"
1712 (if prefix-face
1713 (propertize "\n :" 'font-lock-face prefix-face)
1714 "\n :")
1715 match-str)
1716 ;; Add marker at eol, but no mouse props.
1717 (propertize "\n" 'occur-target marker)))
1718 (data
1719 (if (= nlines 0)
1720 ;; The simple display style
1721 out-line
1722 ;; The complex multi-line display style.
1723 (setq ret (occur-context-lines
1724 out-line nlines keep-props begpt endpt
1725 curr-line prev-line prev-after-lines
1726 prefix-face))
1727 ;; Set first elem of the returned list to `data',
1728 ;; and the second elem to `prev-after-lines'.
1729 (setq prev-after-lines (nth 1 ret))
1730 (nth 0 ret))))
1731 ;; Actually insert the match display data
1732 (with-current-buffer out-buf
1733 (when (and list-matching-lines-jump-to-current-line
1734 (not multi-occur-p)
1735 (not orig-line-shown-p)
1736 (>= curr-line orig-line))
1737 (insert
1738 (concat
1739 (propertize
1740 (format "%7d:%s" orig-line orig-line-str)
1741 'face list-matching-lines-current-line-face
1742 'mouse-face 'mode-line-highlight
1743 'help-echo "Current line") "\n"))
1744 (setq orig-line-shown-p t finalpt (point)))
1745 (insert data)))
1746 (goto-char endpt))
1747 (if endpt
1748 (progn
1749 ;; Sum line numbers between first and last match lines.
1750 (setq curr-line (+ curr-line (count-lines begpt endpt)
1751 ;; Add 1 for empty last match line since
1752 ;; count-lines returns 1 line less.
1753 (if (and (bolp) (eolp)) 1 0)))
1754 ;; On to the next match...
1755 (forward-line 1))
1756 (goto-char (point-max)))
1757 (setq prev-line (1- curr-line)))
1758 ;; Insert original line if haven't done yet.
1759 (when (and list-matching-lines-jump-to-current-line
1760 (not multi-occur-p)
1761 (not orig-line-shown-p))
1762 (with-current-buffer out-buf
1763 (insert
1764 (concat
1765 (propertize
1766 (format "%7d:%s" orig-line orig-line-str)
1767 'face list-matching-lines-current-line-face
1768 'mouse-face 'mode-line-highlight
1769 'help-echo "Current line") "\n"))))
1770 ;; Flush remaining context after-lines.
1771 (when prev-after-lines
1772 (with-current-buffer out-buf
1773 (insert (apply #'concat (occur-engine-add-prefix
1774 prev-after-lines prefix-face)))))))
1775 (when (not (zerop lines)) ;; is the count zero?
1776 (setq global-lines (+ global-lines lines)
1777 global-matches (+ global-matches matches))
1778 (with-current-buffer out-buf
1779 (goto-char headerpt)
1780 (let ((beg (point))
1781 end)
1782 (insert (propertize
1783 (format "%d match%s%s%s in buffer: %s%s\n"
1784 matches (if (= matches 1) "" "es")
1785 ;; Don't display the same number of lines
1786 ;; and matches in case of 1 match per line.
1787 (if (= lines matches)
1788 "" (format " in %d line%s"
1789 lines (if (= lines 1) "" "s")))
1790 ;; Don't display regexp for multi-buffer.
1791 (if (> (length buffers) 1)
1792 "" (occur-regexp-descr regexp))
1793 (buffer-name buf)
1794 (if in-region-p
1795 (format " within region: %d-%d"
1796 occur--region-start
1797 occur--region-end)
1798 ""))
1799 'read-only t))
1800 (setq end (point))
1801 (add-text-properties beg end `(occur-title ,buf))
1802 (when title-face
1803 (add-face-text-property beg end title-face))
1804 (goto-char (if finalpt
1805 (setq occur--final-pos
1806 (cl-incf finalpt (- end beg)))
1807 (point-min)))))))))
1808 ;; Display total match count and regexp for multi-buffer.
1809 (when (and (not (zerop global-lines)) (> (length buffers) 1))
1810 (goto-char (point-min))
1811 (let ((beg (point))
1812 end)
1813 (insert (format "%d match%s%s total%s:\n"
1814 global-matches (if (= global-matches 1) "" "es")
1815 ;; Don't display the same number of lines
1816 ;; and matches in case of 1 match per line.
1817 (if (= global-lines global-matches)
1818 "" (format " in %d line%s"
1819 global-lines (if (= global-lines 1) "" "s")))
1820 (occur-regexp-descr regexp)))
1821 (setq end (point))
1822 (when title-face
1823 (add-face-text-property beg end title-face)))
1824 (goto-char (point-min)))
1825 (if coding
1826 ;; CODING is buffer-file-coding-system of the first buffer
1827 ;; that locally binds it. Let's use it also for the output
1828 ;; buffer.
1829 (set-buffer-file-coding-system coding))
1830 ;; Return the number of matches
1831 global-matches)))
1833 (defun occur-engine-line (beg end &optional keep-props)
1834 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1835 (text-property-not-all beg end 'fontified t))
1836 (if (fboundp 'jit-lock-fontify-now)
1837 (jit-lock-fontify-now beg end)))
1838 (if (and keep-props (not (eq occur-excluded-properties t)))
1839 (let ((str (buffer-substring beg end)))
1840 (remove-list-of-text-properties
1841 0 (length str) occur-excluded-properties str)
1842 str)
1843 (buffer-substring-no-properties beg end)))
1845 (defun occur-engine-add-prefix (lines &optional prefix-face)
1846 (mapcar
1847 #'(lambda (line)
1848 (concat (if prefix-face
1849 (propertize " :" 'font-lock-face prefix-face)
1850 " :")
1851 line "\n"))
1852 lines))
1854 (defun occur-accumulate-lines (count &optional keep-props pt)
1855 (save-excursion
1856 (when pt
1857 (goto-char pt))
1858 (let ((forwardp (> count 0))
1859 result beg end moved)
1860 (while (not (or (zerop count)
1861 (if forwardp
1862 (eobp)
1863 (and (bobp) (not moved)))))
1864 (setq count (+ count (if forwardp -1 1)))
1865 (setq beg (line-beginning-position)
1866 end (line-end-position))
1867 (push (occur-engine-line beg end keep-props) result)
1868 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1869 (nreverse result))))
1871 ;; Generate context display for occur.
1872 ;; OUT-LINE is the line where the match is.
1873 ;; NLINES and KEEP-PROPS are args to occur-engine.
1874 ;; CURR-LINE is line count of the current match,
1875 ;; PREV-LINE is line count of the previous match,
1876 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1877 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1878 ;; then concatenate them all together.
1879 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1880 curr-line prev-line prev-after-lines
1881 &optional prefix-face)
1882 ;; Find after- and before-context lines of the current match.
1883 (let ((before-lines
1884 (nreverse (cdr (occur-accumulate-lines
1885 (- (1+ (abs nlines))) keep-props begpt))))
1886 (after-lines
1887 (cdr (occur-accumulate-lines
1888 (1+ nlines) keep-props endpt)))
1889 separator)
1891 ;; Combine after-lines of the previous match
1892 ;; with before-lines of the current match.
1894 (when prev-after-lines
1895 ;; Don't overlap prev after-lines with current before-lines.
1896 (if (>= (+ prev-line (length prev-after-lines))
1897 (- curr-line (length before-lines)))
1898 (setq prev-after-lines
1899 (butlast prev-after-lines
1900 (- (length prev-after-lines)
1901 (- curr-line prev-line (length before-lines) 1))))
1902 ;; Separate non-overlapping context lines with a dashed line.
1903 (setq separator "-------\n")))
1905 (when prev-line
1906 ;; Don't overlap current before-lines with previous match line.
1907 (if (<= (- curr-line (length before-lines))
1908 prev-line)
1909 (setq before-lines
1910 (nthcdr (- (length before-lines)
1911 (- curr-line prev-line 1))
1912 before-lines))
1913 ;; Separate non-overlapping before-context lines.
1914 (unless (> nlines 0)
1915 (setq separator "-------\n"))))
1917 (list
1918 ;; Return a list where the first element is the output line.
1919 (apply #'concat
1920 (append
1921 (if prev-after-lines
1922 (occur-engine-add-prefix prev-after-lines prefix-face))
1923 (if separator
1924 (list (if prefix-face
1925 (propertize separator 'font-lock-face prefix-face)
1926 separator)))
1927 (occur-engine-add-prefix before-lines prefix-face)
1928 (list out-line)))
1929 ;; And the second element is the list of context after-lines.
1930 (if (> nlines 0) after-lines))))
1933 ;; It would be nice to use \\[...], but there is no reasonable way
1934 ;; to make that display both SPC and Y.
1935 (defconst query-replace-help
1936 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1937 RET or `q' to exit, Period to replace one match and exit,
1938 Comma to replace but not move point immediately,
1939 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1940 C-w to delete match and recursive edit,
1941 C-l to clear the screen, redisplay, and offer same replacement again,
1942 ! to replace all remaining matches in this buffer with no more questions,
1943 ^ to move point back to previous match,
1944 u to undo previous replacement,
1945 U to undo all replacements,
1946 E to edit the replacement string.
1947 In multi-buffer replacements type `Y' to replace all remaining
1948 matches in all remaining buffers with no more questions,
1949 `N' to skip to the next buffer without replacing remaining matches
1950 in the current buffer."
1951 "Help message while in `query-replace'.")
1953 (defvar query-replace-map
1954 (let ((map (make-sparse-keymap)))
1955 (define-key map " " 'act)
1956 (define-key map "\d" 'skip)
1957 (define-key map [delete] 'skip)
1958 (define-key map [backspace] 'skip)
1959 (define-key map "y" 'act)
1960 (define-key map "n" 'skip)
1961 (define-key map "Y" 'act)
1962 (define-key map "N" 'skip)
1963 (define-key map "e" 'edit-replacement)
1964 (define-key map "E" 'edit-replacement)
1965 (define-key map "," 'act-and-show)
1966 (define-key map "q" 'exit)
1967 (define-key map "\r" 'exit)
1968 (define-key map [return] 'exit)
1969 (define-key map "." 'act-and-exit)
1970 (define-key map "\C-r" 'edit)
1971 (define-key map "\C-w" 'delete-and-edit)
1972 (define-key map "\C-l" 'recenter)
1973 (define-key map "!" 'automatic)
1974 (define-key map "^" 'backup)
1975 (define-key map "u" 'undo)
1976 (define-key map "U" 'undo-all)
1977 (define-key map "\C-h" 'help)
1978 (define-key map [f1] 'help)
1979 (define-key map [help] 'help)
1980 (define-key map "?" 'help)
1981 (define-key map "\C-g" 'quit)
1982 (define-key map "\C-]" 'quit)
1983 (define-key map "\C-v" 'scroll-up)
1984 (define-key map "\M-v" 'scroll-down)
1985 (define-key map [next] 'scroll-up)
1986 (define-key map [prior] 'scroll-down)
1987 (define-key map [?\C-\M-v] 'scroll-other-window)
1988 (define-key map [M-next] 'scroll-other-window)
1989 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1990 (define-key map [M-prior] 'scroll-other-window-down)
1991 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1992 ;; should check for ESC specially.
1993 ;; (define-key map "\e" 'exit-prefix)
1994 (define-key map [escape] 'exit-prefix)
1995 map)
1996 "Keymap of responses to questions posed by commands like `query-replace'.
1997 The \"bindings\" in this map are not commands; they are answers.
1998 The valid answers include `act', `skip', `act-and-show',
1999 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
2000 `scroll-down', `scroll-other-window', `scroll-other-window-down',
2001 `edit', `edit-replacement', `delete-and-edit', `automatic',
2002 `backup', `undo', `undo-all', `quit', and `help'.
2004 This keymap is used by `y-or-n-p' as well as `query-replace'.")
2006 (defvar multi-query-replace-map
2007 (let ((map (make-sparse-keymap)))
2008 (set-keymap-parent map query-replace-map)
2009 (define-key map "Y" 'automatic-all)
2010 (define-key map "N" 'exit-current)
2011 map)
2012 "Keymap that defines additional bindings for multi-buffer replacements.
2013 It extends its parent map `query-replace-map' with new bindings to
2014 operate on a set of buffers/files. The difference with its parent map
2015 is the additional answers `automatic-all' to replace all remaining
2016 matches in all remaining buffers with no more questions, and
2017 `exit-current' to skip remaining matches in the current buffer
2018 and to continue with the next buffer in the sequence.")
2020 (defun replace-match-string-symbols (n)
2021 "Process a list (and any sub-lists), expanding certain symbols.
2022 Symbol Expands To
2023 N (match-string N) (where N is a string of digits)
2024 #N (string-to-number (match-string N))
2025 & (match-string 0)
2026 #& (string-to-number (match-string 0))
2027 # replace-count
2029 Note that these symbols must be preceded by a backslash in order to
2030 type them using Lisp syntax."
2031 (while (consp n)
2032 (cond
2033 ((consp (car n))
2034 (replace-match-string-symbols (car n))) ;Process sub-list
2035 ((symbolp (car n))
2036 (let ((name (symbol-name (car n))))
2037 (cond
2038 ((string-match "^[0-9]+$" name)
2039 (setcar n (list 'match-string (string-to-number name))))
2040 ((string-match "^#[0-9]+$" name)
2041 (setcar n (list 'string-to-number
2042 (list 'match-string
2043 (string-to-number (substring name 1))))))
2044 ((string= "&" name)
2045 (setcar n '(match-string 0)))
2046 ((string= "#&" name)
2047 (setcar n '(string-to-number (match-string 0))))
2048 ((string= "#" name)
2049 (setcar n 'replace-count))))))
2050 (setq n (cdr n))))
2052 (defun replace-eval-replacement (expression count)
2053 (let* ((replace-count count)
2054 (replacement
2055 (condition-case err
2056 (eval expression)
2057 (error
2058 (error "Error evaluating replacement expression: %S" err)))))
2059 (if (stringp replacement)
2060 replacement
2061 (prin1-to-string replacement t))))
2063 (defun replace-quote (replacement)
2064 "Quote a replacement string.
2065 This just doubles all backslashes in REPLACEMENT and
2066 returns the resulting string. If REPLACEMENT is not
2067 a string, it is first passed through `prin1-to-string'
2068 with the `noescape' argument set.
2070 `match-data' is preserved across the call."
2071 (save-match-data
2072 (replace-regexp-in-string "\\\\" "\\\\"
2073 (if (stringp replacement)
2074 replacement
2075 (prin1-to-string replacement t))
2076 t t)))
2078 (defun replace-loop-through-replacements (data count)
2079 ;; DATA is a vector containing the following values:
2080 ;; 0 next-rotate-count
2081 ;; 1 repeat-count
2082 ;; 2 next-replacement
2083 ;; 3 replacements
2084 (if (= (aref data 0) count)
2085 (progn
2086 (aset data 0 (+ count (aref data 1)))
2087 (let ((next (cdr (aref data 2))))
2088 (aset data 2 (if (consp next) next (aref data 3))))))
2089 (car (aref data 2)))
2091 (defun replace-match-data (integers reuse &optional new)
2092 "Like `match-data', but markers in REUSE get invalidated.
2093 If NEW is non-nil, it is set and returned instead of fresh data,
2094 but coerced to the correct value of INTEGERS."
2095 (or (and new
2096 (progn
2097 (set-match-data new)
2098 (and (eq new reuse)
2099 (eq (null integers) (markerp (car reuse)))
2100 new)))
2101 (match-data integers reuse t)))
2103 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data
2104 &optional backward)
2105 "Make a replacement with `replace-match', editing `\\?'.
2106 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
2107 After possibly editing it (if `\\?' is present), NEWTEXT is also
2108 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
2109 is made (to save time).
2110 MATCH-DATA is used for the replacement, and is a data structure
2111 as returned from the `match-data' function.
2112 In case editing is done, it is changed to use markers. BACKWARD is
2113 used to reverse the replacement direction.
2115 The return value is non-nil if there has been no `\\?' or NOEDIT was
2116 passed in. If LITERAL is set, no checking is done, anyway."
2117 (unless (or literal noedit)
2118 (setq noedit t)
2119 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
2120 newtext)
2121 (setq newtext
2122 (read-string "Edit replacement string: "
2123 (prog1
2124 (cons
2125 (replace-match "" t t newtext 3)
2126 (1+ (match-beginning 3)))
2127 (setq match-data
2128 (replace-match-data
2129 nil match-data match-data))))
2130 noedit nil)))
2131 (set-match-data match-data)
2132 (replace-match newtext fixedcase literal)
2133 ;; `replace-match' leaves point at the end of the replacement text,
2134 ;; so move point to the beginning when replacing backward.
2135 (when backward (goto-char (nth 0 match-data)))
2136 noedit)
2138 (defvar replace-update-post-hook nil
2139 "Function(s) to call after query-replace has found a match in the buffer.")
2141 (defvar replace-search-function nil
2142 "Function to use when searching for strings to replace.
2143 It is used by `query-replace' and `replace-string', and is called
2144 with three arguments, as if it were `search-forward'.")
2146 (defvar replace-re-search-function nil
2147 "Function to use when searching for regexps to replace.
2148 It is used by `query-replace-regexp', `replace-regexp',
2149 `query-replace-regexp-eval', and `map-query-replace-regexp'.
2150 It is called with three arguments, as if it were
2151 `re-search-forward'.")
2153 (defun replace-search (search-string limit regexp-flag delimited-flag
2154 case-fold &optional backward)
2155 "Search for the next occurrence of SEARCH-STRING to replace."
2156 ;; Let-bind global isearch-* variables to values used
2157 ;; to search the next replacement. These let-bindings
2158 ;; should be effective both at the time of calling
2159 ;; `isearch-search-fun-default' and also at the
2160 ;; time of funcalling `search-function'.
2161 ;; These isearch-* bindings can't be placed higher
2162 ;; outside of this function because then another I-search
2163 ;; used after `recursive-edit' might override them.
2164 (let* ((isearch-regexp regexp-flag)
2165 (isearch-regexp-function (or delimited-flag
2166 (and replace-char-fold
2167 (not regexp-flag)
2168 #'char-fold-to-regexp)))
2169 (isearch-lax-whitespace
2170 replace-lax-whitespace)
2171 (isearch-regexp-lax-whitespace
2172 replace-regexp-lax-whitespace)
2173 (isearch-case-fold-search case-fold)
2174 (isearch-adjusted nil)
2175 (isearch-nonincremental t) ; don't use lax word mode
2176 (isearch-forward (not backward))
2177 (search-function
2178 (or (if regexp-flag
2179 replace-re-search-function
2180 replace-search-function)
2181 (isearch-search-fun-default))))
2182 (funcall search-function search-string limit t)))
2184 (defvar replace-overlay nil)
2186 (defun replace-highlight (match-beg match-end range-beg range-end
2187 search-string regexp-flag delimited-flag
2188 case-fold &optional backward)
2189 (if query-replace-highlight
2190 (if replace-overlay
2191 (move-overlay replace-overlay match-beg match-end (current-buffer))
2192 (setq replace-overlay (make-overlay match-beg match-end))
2193 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2194 (overlay-put replace-overlay 'face 'query-replace)))
2195 (if query-replace-lazy-highlight
2196 (let ((isearch-string search-string)
2197 (isearch-regexp regexp-flag)
2198 (isearch-regexp-function delimited-flag)
2199 (isearch-lax-whitespace
2200 replace-lax-whitespace)
2201 (isearch-regexp-lax-whitespace
2202 replace-regexp-lax-whitespace)
2203 (isearch-case-fold-search case-fold)
2204 (isearch-forward (not backward))
2205 (isearch-other-end match-beg)
2206 (isearch-error nil))
2207 (isearch-lazy-highlight-new-loop range-beg range-end))))
2209 (defun replace-dehighlight ()
2210 (when replace-overlay
2211 (delete-overlay replace-overlay))
2212 (when query-replace-lazy-highlight
2213 (lazy-highlight-cleanup lazy-highlight-cleanup)
2214 (setq isearch-lazy-highlight-last-string nil))
2215 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2216 (isearch-clean-overlays))
2218 (defun perform-replace (from-string replacements
2219 query-flag regexp-flag delimited-flag
2220 &optional repeat-count map start end backward region-noncontiguous-p)
2221 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2222 Don't use this in your own program unless you want to query and set the mark
2223 just as `query-replace' does. Instead, write a simple loop like this:
2225 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2226 (replace-match \"foobar\" nil nil))
2228 which will run faster and probably do exactly what you want. Please
2229 see the documentation of `replace-match' to find out how to simulate
2230 `case-replace'.
2232 This function returns nil if and only if there were no matches to
2233 make, or the user didn't cancel the call.
2235 REPLACEMENTS is either a string, a list of strings, or a cons cell
2236 containing a function and its first argument. The function is
2237 called to generate each replacement like this:
2238 (funcall (car replacements) (cdr replacements) replace-count)
2239 It must return a string."
2240 (or map (setq map query-replace-map))
2241 (and query-flag minibuffer-auto-raise
2242 (raise-frame (window-frame (minibuffer-window))))
2243 (let* ((case-fold-search
2244 (if (and case-fold-search search-upper-case)
2245 (isearch-no-upper-case-p from-string regexp-flag)
2246 case-fold-search))
2247 (nocasify (not (and case-replace case-fold-search)))
2248 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2249 (search-string from-string)
2250 (real-match-data nil) ; The match data for the current match.
2251 (next-replacement nil)
2252 ;; This is non-nil if we know there is nothing for the user
2253 ;; to edit in the replacement.
2254 (noedit nil)
2255 (keep-going t)
2256 (stack nil)
2257 (search-string-replaced nil) ; last string matching `from-string'
2258 (next-replacement-replaced nil) ; replacement string
2259 ; (substituted regexp)
2260 (last-was-undo)
2261 (replace-count 0)
2262 (skip-read-only-count 0)
2263 (skip-filtered-count 0)
2264 (skip-invisible-count 0)
2265 (nonempty-match nil)
2266 (multi-buffer nil)
2267 (recenter-last-op nil) ; Start cycling order with initial position.
2269 ;; If non-nil, it is marker saying where in the buffer to stop.
2270 (limit nil)
2271 ;; Use local binding in add-function below.
2272 (isearch-filter-predicate isearch-filter-predicate)
2273 (region-bounds nil)
2275 ;; Data for the next match. If a cons, it has the same format as
2276 ;; (match-data); otherwise it is t if a match is possible at point.
2277 (match-again t)
2279 (message
2280 (if query-flag
2281 (apply 'propertize
2282 (substitute-command-keys
2283 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2284 minibuffer-prompt-properties))))
2286 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
2287 (when region-noncontiguous-p
2288 (setq region-bounds
2289 (mapcar (lambda (position)
2290 (cons (copy-marker (car position))
2291 (copy-marker (cdr position))))
2292 (funcall region-extract-function 'bounds)))
2293 (add-function :after-while isearch-filter-predicate
2294 (lambda (start end)
2295 (delq nil (mapcar
2296 (lambda (bounds)
2297 (and
2298 (>= start (car bounds))
2299 (<= start (cdr bounds))
2300 (>= end (car bounds))
2301 (<= end (cdr bounds))))
2302 region-bounds)))))
2304 ;; If region is active, in Transient Mark mode, operate on region.
2305 (if backward
2306 (when end
2307 (setq limit (copy-marker (min start end)))
2308 (goto-char (max start end))
2309 (deactivate-mark))
2310 (when start
2311 (setq limit (copy-marker (max start end)))
2312 (goto-char (min start end))
2313 (deactivate-mark)))
2315 ;; If last typed key in previous call of multi-buffer perform-replace
2316 ;; was `automatic-all', don't ask more questions in next files
2317 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2318 (setq query-flag nil multi-buffer t))
2320 (cond
2321 ((stringp replacements)
2322 (setq next-replacement replacements
2323 replacements nil))
2324 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2325 (or repeat-count (setq repeat-count 1))
2326 (setq replacements (cons 'replace-loop-through-replacements
2327 (vector repeat-count repeat-count
2328 replacements replacements)))))
2330 (when query-replace-lazy-highlight
2331 (setq isearch-lazy-highlight-last-string nil))
2333 (push-mark)
2334 (undo-boundary)
2335 (unwind-protect
2336 ;; Loop finding occurrences that perhaps should be replaced.
2337 (while (and keep-going
2338 (if backward
2339 (not (or (bobp) (and limit (<= (point) limit))))
2340 (not (or (eobp) (and limit (>= (point) limit)))))
2341 ;; Use the next match if it is already known;
2342 ;; otherwise, search for a match after moving forward
2343 ;; one char if progress is required.
2344 (setq real-match-data
2345 (cond ((consp match-again)
2346 (goto-char (if backward
2347 (nth 0 match-again)
2348 (nth 1 match-again)))
2349 (replace-match-data
2350 t real-match-data match-again))
2351 ;; MATCH-AGAIN non-nil means accept an
2352 ;; adjacent match.
2353 (match-again
2354 (and
2355 (replace-search search-string limit
2356 regexp-flag delimited-flag
2357 case-fold-search backward)
2358 ;; For speed, use only integers and
2359 ;; reuse the list used last time.
2360 (replace-match-data t real-match-data)))
2361 ((and (if backward
2362 (> (1- (point)) (point-min))
2363 (< (1+ (point)) (point-max)))
2364 (or (null limit)
2365 (if backward
2366 (> (1- (point)) limit)
2367 (< (1+ (point)) limit))))
2368 ;; If not accepting adjacent matches,
2369 ;; move one char to the right before
2370 ;; searching again. Undo the motion
2371 ;; if the search fails.
2372 (let ((opoint (point)))
2373 (forward-char (if backward -1 1))
2374 (if (replace-search search-string limit
2375 regexp-flag delimited-flag
2376 case-fold-search backward)
2377 (replace-match-data
2378 t real-match-data)
2379 (goto-char opoint)
2380 nil))))))
2382 ;; Record whether the match is nonempty, to avoid an infinite loop
2383 ;; repeatedly matching the same empty string.
2384 (setq nonempty-match
2385 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2387 ;; If the match is empty, record that the next one can't be
2388 ;; adjacent.
2390 ;; Otherwise, if matching a regular expression, do the next
2391 ;; match now, since the replacement for this match may
2392 ;; affect whether the next match is adjacent to this one.
2393 ;; If that match is empty, don't use it.
2394 (setq match-again
2395 (and nonempty-match
2396 (or (not regexp-flag)
2397 (and (if backward
2398 (looking-back search-string nil)
2399 (looking-at search-string))
2400 (let ((match (match-data)))
2401 (and (/= (nth 0 match) (nth 1 match))
2402 match))))))
2404 (cond
2405 ;; Optionally ignore matches that have a read-only property.
2406 ((not (or (not query-replace-skip-read-only)
2407 (not (text-property-not-all
2408 (nth 0 real-match-data) (nth 1 real-match-data)
2409 'read-only nil))))
2410 (setq skip-read-only-count (1+ skip-read-only-count)))
2411 ;; Optionally filter out matches.
2412 ((not (funcall isearch-filter-predicate
2413 (nth 0 real-match-data) (nth 1 real-match-data)))
2414 (setq skip-filtered-count (1+ skip-filtered-count)))
2415 ;; Optionally ignore invisible matches.
2416 ((not (or (eq search-invisible t)
2417 ;; Don't open overlays for automatic replacements.
2418 (and (not query-flag) search-invisible)
2419 ;; Open hidden overlays for interactive replacements.
2420 (not (isearch-range-invisible
2421 (nth 0 real-match-data) (nth 1 real-match-data)))))
2422 (setq skip-invisible-count (1+ skip-invisible-count)))
2424 ;; Calculate the replacement string, if necessary.
2425 (when replacements
2426 (set-match-data real-match-data)
2427 (setq next-replacement
2428 (funcall (car replacements) (cdr replacements)
2429 replace-count)))
2430 (if (not query-flag)
2431 (progn
2432 (unless (or literal noedit)
2433 (replace-highlight
2434 (nth 0 real-match-data) (nth 1 real-match-data)
2435 start end search-string
2436 regexp-flag delimited-flag case-fold-search backward))
2437 (setq noedit
2438 (replace-match-maybe-edit
2439 next-replacement nocasify literal
2440 noedit real-match-data backward)
2441 replace-count (1+ replace-count)))
2442 (undo-boundary)
2443 (let (done replaced key def)
2444 ;; Loop reading commands until one of them sets done,
2445 ;; which means it has finished handling this
2446 ;; occurrence. Any command that sets `done' should
2447 ;; leave behind proper match data for the stack.
2448 ;; Commands not setting `done' need to adjust
2449 ;; `real-match-data'.
2450 (while (not done)
2451 (set-match-data real-match-data)
2452 (run-hooks 'replace-update-post-hook) ; Before `replace-highlight'.
2453 (replace-highlight
2454 (match-beginning 0) (match-end 0)
2455 start end search-string
2456 regexp-flag delimited-flag case-fold-search backward)
2457 ;; Obtain the matched groups: needed only when
2458 ;; regexp-flag non nil.
2459 (when (and last-was-undo regexp-flag)
2460 (setq last-was-undo nil
2461 real-match-data
2462 (save-excursion
2463 (goto-char (match-beginning 0))
2464 (looking-at search-string)
2465 (match-data t real-match-data))))
2466 ;; Matched string and next-replacement-replaced
2467 ;; stored in stack.
2468 (setq search-string-replaced (buffer-substring-no-properties
2469 (match-beginning 0)
2470 (match-end 0))
2471 next-replacement-replaced
2472 (query-replace-descr
2473 (save-match-data
2474 (set-match-data real-match-data)
2475 (match-substitute-replacement
2476 next-replacement nocasify literal))))
2477 ;; Bind message-log-max so we don't fill up the
2478 ;; message log with a bunch of identical messages.
2479 (let ((message-log-max nil)
2480 (replacement-presentation
2481 (if query-replace-show-replacement
2482 (save-match-data
2483 (set-match-data real-match-data)
2484 (match-substitute-replacement next-replacement
2485 nocasify literal))
2486 next-replacement)))
2487 (message message
2488 (query-replace-descr from-string)
2489 (query-replace-descr replacement-presentation)))
2490 (setq key (read-event))
2491 ;; Necessary in case something happens during
2492 ;; read-event that clobbers the match data.
2493 (set-match-data real-match-data)
2494 (setq key (vector key))
2495 (setq def (lookup-key map key))
2496 ;; Restore the match data while we process the command.
2497 (cond ((eq def 'help)
2498 (with-output-to-temp-buffer "*Help*"
2499 (princ
2500 (concat "Query replacing "
2501 (if delimited-flag
2502 (or (and (symbolp delimited-flag)
2503 (get delimited-flag
2504 'isearch-message-prefix))
2505 "word ") "")
2506 (if regexp-flag "regexp " "")
2507 (if backward "backward " "")
2508 from-string " with "
2509 next-replacement ".\n\n"
2510 (substitute-command-keys
2511 query-replace-help)))
2512 (with-current-buffer standard-output
2513 (help-mode))))
2514 ((eq def 'exit)
2515 (setq keep-going nil)
2516 (setq done t))
2517 ((eq def 'exit-current)
2518 (setq multi-buffer t keep-going nil done t))
2519 ((eq def 'backup)
2520 (if stack
2521 (let ((elt (pop stack)))
2522 (goto-char (nth 0 elt))
2523 (setq replaced (nth 1 elt)
2524 real-match-data
2525 (replace-match-data
2526 t real-match-data
2527 (nth 2 elt))))
2528 (message "No previous match")
2529 (ding 'no-terminate)
2530 (sit-for 1)))
2531 ((or (eq def 'undo) (eq def 'undo-all))
2532 (if (null stack)
2533 (progn
2534 (message "Nothing to undo")
2535 (ding 'no-terminate)
2536 (sit-for 1))
2537 (let ((stack-idx 0)
2538 (stack-len (length stack))
2539 (num-replacements 0)
2540 search-string
2541 next-replacement)
2542 (while (and (< stack-idx stack-len)
2543 stack
2544 (null replaced))
2545 (let* ((elt (nth stack-idx stack)))
2546 (setq
2547 stack-idx (1+ stack-idx)
2548 replaced (nth 1 elt)
2549 ;; Bind swapped values
2550 ;; (search-string <--> replacement)
2551 search-string (nth (if replaced 4 3) elt)
2552 next-replacement (nth (if replaced 3 4) elt)
2553 search-string-replaced search-string
2554 next-replacement-replaced next-replacement)
2556 (when (and (= stack-idx stack-len)
2557 (null replaced)
2558 (zerop num-replacements))
2559 (message "Nothing to undo")
2560 (ding 'no-terminate)
2561 (sit-for 1))
2563 (when replaced
2564 (setq stack (nthcdr stack-idx stack))
2565 (goto-char (nth 0 elt))
2566 (set-match-data (nth 2 elt))
2567 (setq real-match-data
2568 (save-excursion
2569 (goto-char (match-beginning 0))
2570 (looking-at search-string)
2571 (match-data t (nth 2 elt)))
2572 noedit
2573 (replace-match-maybe-edit
2574 next-replacement nocasify literal
2575 noedit real-match-data backward)
2576 replace-count (1- replace-count)
2577 real-match-data
2578 (save-excursion
2579 (goto-char (match-beginning 0))
2580 (looking-at next-replacement)
2581 (match-data t (nth 2 elt))))
2582 ;; Set replaced nil to keep in loop
2583 (when (eq def 'undo-all)
2584 (setq replaced nil
2585 stack-len (- stack-len stack-idx)
2586 stack-idx 0
2587 num-replacements
2588 (1+ num-replacements))))))
2589 (when (and (eq def 'undo-all)
2590 (null (zerop num-replacements)))
2591 (message "Undid %d %s" num-replacements
2592 (if (= num-replacements 1)
2593 "replacement"
2594 "replacements"))
2595 (ding 'no-terminate)
2596 (sit-for 1)))
2597 (setq replaced nil last-was-undo t)))
2598 ((eq def 'act)
2599 (or replaced
2600 (setq noedit
2601 (replace-match-maybe-edit
2602 next-replacement nocasify literal
2603 noedit real-match-data backward)
2604 replace-count (1+ replace-count)))
2605 (setq done t replaced t))
2606 ((eq def 'act-and-exit)
2607 (or replaced
2608 (setq noedit
2609 (replace-match-maybe-edit
2610 next-replacement nocasify literal
2611 noedit real-match-data backward)
2612 replace-count (1+ replace-count)))
2613 (setq keep-going nil)
2614 (setq done t replaced t))
2615 ((eq def 'act-and-show)
2616 (if (not replaced)
2617 (setq noedit
2618 (replace-match-maybe-edit
2619 next-replacement nocasify literal
2620 noedit real-match-data backward)
2621 replace-count (1+ replace-count)
2622 real-match-data (replace-match-data
2623 t real-match-data)
2624 replaced t)))
2625 ((or (eq def 'automatic) (eq def 'automatic-all))
2626 (or replaced
2627 (setq noedit
2628 (replace-match-maybe-edit
2629 next-replacement nocasify literal
2630 noedit real-match-data backward)
2631 replace-count (1+ replace-count)))
2632 (setq done t query-flag nil replaced t)
2633 (if (eq def 'automatic-all) (setq multi-buffer t)))
2634 ((eq def 'skip)
2635 (setq done t))
2636 ((eq def 'recenter)
2637 ;; `this-command' has the value `query-replace',
2638 ;; so we need to bind it to `recenter-top-bottom'
2639 ;; to allow it to detect a sequence of `C-l'.
2640 (let ((this-command 'recenter-top-bottom)
2641 (last-command 'recenter-top-bottom))
2642 (recenter-top-bottom)))
2643 ((eq def 'edit)
2644 (let ((opos (point-marker)))
2645 (setq real-match-data (replace-match-data
2646 nil real-match-data
2647 real-match-data))
2648 (goto-char (match-beginning 0))
2649 (save-excursion
2650 (save-window-excursion
2651 (recursive-edit)))
2652 (goto-char opos)
2653 (set-marker opos nil))
2654 ;; Before we make the replacement,
2655 ;; decide whether the search string
2656 ;; can match again just after this match.
2657 (if (and regexp-flag nonempty-match)
2658 (setq match-again (and (looking-at search-string)
2659 (match-data)))))
2660 ;; Edit replacement.
2661 ((eq def 'edit-replacement)
2662 (setq real-match-data (replace-match-data
2663 nil real-match-data
2664 real-match-data)
2665 next-replacement
2666 (read-string "Edit replacement string: "
2667 next-replacement)
2668 noedit nil)
2669 (if replaced
2670 (set-match-data real-match-data)
2671 (setq noedit
2672 (replace-match-maybe-edit
2673 next-replacement nocasify literal noedit
2674 real-match-data backward)
2675 replaced t))
2676 (setq done t))
2678 ((eq def 'delete-and-edit)
2679 (replace-match "" t t)
2680 (setq real-match-data (replace-match-data
2681 nil real-match-data))
2682 (replace-dehighlight)
2683 (save-excursion (recursive-edit))
2684 (setq replaced t))
2685 ;; Note: we do not need to treat `exit-prefix'
2686 ;; specially here, since we reread
2687 ;; any unrecognized character.
2689 (setq this-command 'mode-exited)
2690 (setq keep-going nil)
2691 (setq unread-command-events
2692 (append (listify-key-sequence key)
2693 unread-command-events))
2694 (setq done t)))
2695 (when query-replace-lazy-highlight
2696 ;; Force lazy rehighlighting only after replacements.
2697 (if (not (memq def '(skip backup)))
2698 (setq isearch-lazy-highlight-last-string nil)))
2699 (unless (eq def 'recenter)
2700 ;; Reset recenter cycling order to initial position.
2701 (setq recenter-last-op nil)))
2702 ;; Record previous position for ^ when we move on.
2703 ;; Change markers to numbers in the match data
2704 ;; since lots of markers slow down editing.
2705 (push (list (point) replaced
2706 ;;; If the replacement has already happened, all we need is the
2707 ;;; current match start and end. We could get this with a trivial
2708 ;;; match like
2709 ;;; (save-excursion (goto-char (match-beginning 0))
2710 ;;; (search-forward (match-string 0))
2711 ;;; (match-data t))
2712 ;;; if we really wanted to avoid manually constructing match data.
2713 ;;; Adding current-buffer is necessary so that match-data calls can
2714 ;;; return markers which are appropriate for editing.
2715 (if replaced
2716 (list
2717 (match-beginning 0)
2718 (match-end 0)
2719 (current-buffer))
2720 (match-data t))
2721 search-string-replaced
2722 next-replacement-replaced)
2723 stack)
2724 (setq next-replacement-replaced nil
2725 search-string-replaced nil))))))
2726 (replace-dehighlight))
2727 (or unread-command-events
2728 (message "Replaced %d occurrence%s%s"
2729 replace-count
2730 (if (= replace-count 1) "" "s")
2731 (if (> (+ skip-read-only-count
2732 skip-filtered-count
2733 skip-invisible-count) 0)
2734 (format " (skipped %s)"
2735 (mapconcat
2736 'identity
2737 (delq nil (list
2738 (if (> skip-read-only-count 0)
2739 (format "%s read-only"
2740 skip-read-only-count))
2741 (if (> skip-invisible-count 0)
2742 (format "%s invisible"
2743 skip-invisible-count))
2744 (if (> skip-filtered-count 0)
2745 (format "%s filtered out"
2746 skip-filtered-count))))
2747 ", "))
2748 "")))
2749 (or (and keep-going stack) multi-buffer)))
2751 (provide 'replace)
2753 ;;; replace.el ends here