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