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