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