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