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