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