* lisp/calendar/diary-lib.el (diary-remind): Fix bug#30455.
[emacs.git] / lisp / replace.el
blobc28c9b36f055cd77c48da5b945fe9ad8e9b99ae1
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--region-start-line nil)
1391 (defvar occur--orig-line nil)
1392 (defvar occur--final-pos nil)
1394 (defun occur (regexp &optional nlines region)
1395 "Show all lines in the current buffer containing a match for REGEXP.
1396 If a match spreads across multiple lines, all those lines are shown.
1398 Each match is extended to include complete lines. Only non-overlapping
1399 matches are considered. (Note that extending matches to complete
1400 lines could cause some of the matches to overlap; if so, they will not
1401 be shown as separate matches.)
1403 Each line is displayed with NLINES lines before and after, or -NLINES
1404 before if NLINES is negative.
1405 NLINES defaults to `list-matching-lines-default-context-lines'.
1406 Interactively it is the prefix arg.
1408 Optional arg REGION, if non-nil, mean restrict search to the
1409 specified region. Otherwise search the entire buffer.
1410 REGION must be a list of (START . END) positions as returned by
1411 `region-bounds'.
1413 The lines are shown in a buffer named `*Occur*'.
1414 It serves as a menu to find any of the occurrences in this buffer.
1415 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1416 If `list-matching-lines-jump-to-current-line' is non-nil, then show
1417 the current line highlighted with `list-matching-lines-current-line-face'
1418 and set point at the first match after such line.
1420 If REGEXP contains upper case characters (excluding those preceded by `\\')
1421 and `search-upper-case' is non-nil, the matching is case-sensitive.
1423 When NLINES is a string or when the function is called
1424 interactively with prefix argument without a number (`C-u' alone
1425 as prefix) the matching strings are collected into the `*Occur*'
1426 buffer by using NLINES as a replacement regexp. NLINES may
1427 contain \\& and \\N which convention follows `replace-match'.
1428 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1429 \"\\1\" for NLINES collects all the function names in a lisp
1430 program. When there is no parenthesized subexpressions in REGEXP
1431 the entire match is collected. In any case the searched buffer
1432 is not modified."
1433 (interactive
1434 (nconc (occur-read-primary-args)
1435 (and (use-region-p) (list (region-bounds)))))
1436 (let* ((start (and (caar region) (max (caar region) (point-min))))
1437 (end (and (cdar region) (min (cdar region) (point-max))))
1438 (in-region-p (or start end)))
1439 (when in-region-p
1440 (or start (setq start (point-min)))
1441 (or end (setq end (point-max))))
1442 (let ((occur--region-start start)
1443 (occur--region-end end)
1444 (occur--region-start-line
1445 (and in-region-p
1446 (line-number-at-pos (min start end))))
1447 (occur--orig-line
1448 (line-number-at-pos (point))))
1449 (save-excursion ; If no matches `occur-1' doesn't restore the point.
1450 (and in-region-p (narrow-to-region
1451 (save-excursion (goto-char start) (line-beginning-position))
1452 (save-excursion (goto-char end) (line-end-position))))
1453 (occur-1 regexp nlines (list (current-buffer)))
1454 (and in-region-p (widen))))))
1456 (defvar ido-ignore-item-temp-list)
1458 (defun multi-occur (bufs regexp &optional nlines)
1459 "Show all lines in buffers BUFS containing a match for REGEXP.
1460 This function acts on multiple buffers; otherwise, it is exactly like
1461 `occur'. When you invoke this command interactively, you must specify
1462 the buffer names that you want, one by one.
1463 See also `multi-occur-in-matching-buffers'."
1464 (interactive
1465 (cons
1466 (let* ((bufs (list (read-buffer "First buffer to search: "
1467 (current-buffer) t)))
1468 (buf nil)
1469 (ido-ignore-item-temp-list bufs))
1470 (while (not (string-equal
1471 (setq buf (read-buffer
1472 (if (eq read-buffer-function #'ido-read-buffer)
1473 "Next buffer to search (C-j to end): "
1474 "Next buffer to search (RET to end): ")
1475 nil t))
1476 ""))
1477 (cl-pushnew buf bufs)
1478 (setq ido-ignore-item-temp-list bufs))
1479 (nreverse (mapcar #'get-buffer bufs)))
1480 (occur-read-primary-args)))
1481 (occur-1 regexp nlines bufs))
1483 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1484 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1485 Normally BUFREGEXP matches against each buffer's visited file name,
1486 but if you specify a prefix argument, it matches against the buffer name.
1487 See also `multi-occur'."
1488 (interactive
1489 (cons
1490 (let* ((default (car regexp-history))
1491 (input
1492 (read-regexp
1493 (if current-prefix-arg
1494 "List lines in buffers whose names match regexp: "
1495 "List lines in buffers whose filenames match regexp: "))))
1496 (if (equal input "")
1497 default
1498 input))
1499 (occur-read-primary-args)))
1500 (when bufregexp
1501 (occur-1 regexp nil
1502 (delq nil
1503 (mapcar (lambda (buf)
1504 (when (if allbufs
1505 (string-match bufregexp
1506 (buffer-name buf))
1507 (and (buffer-file-name buf)
1508 (string-match bufregexp
1509 (buffer-file-name buf))))
1510 buf))
1511 (buffer-list))))))
1513 (defun occur-regexp-descr (regexp)
1514 (format " for %s\"%s\""
1515 (or (get-text-property 0 'isearch-regexp-function-descr regexp)
1517 (if (get-text-property 0 'isearch-string regexp)
1518 (propertize
1519 (query-replace-descr
1520 (get-text-property 0 'isearch-string regexp))
1521 'help-echo regexp)
1522 (query-replace-descr regexp))))
1524 (defun occur-1 (regexp nlines bufs &optional buf-name)
1525 (unless (and regexp (not (equal regexp "")))
1526 (error "Occur doesn't work with the empty regexp"))
1527 (unless buf-name
1528 (setq buf-name "*Occur*"))
1529 (let (occur-buf
1530 (active-bufs (delq nil (mapcar #'(lambda (buf)
1531 (when (buffer-live-p buf) buf))
1532 bufs))))
1533 ;; Handle the case where one of the buffers we're searching is the
1534 ;; output buffer. Just rename it.
1535 (when (member buf-name (mapcar 'buffer-name active-bufs))
1536 (with-current-buffer (get-buffer buf-name)
1537 (rename-uniquely)))
1539 ;; Now find or create the output buffer.
1540 ;; If we just renamed that buffer, we will make a new one here.
1541 (setq occur-buf (get-buffer-create buf-name))
1543 (with-current-buffer occur-buf
1544 (if (stringp nlines)
1545 (fundamental-mode) ;; This is for collect operation.
1546 (occur-mode))
1547 (let ((inhibit-read-only t)
1548 ;; Don't generate undo entries for creation of the initial contents.
1549 (buffer-undo-list t)
1550 (occur--final-pos nil))
1551 (erase-buffer)
1552 (let ((count
1553 (if (stringp nlines)
1554 ;; Treat nlines as a regexp to collect.
1555 (let ((bufs active-bufs)
1556 (count 0))
1557 (while bufs
1558 (with-current-buffer (car bufs)
1559 (save-excursion
1560 (goto-char (point-min))
1561 (while (re-search-forward regexp nil t)
1562 ;; Insert the replacement regexp.
1563 (let ((str (match-substitute-replacement nlines)))
1564 (if str
1565 (with-current-buffer occur-buf
1566 (insert str)
1567 (setq count (1+ count))
1568 (or (zerop (current-column))
1569 (insert "\n"))))))))
1570 (setq bufs (cdr bufs)))
1571 count)
1572 ;; Perform normal occur.
1573 (occur-engine
1574 regexp active-bufs occur-buf
1575 (or nlines list-matching-lines-default-context-lines)
1576 (if (and case-fold-search search-upper-case)
1577 (isearch-no-upper-case-p regexp t)
1578 case-fold-search)
1579 list-matching-lines-buffer-name-face
1580 (if (face-differs-from-default-p list-matching-lines-prefix-face)
1581 list-matching-lines-prefix-face)
1582 list-matching-lines-face
1583 (not (eq occur-excluded-properties t))))))
1584 (let* ((bufcount (length active-bufs))
1585 (diff (- (length bufs) bufcount)))
1586 (message "Searched %d buffer%s%s; %s match%s%s"
1587 bufcount (if (= bufcount 1) "" "s")
1588 (if (zerop diff) "" (format " (%d killed)" diff))
1589 (if (zerop count) "no" (format "%d" count))
1590 (if (= count 1) "" "es")
1591 ;; Don't display regexp if with remaining text
1592 ;; it is longer than window-width.
1593 (if (> (+ (length (or (get-text-property 0 'isearch-string regexp)
1594 regexp))
1596 (window-width))
1597 "" (occur-regexp-descr regexp))))
1598 (setq occur-revert-arguments (list regexp nlines bufs))
1599 (if (= count 0)
1600 (kill-buffer occur-buf)
1601 (display-buffer occur-buf)
1602 (when occur--final-pos
1603 (set-window-point
1604 (get-buffer-window occur-buf 'all-frames)
1605 occur--final-pos))
1606 (setq next-error-last-buffer occur-buf)
1607 (setq buffer-read-only t)
1608 (set-buffer-modified-p nil)
1609 (run-hooks 'occur-hook)))))))
1611 (defun occur-engine (regexp buffers out-buf nlines case-fold
1612 title-face prefix-face match-face keep-props)
1613 (with-current-buffer out-buf
1614 (let ((global-lines 0) ;; total count of matching lines
1615 (global-matches 0) ;; total count of matches
1616 (coding nil)
1617 (case-fold-search case-fold)
1618 (in-region-p (and occur--region-start occur--region-end))
1619 (multi-occur-p (cdr buffers)))
1620 ;; Map over all the buffers
1621 (dolist (buf buffers)
1622 (when (buffer-live-p buf)
1623 (let ((lines 0) ;; count of matching lines
1624 (matches 0) ;; count of matches
1625 (curr-line ;; line count
1626 (or occur--region-start-line 1))
1627 (orig-line occur--orig-line)
1628 (orig-line-shown-p)
1629 (prev-line nil) ;; line number of prev match endpt
1630 (prev-after-lines nil) ;; context lines of prev match
1631 (matchbeg 0)
1632 (origpt nil)
1633 (begpt nil)
1634 (endpt nil)
1635 (marker nil)
1636 (curstring "")
1637 (ret nil)
1638 (inhibit-field-text-motion t)
1639 (headerpt (with-current-buffer out-buf (point))))
1640 (with-current-buffer buf
1641 ;; The following binding is for when case-fold-search
1642 ;; has a local binding in the original buffer, in which
1643 ;; case we cannot bind it globally and let that have
1644 ;; effect in every buffer we search.
1645 (let ((case-fold-search case-fold))
1646 (or coding
1647 ;; Set CODING only if the current buffer locally
1648 ;; binds buffer-file-coding-system.
1649 (not (local-variable-p 'buffer-file-coding-system))
1650 (setq coding buffer-file-coding-system))
1651 (save-excursion
1652 (goto-char (point-min)) ;; begin searching in the buffer
1653 (while (not (eobp))
1654 (setq origpt (point))
1655 (when (setq endpt (re-search-forward regexp nil t))
1656 (setq lines (1+ lines)) ;; increment matching lines count
1657 (setq matchbeg (match-beginning 0))
1658 ;; Get beginning of first match line and end of the last.
1659 (save-excursion
1660 (goto-char matchbeg)
1661 (setq begpt (line-beginning-position))
1662 (goto-char endpt)
1663 (setq endpt (line-end-position)))
1664 ;; Sum line numbers up to the first match line.
1665 (setq curr-line (+ curr-line (count-lines origpt begpt)))
1666 (setq marker (make-marker))
1667 (set-marker marker matchbeg)
1668 (setq curstring (occur-engine-line begpt endpt keep-props))
1669 ;; Highlight the matches
1670 (let ((len (length curstring))
1671 (start 0))
1672 ;; Count empty lines that don't use next loop (Bug#22062).
1673 (when (zerop len)
1674 (setq matches (1+ matches)))
1675 (when (and list-matching-lines-jump-to-current-line
1676 (not multi-occur-p))
1677 (when (= curr-line orig-line)
1678 (add-face-text-property
1679 0 len list-matching-lines-current-line-face nil curstring)
1680 (add-text-properties 0 len '(current-line t) curstring))
1681 (when (and (>= orig-line (- curr-line nlines))
1682 (<= orig-line (+ curr-line nlines)))
1683 ;; Shown either here or will be shown by occur-context-lines
1684 (setq orig-line-shown-p t)))
1685 (while (and (< start len)
1686 (string-match regexp curstring start))
1687 (setq matches (1+ matches))
1688 (add-text-properties
1689 (match-beginning 0) (match-end 0)
1690 '(occur-match t) curstring)
1691 (when match-face
1692 ;; Add `match-face' to faces copied from the buffer.
1693 (add-face-text-property
1694 (match-beginning 0) (match-end 0)
1695 match-face nil curstring))
1696 ;; Avoid infloop (Bug#7593).
1697 (let ((end (match-end 0)))
1698 (setq start (if (= start end) (1+ start) end)))))
1699 ;; Generate the string to insert for this match
1700 (let* ((match-prefix
1701 ;; Using 7 digits aligns tabs properly.
1702 (apply #'propertize (format "%7d:" curr-line)
1703 (append
1704 (when prefix-face
1705 `(font-lock-face ,prefix-face))
1706 `(occur-prefix t mouse-face (highlight)
1707 ;; Allow insertion of text
1708 ;; at the end of the prefix
1709 ;; (for Occur Edit mode).
1710 front-sticky t
1711 rear-nonsticky t
1712 occur-target ,marker
1713 follow-link t
1714 help-echo "mouse-2: go to this occurrence"))))
1715 (match-str
1716 ;; We don't put `mouse-face' on the newline,
1717 ;; because that loses. And don't put it
1718 ;; on context lines to reduce flicker.
1719 (propertize curstring 'mouse-face (list 'highlight)
1720 'occur-target marker
1721 'follow-link t
1722 'help-echo
1723 "mouse-2: go to this occurrence"))
1724 (out-line
1725 (concat
1726 match-prefix
1727 ;; Add non-numeric prefix to all non-first lines
1728 ;; of multi-line matches.
1729 (replace-regexp-in-string
1730 "\n"
1731 (if prefix-face
1732 (propertize
1733 "\n :" 'font-lock-face prefix-face)
1734 "\n :")
1735 match-str)
1736 ;; Add marker at eol, but no mouse props.
1737 (propertize "\n" 'occur-target marker)))
1738 (data
1739 (if (= nlines 0)
1740 ;; The simple display style
1741 out-line
1742 ;; The complex multi-line display style.
1743 (setq ret (occur-context-lines
1744 out-line nlines keep-props begpt
1745 endpt curr-line prev-line
1746 prev-after-lines prefix-face
1747 orig-line multi-occur-p))
1748 ;; Set first elem of the returned list to `data',
1749 ;; and the second elem to `prev-after-lines'.
1750 (setq prev-after-lines (nth 1 ret))
1751 (nth 0 ret)))
1752 (orig-line-str
1753 (when (and list-matching-lines-jump-to-current-line
1754 (null orig-line-shown-p)
1755 (> curr-line orig-line))
1756 (setq orig-line-shown-p t)
1757 (save-excursion
1758 (goto-char (point-min))
1759 (forward-line (- orig-line (or occur--region-start-line 1)))
1760 (occur-engine-line (line-beginning-position)
1761 (line-end-position) keep-props)))))
1762 ;; Actually insert the match display data
1763 (with-current-buffer out-buf
1764 (when orig-line-str
1765 (add-face-text-property
1766 0 (length orig-line-str)
1767 list-matching-lines-current-line-face nil orig-line-str)
1768 (add-text-properties 0 (length orig-line-str)
1769 '(current-line t) orig-line-str)
1770 (insert (car (occur-engine-add-prefix
1771 (list orig-line-str) prefix-face))))
1772 (insert data)))
1773 (goto-char endpt))
1774 (if endpt
1775 (progn
1776 ;; Sum line numbers between first and last match lines.
1777 (setq curr-line (+ curr-line (count-lines begpt endpt)
1778 ;; Add 1 for empty last match line
1779 ;; since count-lines returns one
1780 ;; line less.
1781 (if (and (bolp) (eolp)) 1 0)))
1782 ;; On to the next match...
1783 (forward-line 1))
1784 (goto-char (point-max)))
1785 (setq prev-line (1- curr-line)))
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 (and list-matching-lines-jump-to-current-line
1792 (null orig-line-shown-p))
1793 (setq orig-line-shown-p t)
1794 (let ((orig-line-str
1795 (save-excursion
1796 (goto-char (point-min))
1797 (forward-line (- orig-line (or occur--region-start-line 1)))
1798 (occur-engine-line (line-beginning-position)
1799 (line-end-position) keep-props))))
1800 (add-face-text-property
1801 0 (length orig-line-str)
1802 list-matching-lines-current-line-face nil orig-line-str)
1803 (add-text-properties 0 (length orig-line-str)
1804 '(current-line t) orig-line-str)
1805 (with-current-buffer out-buf
1806 (insert (car (occur-engine-add-prefix
1807 (list orig-line-str) prefix-face))))))))
1808 (when (not (zerop lines)) ;; is the count zero?
1809 (setq global-lines (+ global-lines lines)
1810 global-matches (+ global-matches matches))
1811 (with-current-buffer out-buf
1812 (goto-char headerpt)
1813 (let ((beg (point))
1814 end)
1815 (insert (propertize
1816 (format "%d match%s%s%s in buffer: %s%s\n"
1817 matches (if (= matches 1) "" "es")
1818 ;; Don't display the same number of lines
1819 ;; and matches in case of 1 match per line.
1820 (if (= lines matches)
1821 "" (format " in %d line%s"
1822 lines
1823 (if (= lines 1) "" "s")))
1824 ;; Don't display regexp for multi-buffer.
1825 (if (> (length buffers) 1)
1826 "" (occur-regexp-descr regexp))
1827 (buffer-name buf)
1828 (if in-region-p
1829 (format " within region: %d-%d"
1830 occur--region-start
1831 occur--region-end)
1832 ""))
1833 'read-only t))
1834 (setq end (point))
1835 (add-text-properties beg end `(occur-title ,buf))
1836 (when title-face
1837 (add-face-text-property beg end title-face))
1838 (goto-char (if (and list-matching-lines-jump-to-current-line
1839 (not multi-occur-p))
1840 (setq occur--final-pos
1841 (and (goto-char (point-max))
1842 (or (previous-single-property-change (point) 'current-line)
1843 (point-max))))
1844 (point-min))))))))))
1845 ;; Display total match count and regexp for multi-buffer.
1846 (when (and (not (zerop global-lines)) (> (length buffers) 1))
1847 (goto-char (point-min))
1848 (let ((beg (point))
1849 end)
1850 (insert (format "%d match%s%s total%s:\n"
1851 global-matches (if (= global-matches 1) "" "es")
1852 ;; Don't display the same number of lines
1853 ;; and matches in case of 1 match per line.
1854 (if (= global-lines global-matches)
1855 "" (format " in %d line%s"
1856 global-lines (if (= global-lines 1) "" "s")))
1857 (occur-regexp-descr regexp)))
1858 (setq end (point))
1859 (when title-face
1860 (add-face-text-property beg end title-face)))
1861 (goto-char (point-min)))
1862 (if coding
1863 ;; CODING is buffer-file-coding-system of the first buffer
1864 ;; that locally binds it. Let's use it also for the output
1865 ;; buffer.
1866 (set-buffer-file-coding-system coding))
1867 ;; Return the number of matches
1868 global-matches)))
1870 (defun occur-engine-line (beg end &optional keep-props)
1871 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1872 (text-property-not-all beg end 'fontified t))
1873 (if (fboundp 'jit-lock-fontify-now)
1874 (jit-lock-fontify-now beg end)))
1875 (if (and keep-props (not (eq occur-excluded-properties t)))
1876 (let ((str (buffer-substring beg end)))
1877 (remove-list-of-text-properties
1878 0 (length str) occur-excluded-properties str)
1879 str)
1880 (buffer-substring-no-properties beg end)))
1882 (defun occur-engine-add-prefix (lines &optional prefix-face)
1883 (mapcar
1884 #'(lambda (line)
1885 (concat (if prefix-face
1886 (propertize " :" 'font-lock-face prefix-face)
1887 " :")
1888 line "\n"))
1889 lines))
1891 (defun occur-accumulate-lines (count &optional keep-props pt)
1892 (save-excursion
1893 (when pt
1894 (goto-char pt))
1895 (let ((forwardp (> count 0))
1896 result beg end moved)
1897 (while (not (or (zerop count)
1898 (if forwardp
1899 (eobp)
1900 (and (bobp) (not moved)))))
1901 (setq count (+ count (if forwardp -1 1)))
1902 (setq beg (line-beginning-position)
1903 end (line-end-position))
1904 (push (occur-engine-line beg end keep-props) result)
1905 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1906 (nreverse result))))
1908 ;; Generate context display for occur.
1909 ;; OUT-LINE is the line where the match is.
1910 ;; NLINES and KEEP-PROPS are args to occur-engine.
1911 ;; CURR-LINE is line count of the current match,
1912 ;; PREV-LINE is line count of the previous match,
1913 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1914 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1915 ;; then concatenate them all together.
1916 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1917 curr-line prev-line prev-after-lines
1918 &optional prefix-face
1919 orig-line multi-occur-p)
1920 ;; Find after- and before-context lines of the current match.
1921 (let ((before-lines
1922 (nreverse (cdr (occur-accumulate-lines
1923 (- (1+ (abs nlines))) keep-props begpt))))
1924 (after-lines
1925 (cdr (occur-accumulate-lines
1926 (1+ nlines) keep-props endpt)))
1927 separator)
1929 (when (and list-matching-lines-jump-to-current-line
1930 (not multi-occur-p))
1931 (when (and (>= orig-line (- curr-line nlines))
1932 (< orig-line curr-line))
1933 (let ((curstring (nth (- (length before-lines) (- curr-line orig-line)) before-lines)))
1934 (add-face-text-property
1935 0 (length curstring)
1936 list-matching-lines-current-line-face nil curstring)
1937 (add-text-properties 0 (length curstring)
1938 '(current-line t) curstring)))
1939 (when (and (<= orig-line (+ curr-line nlines))
1940 (> orig-line curr-line))
1941 (let ((curstring (nth (- orig-line curr-line 1) after-lines)))
1942 (add-face-text-property
1943 0 (length curstring)
1944 list-matching-lines-current-line-face nil curstring)
1945 (add-text-properties 0 (length curstring)
1946 '(current-line t) curstring))))
1948 ;; Combine after-lines of the previous match
1949 ;; with before-lines of the current match.
1951 (when prev-after-lines
1952 ;; Don't overlap prev after-lines with current before-lines.
1953 (if (>= (+ prev-line (length prev-after-lines))
1954 (- curr-line (length before-lines)))
1955 (setq prev-after-lines
1956 (butlast prev-after-lines
1957 (- (length prev-after-lines)
1958 (- curr-line prev-line (length before-lines) 1))))
1959 ;; Separate non-overlapping context lines with a dashed line.
1960 (setq separator "-------\n")))
1962 (when prev-line
1963 ;; Don't overlap current before-lines with previous match line.
1964 (if (<= (- curr-line (length before-lines))
1965 prev-line)
1966 (setq before-lines
1967 (nthcdr (- (length before-lines)
1968 (- curr-line prev-line 1))
1969 before-lines))
1970 ;; Separate non-overlapping before-context lines.
1971 (unless (> nlines 0)
1972 (setq separator "-------\n"))))
1974 (list
1975 ;; Return a list where the first element is the output line.
1976 (apply #'concat
1977 (append
1978 (if prev-after-lines
1979 (occur-engine-add-prefix prev-after-lines prefix-face))
1980 (if separator
1981 (list (if prefix-face
1982 (propertize separator 'font-lock-face prefix-face)
1983 separator)))
1984 (occur-engine-add-prefix before-lines prefix-face)
1985 (list out-line)))
1986 ;; And the second element is the list of context after-lines.
1987 (if (> nlines 0) after-lines))))
1990 ;; It would be nice to use \\[...], but there is no reasonable way
1991 ;; to make that display both SPC and Y.
1992 (defconst query-replace-help
1993 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1994 RET or `q' to exit, Period to replace one match and exit,
1995 Comma to replace but not move point immediately,
1996 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1997 C-w to delete match and recursive edit,
1998 C-l to clear the screen, redisplay, and offer same replacement again,
1999 ! to replace all remaining matches in this buffer with no more questions,
2000 ^ to move point back to previous match,
2001 u to undo previous replacement,
2002 U to undo all replacements,
2003 E to edit the replacement string.
2004 In multi-buffer replacements type `Y' to replace all remaining
2005 matches in all remaining buffers with no more questions,
2006 `N' to skip to the next buffer without replacing remaining matches
2007 in the current buffer."
2008 "Help message while in `query-replace'.")
2010 (defvar query-replace-map
2011 (let ((map (make-sparse-keymap)))
2012 (define-key map " " 'act)
2013 (define-key map "\d" 'skip)
2014 (define-key map [delete] 'skip)
2015 (define-key map [backspace] 'skip)
2016 (define-key map "y" 'act)
2017 (define-key map "n" 'skip)
2018 (define-key map "Y" 'act)
2019 (define-key map "N" 'skip)
2020 (define-key map "e" 'edit-replacement)
2021 (define-key map "E" 'edit-replacement)
2022 (define-key map "," 'act-and-show)
2023 (define-key map "q" 'exit)
2024 (define-key map "\r" 'exit)
2025 (define-key map [return] 'exit)
2026 (define-key map "." 'act-and-exit)
2027 (define-key map "\C-r" 'edit)
2028 (define-key map "\C-w" 'delete-and-edit)
2029 (define-key map "\C-l" 'recenter)
2030 (define-key map "!" 'automatic)
2031 (define-key map "^" 'backup)
2032 (define-key map "u" 'undo)
2033 (define-key map "U" 'undo-all)
2034 (define-key map "\C-h" 'help)
2035 (define-key map [f1] 'help)
2036 (define-key map [help] 'help)
2037 (define-key map "?" 'help)
2038 (define-key map "\C-g" 'quit)
2039 (define-key map "\C-]" 'quit)
2040 (define-key map "\C-v" 'scroll-up)
2041 (define-key map "\M-v" 'scroll-down)
2042 (define-key map [next] 'scroll-up)
2043 (define-key map [prior] 'scroll-down)
2044 (define-key map [?\C-\M-v] 'scroll-other-window)
2045 (define-key map [M-next] 'scroll-other-window)
2046 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
2047 (define-key map [M-prior] 'scroll-other-window-down)
2048 ;; Binding ESC would prohibit the M-v binding. Instead, callers
2049 ;; should check for ESC specially.
2050 ;; (define-key map "\e" 'exit-prefix)
2051 (define-key map [escape] 'exit-prefix)
2052 map)
2053 "Keymap of responses to questions posed by commands like `query-replace'.
2054 The \"bindings\" in this map are not commands; they are answers.
2055 The valid answers include `act', `skip', `act-and-show',
2056 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
2057 `scroll-down', `scroll-other-window', `scroll-other-window-down',
2058 `edit', `edit-replacement', `delete-and-edit', `automatic',
2059 `backup', `undo', `undo-all', `quit', and `help'.
2061 This keymap is used by `y-or-n-p' as well as `query-replace'.")
2063 (defvar multi-query-replace-map
2064 (let ((map (make-sparse-keymap)))
2065 (set-keymap-parent map query-replace-map)
2066 (define-key map "Y" 'automatic-all)
2067 (define-key map "N" 'exit-current)
2068 map)
2069 "Keymap that defines additional bindings for multi-buffer replacements.
2070 It extends its parent map `query-replace-map' with new bindings to
2071 operate on a set of buffers/files. The difference with its parent map
2072 is the additional answers `automatic-all' to replace all remaining
2073 matches in all remaining buffers with no more questions, and
2074 `exit-current' to skip remaining matches in the current buffer
2075 and to continue with the next buffer in the sequence.")
2077 (defun replace-match-string-symbols (n)
2078 "Process a list (and any sub-lists), expanding certain symbols.
2079 Symbol Expands To
2080 N (match-string N) (where N is a string of digits)
2081 #N (string-to-number (match-string N))
2082 & (match-string 0)
2083 #& (string-to-number (match-string 0))
2084 # replace-count
2086 Note that these symbols must be preceded by a backslash in order to
2087 type them using Lisp syntax."
2088 (while (consp n)
2089 (cond
2090 ((consp (car n))
2091 (replace-match-string-symbols (car n))) ;Process sub-list
2092 ((symbolp (car n))
2093 (let ((name (symbol-name (car n))))
2094 (cond
2095 ((string-match "^[0-9]+$" name)
2096 (setcar n (list 'match-string (string-to-number name))))
2097 ((string-match "^#[0-9]+$" name)
2098 (setcar n (list 'string-to-number
2099 (list 'match-string
2100 (string-to-number (substring name 1))))))
2101 ((string= "&" name)
2102 (setcar n '(match-string 0)))
2103 ((string= "#&" name)
2104 (setcar n '(string-to-number (match-string 0))))
2105 ((string= "#" name)
2106 (setcar n 'replace-count))))))
2107 (setq n (cdr n))))
2109 (defun replace-eval-replacement (expression count)
2110 (let* ((replace-count count)
2111 (replacement
2112 (condition-case err
2113 (eval expression)
2114 (error
2115 (error "Error evaluating replacement expression: %S" err)))))
2116 (if (stringp replacement)
2117 replacement
2118 (prin1-to-string replacement t))))
2120 (defun replace-quote (replacement)
2121 "Quote a replacement string.
2122 This just doubles all backslashes in REPLACEMENT and
2123 returns the resulting string. If REPLACEMENT is not
2124 a string, it is first passed through `prin1-to-string'
2125 with the `noescape' argument set.
2127 `match-data' is preserved across the call."
2128 (save-match-data
2129 (replace-regexp-in-string "\\\\" "\\\\"
2130 (if (stringp replacement)
2131 replacement
2132 (prin1-to-string replacement t))
2133 t t)))
2135 (defun replace-loop-through-replacements (data count)
2136 ;; DATA is a vector containing the following values:
2137 ;; 0 next-rotate-count
2138 ;; 1 repeat-count
2139 ;; 2 next-replacement
2140 ;; 3 replacements
2141 (if (= (aref data 0) count)
2142 (progn
2143 (aset data 0 (+ count (aref data 1)))
2144 (let ((next (cdr (aref data 2))))
2145 (aset data 2 (if (consp next) next (aref data 3))))))
2146 (car (aref data 2)))
2148 (defun replace-match-data (integers reuse &optional new)
2149 "Like `match-data', but markers in REUSE get invalidated.
2150 If NEW is non-nil, it is set and returned instead of fresh data,
2151 but coerced to the correct value of INTEGERS."
2152 (or (and new
2153 (progn
2154 (set-match-data new)
2155 (and (eq new reuse)
2156 (eq (null integers) (markerp (car reuse)))
2157 new)))
2158 (match-data integers reuse t)))
2160 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data
2161 &optional backward)
2162 "Make a replacement with `replace-match', editing `\\?'.
2163 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
2164 After possibly editing it (if `\\?' is present), NEWTEXT is also
2165 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
2166 is made (to save time).
2167 MATCH-DATA is used for the replacement, and is a data structure
2168 as returned from the `match-data' function.
2169 In case editing is done, it is changed to use markers. BACKWARD is
2170 used to reverse the replacement direction.
2172 The return value is non-nil if there has been no `\\?' or NOEDIT was
2173 passed in. If LITERAL is set, no checking is done, anyway."
2174 (unless (or literal noedit)
2175 (setq noedit t)
2176 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
2177 newtext)
2178 (setq newtext
2179 (read-string "Edit replacement string: "
2180 (prog1
2181 (cons
2182 (replace-match "" t t newtext 3)
2183 (1+ (match-beginning 3)))
2184 (setq match-data
2185 (replace-match-data
2186 nil match-data match-data))))
2187 noedit nil)))
2188 (set-match-data match-data)
2189 (replace-match newtext fixedcase literal)
2190 ;; `replace-match' leaves point at the end of the replacement text,
2191 ;; so move point to the beginning when replacing backward.
2192 (when backward (goto-char (nth 0 match-data)))
2193 noedit)
2195 (defvar replace-update-post-hook nil
2196 "Function(s) to call after query-replace has found a match in the buffer.")
2198 (defvar replace-search-function nil
2199 "Function to use when searching for strings to replace.
2200 It is used by `query-replace' and `replace-string', and is called
2201 with three arguments, as if it were `search-forward'.")
2203 (defvar replace-re-search-function nil
2204 "Function to use when searching for regexps to replace.
2205 It is used by `query-replace-regexp', `replace-regexp',
2206 `query-replace-regexp-eval', and `map-query-replace-regexp'.
2207 It is called with three arguments, as if it were
2208 `re-search-forward'.")
2210 (defun replace-search (search-string limit regexp-flag delimited-flag
2211 case-fold &optional backward)
2212 "Search for the next occurrence of SEARCH-STRING to replace."
2213 ;; Let-bind global isearch-* variables to values used
2214 ;; to search the next replacement. These let-bindings
2215 ;; should be effective both at the time of calling
2216 ;; `isearch-search-fun-default' and also at the
2217 ;; time of funcalling `search-function'.
2218 ;; These isearch-* bindings can't be placed higher
2219 ;; outside of this function because then another I-search
2220 ;; used after `recursive-edit' might override them.
2221 (let* ((isearch-regexp regexp-flag)
2222 (isearch-regexp-function (or delimited-flag
2223 (and replace-char-fold
2224 (not regexp-flag)
2225 #'char-fold-to-regexp)))
2226 (isearch-lax-whitespace
2227 replace-lax-whitespace)
2228 (isearch-regexp-lax-whitespace
2229 replace-regexp-lax-whitespace)
2230 (isearch-case-fold-search case-fold)
2231 (isearch-adjusted nil)
2232 (isearch-nonincremental t) ; don't use lax word mode
2233 (isearch-forward (not backward))
2234 (search-function
2235 (or (if regexp-flag
2236 replace-re-search-function
2237 replace-search-function)
2238 (isearch-search-fun-default))))
2239 (funcall search-function search-string limit t)))
2241 (defvar replace-overlay nil)
2243 (defun replace-highlight (match-beg match-end range-beg range-end
2244 search-string regexp-flag delimited-flag
2245 case-fold &optional backward)
2246 (if query-replace-highlight
2247 (if replace-overlay
2248 (move-overlay replace-overlay match-beg match-end (current-buffer))
2249 (setq replace-overlay (make-overlay match-beg match-end))
2250 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2251 (overlay-put replace-overlay 'face 'query-replace)))
2252 (if query-replace-lazy-highlight
2253 (let ((isearch-string search-string)
2254 (isearch-regexp regexp-flag)
2255 (isearch-regexp-function (or delimited-flag
2256 (and replace-char-fold
2257 (not regexp-flag)
2258 #'char-fold-to-regexp)))
2259 (isearch-lax-whitespace
2260 replace-lax-whitespace)
2261 (isearch-regexp-lax-whitespace
2262 replace-regexp-lax-whitespace)
2263 (isearch-case-fold-search case-fold)
2264 (isearch-forward (not backward))
2265 (isearch-other-end match-beg)
2266 (isearch-error nil))
2267 (isearch-lazy-highlight-new-loop range-beg range-end))))
2269 (defun replace-dehighlight ()
2270 (when replace-overlay
2271 (delete-overlay replace-overlay))
2272 (when query-replace-lazy-highlight
2273 (lazy-highlight-cleanup lazy-highlight-cleanup)
2274 (setq isearch-lazy-highlight-last-string nil))
2275 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2276 (isearch-clean-overlays))
2278 ;; A macro because we push STACK, i.e. a local var in `perform-replace'.
2279 (defmacro replace--push-stack (replaced search-str next-replace stack)
2280 (declare (indent 0) (debug (form form form gv-place)))
2281 `(push (list (point) ,replaced
2282 ;;; If the replacement has already happened, all we need is the
2283 ;;; current match start and end. We could get this with a trivial
2284 ;;; match like
2285 ;;; (save-excursion (goto-char (match-beginning 0))
2286 ;;; (search-forward (match-string 0))
2287 ;;; (match-data t))
2288 ;;; if we really wanted to avoid manually constructing match data.
2289 ;;; Adding current-buffer is necessary so that match-data calls can
2290 ;;; return markers which are appropriate for editing.
2291 (if ,replaced
2292 (list
2293 (match-beginning 0) (match-end 0) (current-buffer))
2294 (match-data t))
2295 ,search-str ,next-replace)
2296 ,stack))
2298 (defun perform-replace (from-string replacements
2299 query-flag regexp-flag delimited-flag
2300 &optional repeat-count map start end backward region-noncontiguous-p)
2301 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2302 Don't use this in your own program unless you want to query and set the mark
2303 just as `query-replace' does. Instead, write a simple loop like this:
2305 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2306 (replace-match \"foobar\" nil nil))
2308 which will run faster and probably do exactly what you want. Please
2309 see the documentation of `replace-match' to find out how to simulate
2310 `case-replace'.
2312 This function returns nil if and only if there were no matches to
2313 make, or the user didn't cancel the call.
2315 REPLACEMENTS is either a string, a list of strings, or a cons cell
2316 containing a function and its first argument. The function is
2317 called to generate each replacement like this:
2318 (funcall (car replacements) (cdr replacements) replace-count)
2319 It must return a string."
2320 (or map (setq map query-replace-map))
2321 (and query-flag minibuffer-auto-raise
2322 (raise-frame (window-frame (minibuffer-window))))
2323 (let* ((case-fold-search
2324 (if (and case-fold-search search-upper-case)
2325 (isearch-no-upper-case-p from-string regexp-flag)
2326 case-fold-search))
2327 (nocasify (not (and case-replace case-fold-search)))
2328 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2329 (search-string from-string)
2330 (real-match-data nil) ; The match data for the current match.
2331 (next-replacement nil)
2332 ;; This is non-nil if we know there is nothing for the user
2333 ;; to edit in the replacement.
2334 (noedit nil)
2335 (keep-going t)
2336 (stack nil)
2337 (search-string-replaced nil) ; last string matching `from-string'
2338 (next-replacement-replaced nil) ; replacement string
2339 ; (substituted regexp)
2340 (last-was-undo)
2341 (last-was-act-and-show)
2342 (update-stack t)
2343 (replace-count 0)
2344 (skip-read-only-count 0)
2345 (skip-filtered-count 0)
2346 (skip-invisible-count 0)
2347 (nonempty-match nil)
2348 (multi-buffer nil)
2349 (recenter-last-op nil) ; Start cycling order with initial position.
2351 ;; If non-nil, it is marker saying where in the buffer to stop.
2352 (limit nil)
2353 ;; Use local binding in add-function below.
2354 (isearch-filter-predicate isearch-filter-predicate)
2355 (region-bounds nil)
2357 ;; Data for the next match. If a cons, it has the same format as
2358 ;; (match-data); otherwise it is t if a match is possible at point.
2359 (match-again t)
2361 (message
2362 (if query-flag
2363 (apply 'propertize
2364 (substitute-command-keys
2365 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2366 minibuffer-prompt-properties))))
2368 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
2369 (when region-noncontiguous-p
2370 (setq region-bounds
2371 (mapcar (lambda (position)
2372 (cons (copy-marker (car position))
2373 (copy-marker (cdr position))))
2374 (funcall region-extract-function 'bounds)))
2375 (add-function :after-while isearch-filter-predicate
2376 (lambda (start end)
2377 (delq nil (mapcar
2378 (lambda (bounds)
2379 (and
2380 (>= start (car bounds))
2381 (<= start (cdr bounds))
2382 (>= end (car bounds))
2383 (<= end (cdr bounds))))
2384 region-bounds)))))
2386 ;; If region is active, in Transient Mark mode, operate on region.
2387 (if backward
2388 (when end
2389 (setq limit (copy-marker (min start end)))
2390 (goto-char (max start end))
2391 (deactivate-mark))
2392 (when start
2393 (setq limit (copy-marker (max start end)))
2394 (goto-char (min start end))
2395 (deactivate-mark)))
2397 ;; If last typed key in previous call of multi-buffer perform-replace
2398 ;; was `automatic-all', don't ask more questions in next files
2399 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2400 (setq query-flag nil multi-buffer t))
2402 (cond
2403 ((stringp replacements)
2404 (setq next-replacement replacements
2405 replacements nil))
2406 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2407 (or repeat-count (setq repeat-count 1))
2408 (setq replacements (cons 'replace-loop-through-replacements
2409 (vector repeat-count repeat-count
2410 replacements replacements)))))
2412 (when query-replace-lazy-highlight
2413 (setq isearch-lazy-highlight-last-string nil))
2415 (push-mark)
2416 (undo-boundary)
2417 (unwind-protect
2418 ;; Loop finding occurrences that perhaps should be replaced.
2419 (while (and keep-going
2420 (if backward
2421 (not (or (bobp) (and limit (<= (point) limit))))
2422 (not (or (eobp) (and limit (>= (point) limit)))))
2423 ;; Use the next match if it is already known;
2424 ;; otherwise, search for a match after moving forward
2425 ;; one char if progress is required.
2426 (setq real-match-data
2427 (cond ((consp match-again)
2428 (goto-char (if backward
2429 (nth 0 match-again)
2430 (nth 1 match-again)))
2431 (replace-match-data
2432 t real-match-data match-again))
2433 ;; MATCH-AGAIN non-nil means accept an
2434 ;; adjacent match.
2435 (match-again
2436 (and
2437 (replace-search search-string limit
2438 regexp-flag delimited-flag
2439 case-fold-search backward)
2440 ;; For speed, use only integers and
2441 ;; reuse the list used last time.
2442 (replace-match-data t real-match-data)))
2443 ((and (if backward
2444 (> (1- (point)) (point-min))
2445 (< (1+ (point)) (point-max)))
2446 (or (null limit)
2447 (if backward
2448 (> (1- (point)) limit)
2449 (< (1+ (point)) limit))))
2450 ;; If not accepting adjacent matches,
2451 ;; move one char to the right before
2452 ;; searching again. Undo the motion
2453 ;; if the search fails.
2454 (let ((opoint (point)))
2455 (forward-char (if backward -1 1))
2456 (if (replace-search search-string limit
2457 regexp-flag delimited-flag
2458 case-fold-search backward)
2459 (replace-match-data
2460 t real-match-data)
2461 (goto-char opoint)
2462 nil))))))
2464 ;; Record whether the match is nonempty, to avoid an infinite loop
2465 ;; repeatedly matching the same empty string.
2466 (setq nonempty-match
2467 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2469 ;; If the match is empty, record that the next one can't be
2470 ;; adjacent.
2472 ;; Otherwise, if matching a regular expression, do the next
2473 ;; match now, since the replacement for this match may
2474 ;; affect whether the next match is adjacent to this one.
2475 ;; If that match is empty, don't use it.
2476 (setq match-again
2477 (and nonempty-match
2478 (or (not regexp-flag)
2479 (and (if backward
2480 (looking-back search-string nil)
2481 (looking-at search-string))
2482 (let ((match (match-data)))
2483 (and (/= (nth 0 match) (nth 1 match))
2484 match))))))
2486 (cond
2487 ;; Optionally ignore matches that have a read-only property.
2488 ((not (or (not query-replace-skip-read-only)
2489 (not (text-property-not-all
2490 (nth 0 real-match-data) (nth 1 real-match-data)
2491 'read-only nil))))
2492 (setq skip-read-only-count (1+ skip-read-only-count)))
2493 ;; Optionally filter out matches.
2494 ((not (funcall isearch-filter-predicate
2495 (nth 0 real-match-data) (nth 1 real-match-data)))
2496 (setq skip-filtered-count (1+ skip-filtered-count)))
2497 ;; Optionally ignore invisible matches.
2498 ((not (or (eq search-invisible t)
2499 ;; Don't open overlays for automatic replacements.
2500 (and (not query-flag) search-invisible)
2501 ;; Open hidden overlays for interactive replacements.
2502 (not (isearch-range-invisible
2503 (nth 0 real-match-data) (nth 1 real-match-data)))))
2504 (setq skip-invisible-count (1+ skip-invisible-count)))
2506 ;; Calculate the replacement string, if necessary.
2507 (when replacements
2508 (set-match-data real-match-data)
2509 (setq next-replacement
2510 (funcall (car replacements) (cdr replacements)
2511 replace-count)))
2512 (if (not query-flag)
2513 (progn
2514 (unless (or literal noedit)
2515 (replace-highlight
2516 (nth 0 real-match-data) (nth 1 real-match-data)
2517 start end search-string
2518 regexp-flag delimited-flag case-fold-search backward))
2519 (setq noedit
2520 (replace-match-maybe-edit
2521 next-replacement nocasify literal
2522 noedit real-match-data backward)
2523 replace-count (1+ replace-count)))
2524 (undo-boundary)
2525 (let (done replaced key def)
2526 ;; Loop reading commands until one of them sets done,
2527 ;; which means it has finished handling this
2528 ;; occurrence. Any command that sets `done' should
2529 ;; leave behind proper match data for the stack.
2530 ;; Commands not setting `done' need to adjust
2531 ;; `real-match-data'.
2532 (while (not done)
2533 (set-match-data real-match-data)
2534 (run-hooks 'replace-update-post-hook) ; Before `replace-highlight'.
2535 (replace-highlight
2536 (match-beginning 0) (match-end 0)
2537 start end search-string
2538 regexp-flag delimited-flag case-fold-search backward)
2539 ;; Obtain the matched groups: needed only when
2540 ;; regexp-flag non nil.
2541 (when (and last-was-undo regexp-flag)
2542 (setq last-was-undo nil
2543 real-match-data
2544 (save-excursion
2545 (goto-char (match-beginning 0))
2546 (looking-at search-string)
2547 (match-data t real-match-data))))
2548 ;; Matched string and next-replacement-replaced
2549 ;; stored in stack.
2550 (setq search-string-replaced (buffer-substring-no-properties
2551 (match-beginning 0)
2552 (match-end 0))
2553 next-replacement-replaced
2554 (query-replace-descr
2555 (save-match-data
2556 (set-match-data real-match-data)
2557 (match-substitute-replacement
2558 next-replacement nocasify literal))))
2559 ;; Bind message-log-max so we don't fill up the
2560 ;; message log with a bunch of identical messages.
2561 (let ((message-log-max nil)
2562 (replacement-presentation
2563 (if query-replace-show-replacement
2564 (save-match-data
2565 (set-match-data real-match-data)
2566 (match-substitute-replacement next-replacement
2567 nocasify literal))
2568 next-replacement)))
2569 (message message
2570 (query-replace-descr from-string)
2571 (query-replace-descr replacement-presentation)))
2572 (setq key (read-event))
2573 ;; Necessary in case something happens during
2574 ;; read-event that clobbers the match data.
2575 (set-match-data real-match-data)
2576 (setq key (vector key))
2577 (setq def (lookup-key map key))
2578 ;; Restore the match data while we process the command.
2579 (cond ((eq def 'help)
2580 (with-output-to-temp-buffer "*Help*"
2581 (princ
2582 (concat "Query replacing "
2583 (if delimited-flag
2584 (or (and (symbolp delimited-flag)
2585 (get delimited-flag
2586 'isearch-message-prefix))
2587 "word ") "")
2588 (if regexp-flag "regexp " "")
2589 (if backward "backward " "")
2590 from-string " with "
2591 next-replacement ".\n\n"
2592 (substitute-command-keys
2593 query-replace-help)))
2594 (with-current-buffer standard-output
2595 (help-mode))))
2596 ((eq def 'exit)
2597 (setq keep-going nil)
2598 (setq done t))
2599 ((eq def 'exit-current)
2600 (setq multi-buffer t keep-going nil done t))
2601 ((eq def 'backup)
2602 (if stack
2603 (let ((elt (pop stack)))
2604 (goto-char (nth 0 elt))
2605 (setq replaced (nth 1 elt)
2606 real-match-data
2607 (replace-match-data
2608 t real-match-data
2609 (nth 2 elt))))
2610 (message "No previous match")
2611 (ding 'no-terminate)
2612 (sit-for 1)))
2613 ((or (eq def 'undo) (eq def 'undo-all))
2614 (if (null stack)
2615 (progn
2616 (message "Nothing to undo")
2617 (ding 'no-terminate)
2618 (sit-for 1))
2619 (let ((stack-idx 0)
2620 (stack-len (length stack))
2621 (num-replacements 0)
2622 search-string
2623 next-replacement)
2624 (while (and (< stack-idx stack-len)
2625 stack
2626 (or (null replaced) last-was-act-and-show))
2627 (let* ((elt (nth stack-idx stack)))
2628 (setq
2629 stack-idx (1+ stack-idx)
2630 replaced (nth 1 elt)
2631 ;; Bind swapped values
2632 ;; (search-string <--> replacement)
2633 search-string (nth (if replaced 4 3) elt)
2634 next-replacement (nth (if replaced 3 4) elt)
2635 search-string-replaced search-string
2636 next-replacement-replaced next-replacement
2637 last-was-act-and-show nil)
2639 (when (and (= stack-idx stack-len)
2640 (and (null replaced) (not last-was-act-and-show))
2641 (zerop num-replacements))
2642 (message "Nothing to undo")
2643 (ding 'no-terminate)
2644 (sit-for 1))
2646 (when replaced
2647 (setq stack (nthcdr stack-idx stack))
2648 (goto-char (nth 0 elt))
2649 (set-match-data (nth 2 elt))
2650 (setq real-match-data
2651 (save-excursion
2652 (goto-char (match-beginning 0))
2653 (looking-at search-string)
2654 (match-data t (nth 2 elt)))
2655 noedit
2656 (replace-match-maybe-edit
2657 next-replacement nocasify literal
2658 noedit real-match-data backward)
2659 replace-count (1- replace-count)
2660 real-match-data
2661 (save-excursion
2662 (goto-char (match-beginning 0))
2663 (looking-at next-replacement)
2664 (match-data t (nth 2 elt))))
2665 ;; Set replaced nil to keep in loop
2666 (when (eq def 'undo-all)
2667 (setq replaced nil
2668 stack-len (- stack-len stack-idx)
2669 stack-idx 0
2670 num-replacements
2671 (1+ num-replacements))))))
2672 (when (and (eq def 'undo-all)
2673 (null (zerop num-replacements)))
2674 (message "Undid %d %s" num-replacements
2675 (if (= num-replacements 1)
2676 "replacement"
2677 "replacements"))
2678 (ding 'no-terminate)
2679 (sit-for 1)))
2680 (setq replaced nil last-was-undo t last-was-act-and-show nil)))
2681 ((eq def 'act)
2682 (or replaced
2683 (setq noedit
2684 (replace-match-maybe-edit
2685 next-replacement nocasify literal
2686 noedit real-match-data backward)
2687 replace-count (1+ replace-count)))
2688 (setq done t replaced t update-stack (not last-was-act-and-show)))
2689 ((eq def 'act-and-exit)
2690 (or replaced
2691 (setq noedit
2692 (replace-match-maybe-edit
2693 next-replacement nocasify literal
2694 noedit real-match-data backward)
2695 replace-count (1+ replace-count)))
2696 (setq keep-going nil)
2697 (setq done t replaced t))
2698 ((eq def 'act-and-show)
2699 (unless replaced
2700 (setq noedit
2701 (replace-match-maybe-edit
2702 next-replacement nocasify literal
2703 noedit real-match-data backward)
2704 replace-count (1+ replace-count)
2705 real-match-data (replace-match-data
2706 t real-match-data)
2707 replaced t last-was-act-and-show t)
2708 (replace--push-stack
2709 replaced
2710 search-string-replaced
2711 next-replacement-replaced stack)))
2712 ((or (eq def 'automatic) (eq def 'automatic-all))
2713 (or replaced
2714 (setq noedit
2715 (replace-match-maybe-edit
2716 next-replacement nocasify literal
2717 noedit real-match-data backward)
2718 replace-count (1+ replace-count)))
2719 (setq done t query-flag nil replaced t)
2720 (if (eq def 'automatic-all) (setq multi-buffer t)))
2721 ((eq def 'skip)
2722 (setq done t update-stack (not last-was-act-and-show)))
2723 ((eq def 'recenter)
2724 ;; `this-command' has the value `query-replace',
2725 ;; so we need to bind it to `recenter-top-bottom'
2726 ;; to allow it to detect a sequence of `C-l'.
2727 (let ((this-command 'recenter-top-bottom)
2728 (last-command 'recenter-top-bottom))
2729 (recenter-top-bottom)))
2730 ((eq def 'edit)
2731 (let ((opos (point-marker)))
2732 (setq real-match-data (replace-match-data
2733 nil real-match-data
2734 real-match-data))
2735 (goto-char (match-beginning 0))
2736 (save-excursion
2737 (save-window-excursion
2738 (recursive-edit)))
2739 (goto-char opos)
2740 (set-marker opos nil))
2741 ;; Before we make the replacement,
2742 ;; decide whether the search string
2743 ;; can match again just after this match.
2744 (if (and regexp-flag nonempty-match)
2745 (setq match-again (and (looking-at search-string)
2746 (match-data)))))
2747 ;; Edit replacement.
2748 ((eq def 'edit-replacement)
2749 (setq real-match-data (replace-match-data
2750 nil real-match-data
2751 real-match-data)
2752 next-replacement
2753 (read-string "Edit replacement string: "
2754 next-replacement)
2755 noedit nil)
2756 (if replaced
2757 (set-match-data real-match-data)
2758 (setq noedit
2759 (replace-match-maybe-edit
2760 next-replacement nocasify literal noedit
2761 real-match-data backward)
2762 replaced t))
2763 (setq done t))
2765 ((eq def 'delete-and-edit)
2766 (replace-match "" t t)
2767 (setq real-match-data (replace-match-data
2768 nil real-match-data))
2769 (replace-dehighlight)
2770 (save-excursion (recursive-edit))
2771 (setq replaced t))
2772 ;; Note: we do not need to treat `exit-prefix'
2773 ;; specially here, since we reread
2774 ;; any unrecognized character.
2776 (setq this-command 'mode-exited)
2777 (setq keep-going nil)
2778 (setq unread-command-events
2779 (append (listify-key-sequence key)
2780 unread-command-events))
2781 (setq done t)))
2782 (when query-replace-lazy-highlight
2783 ;; Force lazy rehighlighting only after replacements.
2784 (if (not (memq def '(skip backup)))
2785 (setq isearch-lazy-highlight-last-string nil)))
2786 (unless (eq def 'recenter)
2787 ;; Reset recenter cycling order to initial position.
2788 (setq recenter-last-op nil)))
2789 ;; Record previous position for ^ when we move on.
2790 ;; Change markers to numbers in the match data
2791 ;; since lots of markers slow down editing.
2792 (when update-stack
2793 (replace--push-stack
2794 replaced
2795 search-string-replaced
2796 next-replacement-replaced stack))
2797 (setq next-replacement-replaced nil
2798 search-string-replaced nil
2799 last-was-act-and-show nil))))))
2800 (replace-dehighlight))
2801 (or unread-command-events
2802 (message "Replaced %d occurrence%s%s"
2803 replace-count
2804 (if (= replace-count 1) "" "s")
2805 (if (> (+ skip-read-only-count
2806 skip-filtered-count
2807 skip-invisible-count) 0)
2808 (format " (skipped %s)"
2809 (mapconcat
2810 'identity
2811 (delq nil (list
2812 (if (> skip-read-only-count 0)
2813 (format "%s read-only"
2814 skip-read-only-count))
2815 (if (> skip-invisible-count 0)
2816 (format "%s invisible"
2817 skip-invisible-count))
2818 (if (> skip-filtered-count 0)
2819 (format "%s filtered out"
2820 skip-filtered-count))))
2821 ", "))
2822 "")))
2823 (or (and keep-going stack) multi-buffer)))
2825 (provide 'replace)
2827 ;;; replace.el ends here