lisp/*.el: Lexical-binding cleanup.
[emacs.git] / lisp / replace.el
blob31a48d489601c10d2c8aa8ed151310d2b50f31fb
1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2011
4 ;; Free Software Foundation, Inc.
6 ;; Maintainer: FSF
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; This package supplies the string and regular-expression replace functions
27 ;; documented in the Emacs user's manual.
29 ;;; Code:
31 (defcustom case-replace t
32 "Non-nil means `query-replace' should preserve case in replacements."
33 :type 'boolean
34 :group 'matching)
36 (defvar query-replace-history nil
37 "Default history list for query-replace commands.
38 See `query-replace-from-history-variable' and
39 `query-replace-to-history-variable'.")
41 (defvar query-replace-defaults nil
42 "Default values of FROM-STRING and TO-STRING for `query-replace'.
43 This is a cons cell (FROM-STRING . TO-STRING), or nil if there is
44 no default value.")
46 (defvar query-replace-interactive nil
47 "Non-nil means `query-replace' uses the last search string.
48 That becomes the \"string to replace\".")
50 (defcustom query-replace-from-history-variable 'query-replace-history
51 "History list to use for the FROM argument of `query-replace' commands.
52 The value of this variable should be a symbol; that symbol
53 is used as a variable to hold a history list for the strings
54 or patterns to be replaced."
55 :group 'matching
56 :type 'symbol
57 :version "20.3")
59 (defcustom query-replace-to-history-variable 'query-replace-history
60 "History list to use for the TO argument of `query-replace' commands.
61 The value of this variable should be a symbol; that symbol
62 is used as a variable to hold a history list for replacement
63 strings or patterns."
64 :group 'matching
65 :type 'symbol
66 :version "20.3")
68 (defcustom query-replace-skip-read-only nil
69 "Non-nil means `query-replace' and friends ignore read-only matches."
70 :type 'boolean
71 :group 'matching
72 :version "22.1")
74 (defcustom query-replace-show-replacement t
75 "Non-nil means to show what actual replacement text will be."
76 :type 'boolean
77 :group 'matching
78 :version "23.1")
80 (defcustom query-replace-highlight t
81 "Non-nil means to highlight matches during query replacement."
82 :type 'boolean
83 :group 'matching)
85 (defcustom query-replace-lazy-highlight t
86 "Controls the lazy-highlighting during query replacements.
87 When non-nil, all text in the buffer matching the current match
88 is highlighted lazily using isearch lazy highlighting (see
89 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
90 :type 'boolean
91 :group 'lazy-highlight
92 :group 'matching
93 :version "22.1")
95 (defface query-replace
96 '((t (:inherit isearch)))
97 "Face for highlighting query replacement matches."
98 :group 'matching
99 :version "22.1")
101 (defvar replace-count 0
102 "Number of replacements done so far.
103 See `replace-regexp' and `query-replace-regexp-eval'.")
105 (defun query-replace-descr (string)
106 (mapconcat 'isearch-text-char-description string ""))
108 (defun query-replace-read-from (prompt regexp-flag)
109 "Query and return the `from' argument of a query-replace operation.
110 The return value can also be a pair (FROM . TO) indicating that the user
111 wants to replace FROM with TO."
112 (if query-replace-interactive
113 (car (if regexp-flag regexp-search-ring search-ring))
114 (let* ((history-add-new-input nil)
115 (from
116 ;; The save-excursion here is in case the user marks and copies
117 ;; a region in order to specify the minibuffer input.
118 ;; That should not clobber the region for the query-replace itself.
119 (save-excursion
120 (read-from-minibuffer
121 (if query-replace-defaults
122 (format "%s (default %s -> %s): " prompt
123 (query-replace-descr (car query-replace-defaults))
124 (query-replace-descr (cdr query-replace-defaults)))
125 (format "%s: " prompt))
126 nil nil nil
127 query-replace-from-history-variable
128 nil t))))
129 (if (and (zerop (length from)) query-replace-defaults)
130 (cons (car query-replace-defaults)
131 (query-replace-compile-replacement
132 (cdr query-replace-defaults) regexp-flag))
133 (add-to-history query-replace-from-history-variable from nil t)
134 ;; Warn if user types \n or \t, but don't reject the input.
135 (and regexp-flag
136 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
137 (let ((match (match-string 3 from)))
138 (cond
139 ((string= match "\\n")
140 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
141 ((string= match "\\t")
142 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
143 (sit-for 2)))
144 from))))
146 (defun query-replace-compile-replacement (to regexp-flag)
147 "Maybe convert a regexp replacement TO to Lisp.
148 Returns a list suitable for `perform-replace' if necessary,
149 the original string if not."
150 (if (and regexp-flag
151 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
152 (let (pos list char)
153 (while
154 (progn
155 (setq pos (match-end 0))
156 (push (substring to 0 (- pos 2)) list)
157 (setq char (aref to (1- pos))
158 to (substring to pos))
159 (cond ((eq char ?\#)
160 (push '(number-to-string replace-count) list))
161 ((eq char ?\,)
162 (setq pos (read-from-string to))
163 (push `(replace-quote ,(car pos)) list)
164 (let ((end
165 ;; Swallow a space after a symbol
166 ;; if there is a space.
167 (if (and (or (symbolp (car pos))
168 ;; Swallow a space after 'foo
169 ;; but not after (quote foo).
170 (and (eq (car-safe (car pos)) 'quote)
171 (not (= ?\( (aref to 0)))))
172 (eq (string-match " " to (cdr pos))
173 (cdr pos)))
174 (1+ (cdr pos))
175 (cdr pos))))
176 (setq to (substring to end)))))
177 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
178 (setq to (nreverse (delete "" (cons to list))))
179 (replace-match-string-symbols to)
180 (cons 'replace-eval-replacement
181 (if (cdr to)
182 (cons 'concat to)
183 (car to))))
184 to))
187 (defun query-replace-read-to (from prompt regexp-flag)
188 "Query and return the `to' argument of a query-replace operation."
189 (query-replace-compile-replacement
190 (save-excursion
191 (let* ((history-add-new-input nil)
192 (to (read-from-minibuffer
193 (format "%s %s with: " prompt (query-replace-descr from))
194 nil nil nil
195 query-replace-to-history-variable from t)))
196 (add-to-history query-replace-to-history-variable to nil t)
197 (setq query-replace-defaults (cons from to))
198 to))
199 regexp-flag))
201 (defun query-replace-read-args (prompt regexp-flag &optional noerror)
202 (unless noerror
203 (barf-if-buffer-read-only))
204 (let* ((from (query-replace-read-from prompt regexp-flag))
205 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
206 (query-replace-read-to from prompt regexp-flag))))
207 (list from to current-prefix-arg)))
209 (defun query-replace (from-string to-string &optional delimited start end)
210 "Replace some occurrences of FROM-STRING with TO-STRING.
211 As each match is found, the user must type a character saying
212 what to do with it. For directions, type \\[help-command] at that time.
214 In Transient Mark mode, if the mark is active, operate on the contents
215 of the region. Otherwise, operate from point to the end of the buffer.
217 If `query-replace-interactive' is non-nil, the last incremental search
218 string is used as FROM-STRING--you don't have to specify it with the
219 minibuffer.
221 Matching is independent of case if `case-fold-search' is non-nil and
222 FROM-STRING has no uppercase letters. Replacement transfers the case
223 pattern of the old text to the new text, if `case-replace' and
224 `case-fold-search' are non-nil and FROM-STRING has no uppercase
225 letters. \(Transferring the case pattern means that if the old text
226 matched is all caps, or capitalized, then its replacement is upcased
227 or capitalized.)
229 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
230 only matches surrounded by word boundaries.
231 Fourth and fifth arg START and END specify the region to operate on.
233 To customize possible responses, change the \"bindings\" in `query-replace-map'."
234 (interactive
235 (let ((common
236 (query-replace-read-args
237 (concat "Query replace"
238 (if current-prefix-arg " word" "")
239 (if (and transient-mark-mode mark-active) " in region" ""))
240 nil)))
241 (list (nth 0 common) (nth 1 common) (nth 2 common)
242 ;; These are done separately here
243 ;; so that command-history will record these expressions
244 ;; rather than the values they had this time.
245 (if (and transient-mark-mode mark-active)
246 (region-beginning))
247 (if (and transient-mark-mode mark-active)
248 (region-end)))))
249 (perform-replace from-string to-string t nil delimited nil nil start end))
251 (define-key esc-map "%" 'query-replace)
253 (defun query-replace-regexp (regexp to-string &optional delimited start end)
254 "Replace some things after point matching REGEXP with TO-STRING.
255 As each match is found, the user must type a character saying
256 what to do with it. For directions, type \\[help-command] at that time.
258 In Transient Mark mode, if the mark is active, operate on the contents
259 of the region. Otherwise, operate from point to the end of the buffer.
261 If `query-replace-interactive' is non-nil, the last incremental search
262 regexp is used as REGEXP--you don't have to specify it with the
263 minibuffer.
265 Matching is independent of case if `case-fold-search' is non-nil and
266 REGEXP has no uppercase letters. Replacement transfers the case
267 pattern of the old text to the new text, if `case-replace' and
268 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
269 \(Transferring the case pattern means that if the old text matched is
270 all caps, or capitalized, then its replacement is upcased or
271 capitalized.)
273 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
274 only matches surrounded by word boundaries.
275 Fourth and fifth arg START and END specify the region to operate on.
277 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
278 and `\\=\\N' (where N is a digit) stands for
279 whatever what matched the Nth `\\(...\\)' in REGEXP.
280 `\\?' lets you edit the replacement text in the minibuffer
281 at the given position for each replacement.
283 In interactive calls, the replacement text can contain `\\,'
284 followed by a Lisp expression. Each
285 replacement evaluates that expression to compute the replacement
286 string. Inside of that expression, `\\&' is a string denoting the
287 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
288 for the whole or a partial match converted to a number with
289 `string-to-number', and `\\#' itself for the number of replacements
290 done so far (starting with zero).
292 If the replacement expression is a symbol, write a space after it
293 to terminate it. One space there, if any, will be discarded.
295 When using those Lisp features interactively in the replacement
296 text, TO-STRING is actually made a list instead of a string.
297 Use \\[repeat-complex-command] after this command for details."
298 (interactive
299 (let ((common
300 (query-replace-read-args
301 (concat "Query replace"
302 (if current-prefix-arg " word" "")
303 " regexp"
304 (if (and transient-mark-mode mark-active) " in region" ""))
305 t)))
306 (list (nth 0 common) (nth 1 common) (nth 2 common)
307 ;; These are done separately here
308 ;; so that command-history will record these expressions
309 ;; rather than the values they had this time.
310 (if (and transient-mark-mode mark-active)
311 (region-beginning))
312 (if (and transient-mark-mode mark-active)
313 (region-end)))))
314 (perform-replace regexp to-string t t delimited nil nil start end))
316 (define-key esc-map [?\C-%] 'query-replace-regexp)
318 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
319 "Replace some things after point matching REGEXP with the result of TO-EXPR.
321 Interactive use of this function is deprecated in favor of the
322 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
323 using `search-forward-regexp' and `replace-match' is preferred.
325 As each match is found, the user must type a character saying
326 what to do with it. For directions, type \\[help-command] at that time.
328 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
329 reference `replace-count' to get the number of replacements already made.
330 If the result of TO-EXPR is not a string, it is converted to one using
331 `prin1-to-string' with the NOESCAPE argument (which see).
333 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
334 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
335 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
336 Use `\\#&' or `\\#N' if you want a number instead of a string.
337 In interactive use, `\\#' in itself stands for `replace-count'.
339 In Transient Mark mode, if the mark is active, operate on the contents
340 of the region. Otherwise, operate from point to the end of the buffer.
342 If `query-replace-interactive' is non-nil, the last incremental search
343 regexp is used as REGEXP--you don't have to specify it with the
344 minibuffer.
346 Preserves case in each replacement if `case-replace' and `case-fold-search'
347 are non-nil and REGEXP has no uppercase letters.
349 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
350 only matches that are surrounded by word boundaries.
351 Fourth and fifth arg START and END specify the region to operate on."
352 (interactive
353 (progn
354 (barf-if-buffer-read-only)
355 (let* ((from
356 ;; Let-bind the history var to disable the "foo -> bar" default.
357 ;; Maybe we shouldn't disable this default, but for now I'll
358 ;; leave it off. --Stef
359 (let ((query-replace-to-history-variable nil))
360 (query-replace-read-from "Query replace regexp" t)))
361 (to (list (read-from-minibuffer
362 (format "Query replace regexp %s with eval: "
363 (query-replace-descr from))
364 nil nil t query-replace-to-history-variable from t))))
365 ;; We make TO a list because replace-match-string-symbols requires one,
366 ;; and the user might enter a single token.
367 (replace-match-string-symbols to)
368 (list from (car to) current-prefix-arg
369 (if (and transient-mark-mode mark-active)
370 (region-beginning))
371 (if (and transient-mark-mode mark-active)
372 (region-end))))))
373 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
374 t 'literal delimited nil nil start end))
376 (make-obsolete 'query-replace-regexp-eval
377 "for interactive use, use the special `\\,' feature of
378 `query-replace-regexp' instead. Non-interactively, a loop
379 using `search-forward-regexp' and `replace-match' is preferred." "22.1")
381 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
382 "Replace some matches for REGEXP with various strings, in rotation.
383 The second argument TO-STRINGS contains the replacement strings, separated
384 by spaces. This command works like `query-replace-regexp' except that
385 each successive replacement uses the next successive replacement string,
386 wrapping around from the last such string to the first.
388 In Transient Mark mode, if the mark is active, operate on the contents
389 of the region. Otherwise, operate from point to the end of the buffer.
391 Non-interactively, TO-STRINGS may be a list of replacement strings.
393 If `query-replace-interactive' is non-nil, the last incremental search
394 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
396 A prefix argument N says to use each replacement string N times
397 before rotating to the next.
398 Fourth and fifth arg START and END specify the region to operate on."
399 (interactive
400 (let* ((from (if query-replace-interactive
401 (car regexp-search-ring)
402 (read-from-minibuffer "Map query replace (regexp): "
403 nil nil nil
404 query-replace-from-history-variable
405 nil t)))
406 (to (read-from-minibuffer
407 (format "Query replace %s with (space-separated strings): "
408 (query-replace-descr from))
409 nil nil nil
410 query-replace-to-history-variable from t)))
411 (list from to
412 (and current-prefix-arg
413 (prefix-numeric-value current-prefix-arg))
414 (if (and transient-mark-mode mark-active)
415 (region-beginning))
416 (if (and transient-mark-mode mark-active)
417 (region-end)))))
418 (let (replacements)
419 (if (listp to-strings)
420 (setq replacements to-strings)
421 (while (/= (length to-strings) 0)
422 (if (string-match " " to-strings)
423 (setq replacements
424 (append replacements
425 (list (substring to-strings 0
426 (string-match " " to-strings))))
427 to-strings (substring to-strings
428 (1+ (string-match " " to-strings))))
429 (setq replacements (append replacements (list to-strings))
430 to-strings ""))))
431 (perform-replace regexp replacements t t nil n nil start end)))
433 (defun replace-string (from-string to-string &optional delimited start end)
434 "Replace occurrences of FROM-STRING with TO-STRING.
435 Preserve case in each match if `case-replace' and `case-fold-search'
436 are non-nil and FROM-STRING has no uppercase letters.
437 \(Preserving case means that if the string matched is all caps, or capitalized,
438 then its replacement is upcased or capitalized.)
440 In Transient Mark mode, if the mark is active, operate on the contents
441 of the region. Otherwise, operate from point to the end of the buffer.
443 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
444 only matches surrounded by word boundaries.
445 Fourth and fifth arg START and END specify the region to operate on.
447 If `query-replace-interactive' is non-nil, the last incremental search
448 string is used as FROM-STRING--you don't have to specify it with the
449 minibuffer.
451 This function is usually the wrong thing to use in a Lisp program.
452 What you probably want is a loop like this:
453 (while (search-forward FROM-STRING nil t)
454 (replace-match TO-STRING nil t))
455 which will run faster and will not set the mark or print anything.
456 \(You may need a more complex loop if FROM-STRING can match the null string
457 and TO-STRING is also null.)"
458 (interactive
459 (let ((common
460 (query-replace-read-args
461 (concat "Replace"
462 (if current-prefix-arg " word" "")
463 " string"
464 (if (and transient-mark-mode mark-active) " in region" ""))
465 nil)))
466 (list (nth 0 common) (nth 1 common) (nth 2 common)
467 (if (and transient-mark-mode mark-active)
468 (region-beginning))
469 (if (and transient-mark-mode mark-active)
470 (region-end)))))
471 (perform-replace from-string to-string nil nil delimited nil nil start end))
473 (defun replace-regexp (regexp to-string &optional delimited start end)
474 "Replace things after point matching REGEXP with TO-STRING.
475 Preserve case in each match if `case-replace' and `case-fold-search'
476 are non-nil and REGEXP has no uppercase letters.
478 In Transient Mark mode, if the mark is active, operate on the contents
479 of the region. Otherwise, operate from point to the end of the buffer.
481 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
482 only matches surrounded by word boundaries.
483 Fourth and fifth arg START and END specify the region to operate on.
485 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
486 and `\\=\\N' (where N is a digit) stands for
487 whatever what matched the Nth `\\(...\\)' in REGEXP.
488 `\\?' lets you edit the replacement text in the minibuffer
489 at the given position for each replacement.
491 In interactive calls, the replacement text may contain `\\,'
492 followed by a Lisp expression used as part of the replacement
493 text. Inside of that expression, `\\&' is a string denoting the
494 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
495 numeric values from `string-to-number', and `\\#' itself for
496 `replace-count', the number of replacements occurred so far.
498 If your Lisp expression is an identifier and the next letter in
499 the replacement string would be interpreted as part of it, you
500 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
501 for this particular case you may also enter `\\#' in the
502 replacement text directly.
504 When using those Lisp features interactively in the replacement
505 text, TO-STRING is actually made a list instead of a string.
506 Use \\[repeat-complex-command] after this command for details.
508 If `query-replace-interactive' is non-nil, the last incremental search
509 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
511 This function is usually the wrong thing to use in a Lisp program.
512 What you probably want is a loop like this:
513 (while (re-search-forward REGEXP nil t)
514 (replace-match TO-STRING nil nil))
515 which will run faster and will not set the mark or print anything."
516 (interactive
517 (let ((common
518 (query-replace-read-args
519 (concat "Replace"
520 (if current-prefix-arg " word" "")
521 " regexp"
522 (if (and transient-mark-mode mark-active) " in region" ""))
523 t)))
524 (list (nth 0 common) (nth 1 common) (nth 2 common)
525 (if (and transient-mark-mode mark-active)
526 (region-beginning))
527 (if (and transient-mark-mode mark-active)
528 (region-end)))))
529 (perform-replace regexp to-string nil t delimited nil nil start end))
532 (defvar regexp-history nil
533 "History list for some commands that read regular expressions.
535 Maximum length of the history list is determined by the value
536 of `history-length', which see.")
538 (defvar occur-collect-regexp-history '("\\1")
539 "History of regexp for occur's collect operation")
541 (defun read-regexp (prompt &optional default-value)
542 "Read regexp as a string using the regexp history and some useful defaults.
543 Prompt for a regular expression with PROMPT (without a colon and
544 space) in the minibuffer. The optional argument DEFAULT-VALUE
545 provides the value to display in the minibuffer prompt that is
546 returned if the user just types RET.
547 Values available via M-n are the string at point, the last isearch
548 regexp, the last isearch string, and the last replacement regexp."
549 (let* ((defaults
550 (list (regexp-quote
551 (or (funcall (or find-tag-default-function
552 (get major-mode 'find-tag-default-function)
553 'find-tag-default))
554 ""))
555 (car regexp-search-ring)
556 (regexp-quote (or (car search-ring) ""))
557 (car (symbol-value
558 query-replace-from-history-variable))))
559 (defaults (delete-dups (delq nil (delete "" defaults))))
560 ;; Don't add automatically the car of defaults for empty input
561 (history-add-new-input nil)
562 (input
563 (read-from-minibuffer
564 (if default-value
565 (format "%s (default %s): " prompt
566 (query-replace-descr default-value))
567 (format "%s: " prompt))
568 nil nil nil 'regexp-history defaults t)))
569 (if (equal input "")
570 (or default-value input)
571 (prog1 input
572 (add-to-history 'regexp-history input)))))
575 (defalias 'delete-non-matching-lines 'keep-lines)
576 (defalias 'delete-matching-lines 'flush-lines)
577 (defalias 'count-matches 'how-many)
580 (defun keep-lines-read-args (prompt)
581 "Read arguments for `keep-lines' and friends.
582 Prompt for a regexp with PROMPT.
583 Value is a list, (REGEXP)."
584 (list (read-regexp prompt) nil nil t))
586 (defun keep-lines (regexp &optional rstart rend interactive)
587 "Delete all lines except those containing matches for REGEXP.
588 A match split across lines preserves all the lines it lies in.
589 When called from Lisp (and usually interactively as well, see below)
590 applies to all lines starting after point.
592 If REGEXP contains upper case characters (excluding those preceded by `\\')
593 and `search-upper-case' is non-nil, the matching is case-sensitive.
595 Second and third arg RSTART and REND specify the region to operate on.
596 This command operates on (the accessible part of) all lines whose
597 accessible part is entirely contained in the region determined by RSTART
598 and REND. (A newline ending a line counts as part of that line.)
600 Interactively, in Transient Mark mode when the mark is active, operate
601 on all lines whose accessible part is entirely contained in the region.
602 Otherwise, the command applies to all lines starting after point.
603 When calling this function from Lisp, you can pretend that it was
604 called interactively by passing a non-nil INTERACTIVE argument.
606 This function starts looking for the next match from the end of
607 the previous match. Hence, it ignores matches that overlap
608 a previously found match."
610 (interactive
611 (progn
612 (barf-if-buffer-read-only)
613 (keep-lines-read-args "Keep lines containing match for regexp")))
614 (if rstart
615 (progn
616 (goto-char (min rstart rend))
617 (setq rend
618 (progn
619 (save-excursion
620 (goto-char (max rstart rend))
621 (unless (or (bolp) (eobp))
622 (forward-line 0))
623 (point-marker)))))
624 (if (and interactive transient-mark-mode mark-active)
625 (setq rstart (region-beginning)
626 rend (progn
627 (goto-char (region-end))
628 (unless (or (bolp) (eobp))
629 (forward-line 0))
630 (point-marker)))
631 (setq rstart (point)
632 rend (point-max-marker)))
633 (goto-char rstart))
634 (save-excursion
635 (or (bolp) (forward-line 1))
636 (let ((start (point))
637 (case-fold-search
638 (if (and case-fold-search search-upper-case)
639 (isearch-no-upper-case-p regexp t)
640 case-fold-search)))
641 (while (< (point) rend)
642 ;; Start is first char not preserved by previous match.
643 (if (not (re-search-forward regexp rend 'move))
644 (delete-region start rend)
645 (let ((end (save-excursion (goto-char (match-beginning 0))
646 (forward-line 0)
647 (point))))
648 ;; Now end is first char preserved by the new match.
649 (if (< start end)
650 (delete-region start end))))
652 (setq start (save-excursion (forward-line 1) (point)))
653 ;; If the match was empty, avoid matching again at same place.
654 (and (< (point) rend)
655 (= (match-beginning 0) (match-end 0))
656 (forward-char 1)))))
657 (set-marker rend nil)
658 nil)
661 (defun flush-lines (regexp &optional rstart rend interactive)
662 "Delete lines containing matches for REGEXP.
663 When called from Lisp (and usually when called interactively as
664 well, see below), applies to the part of the buffer after point.
665 The line point is in is deleted if and only if it contains a
666 match for regexp starting after point.
668 If REGEXP contains upper case characters (excluding those preceded by `\\')
669 and `search-upper-case' is non-nil, the matching is case-sensitive.
671 Second and third arg RSTART and REND specify the region to operate on.
672 Lines partially contained in this region are deleted if and only if
673 they contain a match entirely contained in it.
675 Interactively, in Transient Mark mode when the mark is active, operate
676 on the contents of the region. Otherwise, operate from point to the
677 end of (the accessible portion of) the buffer. When calling this function
678 from Lisp, you can pretend that it was called interactively by passing
679 a non-nil INTERACTIVE argument.
681 If a match is split across lines, all the lines it lies in are deleted.
682 They are deleted _before_ looking for the next match. Hence, a match
683 starting on the same line at which another match ended is ignored."
685 (interactive
686 (progn
687 (barf-if-buffer-read-only)
688 (keep-lines-read-args "Flush lines containing match for regexp")))
689 (if rstart
690 (progn
691 (goto-char (min rstart rend))
692 (setq rend (copy-marker (max rstart rend))))
693 (if (and interactive transient-mark-mode mark-active)
694 (setq rstart (region-beginning)
695 rend (copy-marker (region-end)))
696 (setq rstart (point)
697 rend (point-max-marker)))
698 (goto-char rstart))
699 (let ((case-fold-search
700 (if (and case-fold-search search-upper-case)
701 (isearch-no-upper-case-p regexp t)
702 case-fold-search)))
703 (save-excursion
704 (while (and (< (point) rend)
705 (re-search-forward regexp rend t))
706 (delete-region (save-excursion (goto-char (match-beginning 0))
707 (forward-line 0)
708 (point))
709 (progn (forward-line 1) (point))))))
710 (set-marker rend nil)
711 nil)
714 (defun how-many (regexp &optional rstart rend interactive)
715 "Print and return number of matches for REGEXP following point.
716 When called from Lisp and INTERACTIVE is omitted or nil, just return
717 the number, do not print it; if INTERACTIVE is t, the function behaves
718 in all respects as if it had been called interactively.
720 If REGEXP contains upper case characters (excluding those preceded by `\\')
721 and `search-upper-case' is non-nil, the matching is case-sensitive.
723 Second and third arg RSTART and REND specify the region to operate on.
725 Interactively, in Transient Mark mode when the mark is active, operate
726 on the contents of the region. Otherwise, operate from point to the
727 end of (the accessible portion of) the buffer.
729 This function starts looking for the next match from the end of
730 the previous match. Hence, it ignores matches that overlap
731 a previously found match."
733 (interactive
734 (keep-lines-read-args "How many matches for regexp"))
735 (save-excursion
736 (if rstart
737 (progn
738 (goto-char (min rstart rend))
739 (setq rend (max rstart rend)))
740 (if (and interactive transient-mark-mode mark-active)
741 (setq rstart (region-beginning)
742 rend (region-end))
743 (setq rstart (point)
744 rend (point-max)))
745 (goto-char rstart))
746 (let ((count 0)
747 opoint
748 (case-fold-search
749 (if (and case-fold-search search-upper-case)
750 (isearch-no-upper-case-p regexp t)
751 case-fold-search)))
752 (while (and (< (point) rend)
753 (progn (setq opoint (point))
754 (re-search-forward regexp rend t)))
755 (if (= opoint (point))
756 (forward-char 1)
757 (setq count (1+ count))))
758 (when interactive (message "%d occurrence%s"
759 count
760 (if (= count 1) "" "s")))
761 count)))
764 (defvar occur-mode-map
765 (let ((map (make-sparse-keymap)))
766 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
767 (define-key map [mouse-2] 'occur-mode-mouse-goto)
768 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
769 (define-key map "\C-m" 'occur-mode-goto-occurrence)
770 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
771 (define-key map "\C-o" 'occur-mode-display-occurrence)
772 (define-key map "\M-n" 'occur-next)
773 (define-key map "\M-p" 'occur-prev)
774 (define-key map "r" 'occur-rename-buffer)
775 (define-key map "c" 'clone-buffer)
776 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
777 (define-key map [menu-bar] (make-sparse-keymap))
778 (define-key map [menu-bar occur]
779 (cons (purecopy "Occur") map))
780 (define-key map [next-error-follow-minor-mode]
781 `(menu-item ,(purecopy "Auto Occurrence Display")
782 next-error-follow-minor-mode
783 :help ,(purecopy
784 "Display another occurrence when moving the cursor")
785 :button (:toggle . (and (boundp 'next-error-follow-minor-mode)
786 next-error-follow-minor-mode))))
787 (define-key map [separator-1] menu-bar-separator)
788 (define-key map [kill-this-buffer]
789 `(menu-item ,(purecopy "Kill Occur Buffer") kill-this-buffer
790 :help ,(purecopy "Kill the current *Occur* buffer")))
791 (define-key map [quit-window]
792 `(menu-item ,(purecopy "Quit Occur Window") quit-window
793 :help ,(purecopy "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame")))
794 (define-key map [revert-buffer]
795 `(menu-item ,(purecopy "Revert Occur Buffer") revert-buffer
796 :help ,(purecopy "Replace the text in the *Occur* buffer with the results of rerunning occur")))
797 (define-key map [clone-buffer]
798 `(menu-item ,(purecopy "Clone Occur Buffer") clone-buffer
799 :help ,(purecopy "Create and return a twin copy of the current *Occur* buffer")))
800 (define-key map [occur-rename-buffer]
801 `(menu-item ,(purecopy "Rename Occur Buffer") occur-rename-buffer
802 :help ,(purecopy "Rename the current *Occur* buffer to *Occur: original-buffer-name*.")))
803 (define-key map [separator-2] menu-bar-separator)
804 (define-key map [occur-mode-goto-occurrence-other-window]
805 `(menu-item ,(purecopy "Go To Occurrence Other Window") occur-mode-goto-occurrence-other-window
806 :help ,(purecopy "Go to the occurrence the current line describes, in another window")))
807 (define-key map [occur-mode-goto-occurrence]
808 `(menu-item ,(purecopy "Go To Occurrence") occur-mode-goto-occurrence
809 :help ,(purecopy "Go to the occurrence the current line describes")))
810 (define-key map [occur-mode-display-occurrence]
811 `(menu-item ,(purecopy "Display Occurrence") occur-mode-display-occurrence
812 :help ,(purecopy "Display in another window the occurrence the current line describes")))
813 (define-key map [occur-next]
814 `(menu-item ,(purecopy "Move to Next Match") occur-next
815 :help ,(purecopy "Move to the Nth (default 1) next match in an Occur mode buffer")))
816 (define-key map [occur-prev]
817 `(menu-item ,(purecopy "Move to Previous Match") occur-prev
818 :help ,(purecopy "Move to the Nth (default 1) previous match in an Occur mode buffer")))
819 map)
820 "Keymap for `occur-mode'.")
822 (defvar occur-revert-arguments nil
823 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
824 See `occur-revert-function'.")
826 (defcustom occur-mode-hook '(turn-on-font-lock)
827 "Hook run when entering Occur mode."
828 :type 'hook
829 :group 'matching)
831 (defcustom occur-hook nil
832 "Hook run by Occur when there are any matches."
833 :type 'hook
834 :group 'matching)
836 (defcustom occur-mode-find-occurrence-hook nil
837 "Hook run by Occur after locating an occurrence.
838 This will be called with the cursor position at the occurrence. An application
839 for this is to reveal context in an outline-mode when the occurrence is hidden."
840 :type 'hook
841 :group 'matching)
843 (put 'occur-mode 'mode-class 'special)
844 (define-derived-mode occur-mode special-mode "Occur"
845 "Major mode for output from \\[occur].
846 \\<occur-mode-map>Move point to one of the items in this buffer, then use
847 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
848 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
850 \\{occur-mode-map}"
851 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
852 (make-local-variable 'occur-revert-arguments)
853 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
854 (setq next-error-function 'occur-next-error))
856 (defun occur-revert-function (_ignore1 _ignore2)
857 "Handle `revert-buffer' for Occur mode buffers."
858 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
860 (defun occur-mode-find-occurrence ()
861 (let ((pos (get-text-property (point) 'occur-target)))
862 (unless pos
863 (error "No occurrence on this line"))
864 (unless (buffer-live-p (marker-buffer pos))
865 (error "Buffer for this occurrence was killed"))
866 pos))
868 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
869 (defun occur-mode-goto-occurrence (&optional event)
870 "Go to the occurrence the current line describes."
871 (interactive (list last-nonmenu-event))
872 (let ((pos
873 (if (null event)
874 ;; Actually `event-end' works correctly with a nil argument as
875 ;; well, so we could dispense with this test, but let's not
876 ;; rely on this undocumented behavior.
877 (occur-mode-find-occurrence)
878 (with-current-buffer (window-buffer (posn-window (event-end event)))
879 (save-excursion
880 (goto-char (posn-point (event-end event)))
881 (occur-mode-find-occurrence)))))
882 same-window-buffer-names
883 same-window-regexps)
884 (pop-to-buffer (marker-buffer pos))
885 (goto-char pos)
886 (run-hooks 'occur-mode-find-occurrence-hook)))
888 (defun occur-mode-goto-occurrence-other-window ()
889 "Go to the occurrence the current line describes, in another window."
890 (interactive)
891 (let ((pos (occur-mode-find-occurrence)))
892 (switch-to-buffer-other-window (marker-buffer pos))
893 (goto-char pos)
894 (run-hooks 'occur-mode-find-occurrence-hook)))
896 (defun occur-mode-display-occurrence ()
897 "Display in another window the occurrence the current line describes."
898 (interactive)
899 (let ((pos (occur-mode-find-occurrence))
900 window
901 ;; Bind these to ensure `display-buffer' puts it in another window.
902 same-window-buffer-names
903 same-window-regexps)
904 (setq window (display-buffer (marker-buffer pos)))
905 ;; This is the way to set point in the proper window.
906 (save-selected-window
907 (select-window window)
908 (goto-char pos)
909 (run-hooks 'occur-mode-find-occurrence-hook))))
911 (defun occur-find-match (n search message)
912 (if (not n) (setq n 1))
913 (let ((r))
914 (while (> n 0)
915 (setq r (funcall search (point) 'occur-match))
916 (and r
917 (get-text-property r 'occur-match)
918 (setq r (funcall search r 'occur-match)))
919 (if r
920 (goto-char r)
921 (error message))
922 (setq n (1- n)))))
924 (defun occur-next (&optional n)
925 "Move to the Nth (default 1) next match in an Occur mode buffer."
926 (interactive "p")
927 (occur-find-match n #'next-single-property-change "No more matches"))
929 (defun occur-prev (&optional n)
930 "Move to the Nth (default 1) previous match in an Occur mode buffer."
931 (interactive "p")
932 (occur-find-match n #'previous-single-property-change "No earlier matches"))
934 (defun occur-next-error (&optional argp reset)
935 "Move to the Nth (default 1) next match in an Occur mode buffer.
936 Compatibility function for \\[next-error] invocations."
937 (interactive "p")
938 ;; we need to run occur-find-match from within the Occur buffer
939 (with-current-buffer
940 ;; Choose the buffer and make it current.
941 (if (next-error-buffer-p (current-buffer))
942 (current-buffer)
943 (next-error-find-buffer nil nil
944 (lambda ()
945 (eq major-mode 'occur-mode))))
947 (goto-char (cond (reset (point-min))
948 ((< argp 0) (line-beginning-position))
949 ((> argp 0) (line-end-position))
950 ((point))))
951 (occur-find-match
952 (abs argp)
953 (if (> 0 argp)
954 #'previous-single-property-change
955 #'next-single-property-change)
956 "No more matches")
957 ;; In case the *Occur* buffer is visible in a nonselected window.
958 (let ((win (get-buffer-window (current-buffer) t)))
959 (if win (set-window-point win (point))))
960 (occur-mode-goto-occurrence)))
962 (defface match
963 '((((class color) (min-colors 88) (background light))
964 :background "yellow1")
965 (((class color) (min-colors 88) (background dark))
966 :background "RoyalBlue3")
967 (((class color) (min-colors 8) (background light))
968 :background "yellow" :foreground "black")
969 (((class color) (min-colors 8) (background dark))
970 :background "blue" :foreground "white")
971 (((type tty) (class mono))
972 :inverse-video t)
973 (t :background "gray"))
974 "Face used to highlight matches permanently."
975 :group 'matching
976 :version "22.1")
978 (defcustom list-matching-lines-default-context-lines 0
979 "Default number of context lines included around `list-matching-lines' matches.
980 A negative number means to include that many lines before the match.
981 A positive number means to include that many lines both before and after."
982 :type 'integer
983 :group 'matching)
985 (defalias 'list-matching-lines 'occur)
987 (defcustom list-matching-lines-face 'match
988 "Face used by \\[list-matching-lines] to show the text that matches.
989 If the value is nil, don't highlight the matching portions specially."
990 :type 'face
991 :group 'matching)
993 (defcustom list-matching-lines-buffer-name-face 'underline
994 "Face used by \\[list-matching-lines] to show the names of buffers.
995 If the value is nil, don't highlight the buffer names specially."
996 :type 'face
997 :group 'matching)
999 (defcustom occur-excluded-properties
1000 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1001 yank-handler follow-link)
1002 "Text properties to discard when copying lines to the *Occur* buffer.
1003 The value should be a list of text properties to discard or t,
1004 which means to discard all text properties."
1005 :type '(choice (const :tag "All" t) (repeat symbol))
1006 :group 'matching
1007 :version "22.1")
1009 (defun occur-read-primary-args ()
1010 (let* ((perform-collect (consp current-prefix-arg))
1011 (regexp (read-regexp (if perform-collect
1012 "Collect strings matching regexp"
1013 "List lines matching regexp")
1014 (car regexp-history))))
1015 (list regexp
1016 (if perform-collect
1017 ;; Perform collect operation
1018 (if (zerop (regexp-opt-depth regexp))
1019 ;; No subexpression so collect the entire match.
1020 "\\&"
1021 ;; Get the regexp for collection pattern.
1022 (let ((default (car occur-collect-regexp-history)))
1023 (read-string
1024 (format "Regexp to collect (default %s): " default)
1025 nil 'occur-collect-regexp-history default)))
1026 ;; Otherwise normal occur takes numerical prefix argument.
1027 (when current-prefix-arg
1028 (prefix-numeric-value current-prefix-arg))))))
1030 (defun occur-rename-buffer (&optional unique-p interactive-p)
1031 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1032 Here `original-buffer-name' is the buffer name where Occur was originally run.
1033 When given the prefix argument, or called non-interactively, the renaming
1034 will not clobber the existing buffer(s) of that name, but use
1035 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1036 if you always want a separate *Occur* buffer for each buffer where you
1037 invoke `occur'."
1038 (interactive "P\np")
1039 (with-current-buffer
1040 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1041 (rename-buffer (concat "*Occur: "
1042 (mapconcat #'buffer-name
1043 (car (cddr occur-revert-arguments)) "/")
1044 "*")
1045 (or unique-p (not interactive-p)))))
1047 (defun occur (regexp &optional nlines)
1048 "Show all lines in the current buffer containing a match for REGEXP.
1049 If a match spreads across multiple lines, all those lines are shown.
1051 Each line is displayed with NLINES lines before and after, or -NLINES
1052 before if NLINES is negative.
1053 NLINES defaults to `list-matching-lines-default-context-lines'.
1054 Interactively it is the prefix arg.
1056 The lines are shown in a buffer named `*Occur*'.
1057 It serves as a menu to find any of the occurrences in this buffer.
1058 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1060 If REGEXP contains upper case characters (excluding those preceded by `\\')
1061 and `search-upper-case' is non-nil, the matching is case-sensitive.
1063 When NLINES is a string or when the function is called
1064 interactively with prefix argument without a number (`C-u' alone
1065 as prefix) the matching strings are collected into the `*Occur*'
1066 buffer by using NLINES as a replacement regexp. NLINES may
1067 contain \\& and \\N which convention follows `replace-match'.
1068 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1069 \"\\1\" for NLINES collects all the function names in a lisp
1070 program. When there is no parenthesized subexpressions in REGEXP
1071 the entire match is collected. In any case the searched buffers
1072 are not modified."
1073 (interactive (occur-read-primary-args))
1074 (occur-1 regexp nlines (list (current-buffer))))
1076 (defvar ido-ignore-item-temp-list)
1078 (defun multi-occur (bufs regexp &optional nlines)
1079 "Show all lines in buffers BUFS containing a match for REGEXP.
1080 This function acts on multiple buffers; otherwise, it is exactly like
1081 `occur'. When you invoke this command interactively, you must specify
1082 the buffer names that you want, one by one."
1083 (interactive
1084 (cons
1085 (let* ((bufs (list (read-buffer "First buffer to search: "
1086 (current-buffer) t)))
1087 (buf nil)
1088 (ido-ignore-item-temp-list bufs))
1089 (while (not (string-equal
1090 (setq buf (read-buffer
1091 (if (eq read-buffer-function 'ido-read-buffer)
1092 "Next buffer to search (C-j to end): "
1093 "Next buffer to search (RET to end): ")
1094 nil t))
1095 ""))
1096 (add-to-list 'bufs buf)
1097 (setq ido-ignore-item-temp-list bufs))
1098 (nreverse (mapcar #'get-buffer bufs)))
1099 (occur-read-primary-args)))
1100 (occur-1 regexp nlines bufs))
1102 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1103 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1104 Normally BUFREGEXP matches against each buffer's visited file name,
1105 but if you specify a prefix argument, it matches against the buffer name.
1106 See also `multi-occur'."
1107 (interactive
1108 (cons
1109 (let* ((default (car regexp-history))
1110 (input
1111 (read-from-minibuffer
1112 (if current-prefix-arg
1113 "List lines in buffers whose names match regexp: "
1114 "List lines in buffers whose filenames match regexp: ")
1118 'regexp-history)))
1119 (if (equal input "")
1120 default
1121 input))
1122 (occur-read-primary-args)))
1123 (when bufregexp
1124 (occur-1 regexp nil
1125 (delq nil
1126 (mapcar (lambda (buf)
1127 (when (if allbufs
1128 (string-match bufregexp
1129 (buffer-name buf))
1130 (and (buffer-file-name buf)
1131 (string-match bufregexp
1132 (buffer-file-name buf))))
1133 buf))
1134 (buffer-list))))))
1136 (defun occur-1 (regexp nlines bufs &optional buf-name)
1137 (unless (and regexp (not (equal regexp "")))
1138 (error "Occur doesn't work with the empty regexp"))
1139 (unless buf-name
1140 (setq buf-name "*Occur*"))
1141 (let (occur-buf
1142 (active-bufs (delq nil (mapcar #'(lambda (buf)
1143 (when (buffer-live-p buf) buf))
1144 bufs))))
1145 ;; Handle the case where one of the buffers we're searching is the
1146 ;; output buffer. Just rename it.
1147 (when (member buf-name (mapcar 'buffer-name active-bufs))
1148 (with-current-buffer (get-buffer buf-name)
1149 (rename-uniquely)))
1151 ;; Now find or create the output buffer.
1152 ;; If we just renamed that buffer, we will make a new one here.
1153 (setq occur-buf (get-buffer-create buf-name))
1155 (with-current-buffer occur-buf
1156 (if (stringp nlines)
1157 (fundamental-mode) ;; This is for collect opeartion.
1158 (occur-mode))
1159 (let ((inhibit-read-only t)
1160 ;; Don't generate undo entries for creation of the initial contents.
1161 (buffer-undo-list t))
1162 (erase-buffer)
1163 (let ((count
1164 (if (stringp nlines)
1165 ;; Treat nlines as a regexp to collect.
1166 (let ((bufs active-bufs)
1167 (count 0))
1168 (while bufs
1169 (with-current-buffer (car bufs)
1170 (save-excursion
1171 (goto-char (point-min))
1172 (while (re-search-forward regexp nil t)
1173 ;; Insert the replacement regexp.
1174 (let ((str (match-substitute-replacement nlines)))
1175 (if str
1176 (with-current-buffer occur-buf
1177 (insert str)
1178 (setq count (1+ count))
1179 (or (zerop (current-column))
1180 (insert "\n"))))))))
1181 (setq bufs (cdr bufs)))
1182 count)
1183 ;; Perform normal occur.
1184 (occur-engine
1185 regexp active-bufs occur-buf
1186 (or nlines list-matching-lines-default-context-lines)
1187 (if (and case-fold-search search-upper-case)
1188 (isearch-no-upper-case-p regexp t)
1189 case-fold-search)
1190 list-matching-lines-buffer-name-face
1191 nil list-matching-lines-face
1192 (not (eq occur-excluded-properties t))))))
1193 (let* ((bufcount (length active-bufs))
1194 (diff (- (length bufs) bufcount)))
1195 (message "Searched %d buffer%s%s; %s match%s%s"
1196 bufcount (if (= bufcount 1) "" "s")
1197 (if (zerop diff) "" (format " (%d killed)" diff))
1198 (if (zerop count) "no" (format "%d" count))
1199 (if (= count 1) "" "es")
1200 ;; Don't display regexp if with remaining text
1201 ;; it is longer than window-width.
1202 (if (> (+ (length regexp) 42) (window-width))
1203 "" (format " for `%s'" (query-replace-descr regexp)))))
1204 (setq occur-revert-arguments (list regexp nlines bufs))
1205 (if (= count 0)
1206 (kill-buffer occur-buf)
1207 (display-buffer occur-buf)
1208 (setq next-error-last-buffer occur-buf)
1209 (setq buffer-read-only t)
1210 (set-buffer-modified-p nil)
1211 (run-hooks 'occur-hook)))))))
1213 (defun occur-engine (regexp buffers out-buf nlines case-fold
1214 title-face prefix-face match-face keep-props)
1215 (with-current-buffer out-buf
1216 (let ((globalcount 0)
1217 (coding nil)
1218 (case-fold-search case-fold))
1219 ;; Map over all the buffers
1220 (dolist (buf buffers)
1221 (when (buffer-live-p buf)
1222 (let ((matches 0) ;; count of matched lines
1223 (lines 1) ;; line count
1224 (prev-after-lines nil) ;; context lines of prev match
1225 (prev-lines nil) ;; line number of prev match endpt
1226 (matchbeg 0)
1227 (origpt nil)
1228 (begpt nil)
1229 (endpt nil)
1230 (marker nil)
1231 (curstring "")
1232 (ret nil)
1233 (inhibit-field-text-motion t)
1234 (headerpt (with-current-buffer out-buf (point))))
1235 (with-current-buffer buf
1236 (or coding
1237 ;; Set CODING only if the current buffer locally
1238 ;; binds buffer-file-coding-system.
1239 (not (local-variable-p 'buffer-file-coding-system))
1240 (setq coding buffer-file-coding-system))
1241 (save-excursion
1242 (goto-char (point-min)) ;; begin searching in the buffer
1243 (while (not (eobp))
1244 (setq origpt (point))
1245 (when (setq endpt (re-search-forward regexp nil t))
1246 (setq matches (1+ matches)) ;; increment match count
1247 (setq matchbeg (match-beginning 0))
1248 ;; Get beginning of first match line and end of the last.
1249 (save-excursion
1250 (goto-char matchbeg)
1251 (setq begpt (line-beginning-position))
1252 (goto-char endpt)
1253 (setq endpt (line-end-position)))
1254 ;; Sum line numbers up to the first match line.
1255 (setq lines (+ lines (count-lines origpt begpt)))
1256 (setq marker (make-marker))
1257 (set-marker marker matchbeg)
1258 (setq curstring (occur-engine-line begpt endpt keep-props))
1259 ;; Highlight the matches
1260 (let ((len (length curstring))
1261 (start 0))
1262 (while (and (< start len)
1263 (string-match regexp curstring start))
1264 (add-text-properties
1265 (match-beginning 0) (match-end 0)
1266 (append
1267 `(occur-match t)
1268 (when match-face
1269 ;; Use `face' rather than `font-lock-face' here
1270 ;; so as to override faces copied from the buffer.
1271 `(face ,match-face)))
1272 curstring)
1273 (setq start (match-end 0))))
1274 ;; Generate the string to insert for this match
1275 (let* ((match-prefix
1276 ;; Using 7 digits aligns tabs properly.
1277 (apply #'propertize (format "%7d:" lines)
1278 (append
1279 (when prefix-face
1280 `(font-lock-face prefix-face))
1281 `(occur-prefix t mouse-face (highlight)
1282 occur-target ,marker follow-link t
1283 help-echo "mouse-2: go to this occurrence"))))
1284 (match-str
1285 ;; We don't put `mouse-face' on the newline,
1286 ;; because that loses. And don't put it
1287 ;; on context lines to reduce flicker.
1288 (propertize curstring 'mouse-face (list 'highlight)
1289 'occur-target marker
1290 'follow-link t
1291 'help-echo
1292 "mouse-2: go to this occurrence"))
1293 (out-line
1294 (concat
1295 match-prefix
1296 ;; Add non-numeric prefix to all non-first lines
1297 ;; of multi-line matches.
1298 (replace-regexp-in-string
1299 "\n"
1300 "\n :"
1301 match-str)
1302 ;; Add marker at eol, but no mouse props.
1303 (propertize "\n" 'occur-target marker)))
1304 (data
1305 (if (= nlines 0)
1306 ;; The simple display style
1307 out-line
1308 ;; The complex multi-line display style.
1309 (setq ret (occur-context-lines
1310 out-line nlines keep-props begpt endpt
1311 lines prev-lines prev-after-lines))
1312 ;; Set first elem of the returned list to `data',
1313 ;; and the second elem to `prev-after-lines'.
1314 (setq prev-after-lines (nth 1 ret))
1315 (nth 0 ret))))
1316 ;; Actually insert the match display data
1317 (with-current-buffer out-buf
1318 (insert data)))
1319 (goto-char endpt))
1320 (if endpt
1321 (progn
1322 ;; Sum line numbers between first and last match lines.
1323 (setq lines (+ lines (count-lines begpt endpt)
1324 ;; Add 1 for empty last match line since
1325 ;; count-lines returns 1 line less.
1326 (if (and (bolp) (eolp)) 1 0)))
1327 ;; On to the next match...
1328 (forward-line 1))
1329 (goto-char (point-max)))
1330 (setq prev-lines (1- lines)))
1331 ;; Flush remaining context after-lines.
1332 (when prev-after-lines
1333 (with-current-buffer out-buf
1334 (insert (apply #'concat (occur-engine-add-prefix
1335 prev-after-lines)))))))
1336 (when (not (zerop matches)) ;; is the count zero?
1337 (setq globalcount (+ globalcount matches))
1338 (with-current-buffer out-buf
1339 (goto-char headerpt)
1340 (let ((beg (point))
1341 end)
1342 (insert (format "%d match%s%s in buffer: %s\n"
1343 matches (if (= matches 1) "" "es")
1344 ;; Don't display regexp for multi-buffer.
1345 (if (> (length buffers) 1)
1346 "" (format " for \"%s\""
1347 (query-replace-descr regexp)))
1348 (buffer-name buf)))
1349 (setq end (point))
1350 (add-text-properties beg end
1351 (append
1352 (when title-face
1353 `(font-lock-face ,title-face))
1354 `(occur-title ,buf))))
1355 (goto-char (point-min)))))))
1356 ;; Display total match count and regexp for multi-buffer.
1357 (when (and (not (zerop globalcount)) (> (length buffers) 1))
1358 (goto-char (point-min))
1359 (let ((beg (point))
1360 end)
1361 (insert (format "%d match%s total for \"%s\":\n"
1362 globalcount (if (= globalcount 1) "" "es")
1363 (query-replace-descr regexp)))
1364 (setq end (point))
1365 (add-text-properties beg end (when title-face
1366 `(font-lock-face ,title-face))))
1367 (goto-char (point-min)))
1368 (if coding
1369 ;; CODING is buffer-file-coding-system of the first buffer
1370 ;; that locally binds it. Let's use it also for the output
1371 ;; buffer.
1372 (set-buffer-file-coding-system coding))
1373 ;; Return the number of matches
1374 globalcount)))
1376 (defun occur-engine-line (beg end &optional keep-props)
1377 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1378 (text-property-not-all beg end 'fontified t))
1379 (if (fboundp 'jit-lock-fontify-now)
1380 (jit-lock-fontify-now beg end)))
1381 (if (and keep-props (not (eq occur-excluded-properties t)))
1382 (let ((str (buffer-substring beg end)))
1383 (remove-list-of-text-properties
1384 0 (length str) occur-excluded-properties str)
1385 str)
1386 (buffer-substring-no-properties beg end)))
1388 (defun occur-engine-add-prefix (lines)
1389 (mapcar
1390 #'(lambda (line)
1391 (concat " :" line "\n"))
1392 lines))
1394 (defun occur-accumulate-lines (count &optional keep-props pt)
1395 (save-excursion
1396 (when pt
1397 (goto-char pt))
1398 (let ((forwardp (> count 0))
1399 result beg end moved)
1400 (while (not (or (zerop count)
1401 (if forwardp
1402 (eobp)
1403 (and (bobp) (not moved)))))
1404 (setq count (+ count (if forwardp -1 1)))
1405 (setq beg (line-beginning-position)
1406 end (line-end-position))
1407 (push (occur-engine-line beg end keep-props) result)
1408 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1409 (nreverse result))))
1411 ;; Generate context display for occur.
1412 ;; OUT-LINE is the line where the match is.
1413 ;; NLINES and KEEP-PROPS are args to occur-engine.
1414 ;; LINES is line count of the current match,
1415 ;; PREV-LINES is line count of the previous match,
1416 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1417 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1418 ;; then concatenate them all together.
1419 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1420 lines prev-lines prev-after-lines)
1421 ;; Find after- and before-context lines of the current match.
1422 (let ((before-lines
1423 (nreverse (cdr (occur-accumulate-lines
1424 (- (1+ (abs nlines))) keep-props begpt))))
1425 (after-lines
1426 (cdr (occur-accumulate-lines
1427 (1+ nlines) keep-props endpt)))
1428 separator)
1430 ;; Combine after-lines of the previous match
1431 ;; with before-lines of the current match.
1433 (when prev-after-lines
1434 ;; Don't overlap prev after-lines with current before-lines.
1435 (if (>= (+ prev-lines (length prev-after-lines))
1436 (- lines (length before-lines)))
1437 (setq prev-after-lines
1438 (butlast prev-after-lines
1439 (- (length prev-after-lines)
1440 (- lines prev-lines (length before-lines) 1))))
1441 ;; Separate non-overlapping context lines with a dashed line.
1442 (setq separator "-------\n")))
1444 (when prev-lines
1445 ;; Don't overlap current before-lines with previous match line.
1446 (if (<= (- lines (length before-lines))
1447 prev-lines)
1448 (setq before-lines
1449 (nthcdr (- (length before-lines)
1450 (- lines prev-lines 1))
1451 before-lines))
1452 ;; Separate non-overlapping before-context lines.
1453 (unless (> nlines 0)
1454 (setq separator "-------\n"))))
1456 (list
1457 ;; Return a list where the first element is the output line.
1458 (apply #'concat
1459 (append
1460 (and prev-after-lines
1461 (occur-engine-add-prefix prev-after-lines))
1462 (and separator (list separator))
1463 (occur-engine-add-prefix before-lines)
1464 (list out-line)))
1465 ;; And the second element is the list of context after-lines.
1466 (if (> nlines 0) after-lines))))
1469 ;; It would be nice to use \\[...], but there is no reasonable way
1470 ;; to make that display both SPC and Y.
1471 (defconst query-replace-help
1472 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1473 RET or `q' to exit, Period to replace one match and exit,
1474 Comma to replace but not move point immediately,
1475 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1476 C-w to delete match and recursive edit,
1477 C-l to clear the screen, redisplay, and offer same replacement again,
1478 ! to replace all remaining matches with no more questions,
1479 ^ to move point back to previous match,
1480 E to edit the replacement string"
1481 "Help message while in `query-replace'.")
1483 (defvar query-replace-map
1484 (let ((map (make-sparse-keymap)))
1485 (define-key map " " 'act)
1486 (define-key map "\d" 'skip)
1487 (define-key map [delete] 'skip)
1488 (define-key map [backspace] 'skip)
1489 (define-key map "y" 'act)
1490 (define-key map "n" 'skip)
1491 (define-key map "Y" 'act)
1492 (define-key map "N" 'skip)
1493 (define-key map "e" 'edit-replacement)
1494 (define-key map "E" 'edit-replacement)
1495 (define-key map "," 'act-and-show)
1496 (define-key map "q" 'exit)
1497 (define-key map "\r" 'exit)
1498 (define-key map [return] 'exit)
1499 (define-key map "." 'act-and-exit)
1500 (define-key map "\C-r" 'edit)
1501 (define-key map "\C-w" 'delete-and-edit)
1502 (define-key map "\C-l" 'recenter)
1503 (define-key map "!" 'automatic)
1504 (define-key map "^" 'backup)
1505 (define-key map "\C-h" 'help)
1506 (define-key map [f1] 'help)
1507 (define-key map [help] 'help)
1508 (define-key map "?" 'help)
1509 (define-key map "\C-g" 'quit)
1510 (define-key map "\C-]" 'quit)
1511 (define-key map "\e" 'exit-prefix)
1512 (define-key map [escape] 'exit-prefix)
1513 map)
1514 "Keymap that defines the responses to questions in `query-replace'.
1515 The \"bindings\" in this map are not commands; they are answers.
1516 The valid answers include `act', `skip', `act-and-show',
1517 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1518 `automatic', `backup', `exit-prefix', and `help'.")
1520 (defvar multi-query-replace-map
1521 (let ((map (make-sparse-keymap)))
1522 (set-keymap-parent map query-replace-map)
1523 (define-key map "Y" 'automatic-all)
1524 (define-key map "N" 'exit-current)
1525 map)
1526 "Keymap that defines additional bindings for multi-buffer replacements.
1527 It extends its parent map `query-replace-map' with new bindings to
1528 operate on a set of buffers/files. The difference with its parent map
1529 is the additional answers `automatic-all' to replace all remaining
1530 matches in all remaining buffers with no more questions, and
1531 `exit-current' to skip remaining matches in the current buffer
1532 and to continue with the next buffer in the sequence.")
1534 (defun replace-match-string-symbols (n)
1535 "Process a list (and any sub-lists), expanding certain symbols.
1536 Symbol Expands To
1537 N (match-string N) (where N is a string of digits)
1538 #N (string-to-number (match-string N))
1539 & (match-string 0)
1540 #& (string-to-number (match-string 0))
1541 # replace-count
1543 Note that these symbols must be preceded by a backslash in order to
1544 type them using Lisp syntax."
1545 (while (consp n)
1546 (cond
1547 ((consp (car n))
1548 (replace-match-string-symbols (car n))) ;Process sub-list
1549 ((symbolp (car n))
1550 (let ((name (symbol-name (car n))))
1551 (cond
1552 ((string-match "^[0-9]+$" name)
1553 (setcar n (list 'match-string (string-to-number name))))
1554 ((string-match "^#[0-9]+$" name)
1555 (setcar n (list 'string-to-number
1556 (list 'match-string
1557 (string-to-number (substring name 1))))))
1558 ((string= "&" name)
1559 (setcar n '(match-string 0)))
1560 ((string= "#&" name)
1561 (setcar n '(string-to-number (match-string 0))))
1562 ((string= "#" name)
1563 (setcar n 'replace-count))))))
1564 (setq n (cdr n))))
1566 (defun replace-eval-replacement (expression count)
1567 (let* ((replace-count count)
1568 (replacement (eval expression)))
1569 (if (stringp replacement)
1570 replacement
1571 (prin1-to-string replacement t))))
1573 (defun replace-quote (replacement)
1574 "Quote a replacement string.
1575 This just doubles all backslashes in REPLACEMENT and
1576 returns the resulting string. If REPLACEMENT is not
1577 a string, it is first passed through `prin1-to-string'
1578 with the `noescape' argument set.
1580 `match-data' is preserved across the call."
1581 (save-match-data
1582 (replace-regexp-in-string "\\\\" "\\\\"
1583 (if (stringp replacement)
1584 replacement
1585 (prin1-to-string replacement t))
1586 t t)))
1588 (defun replace-loop-through-replacements (data count)
1589 ;; DATA is a vector contaning the following values:
1590 ;; 0 next-rotate-count
1591 ;; 1 repeat-count
1592 ;; 2 next-replacement
1593 ;; 3 replacements
1594 (if (= (aref data 0) count)
1595 (progn
1596 (aset data 0 (+ count (aref data 1)))
1597 (let ((next (cdr (aref data 2))))
1598 (aset data 2 (if (consp next) next (aref data 3))))))
1599 (car (aref data 2)))
1601 (defun replace-match-data (integers reuse &optional new)
1602 "Like `match-data', but markers in REUSE get invalidated.
1603 If NEW is non-nil, it is set and returned instead of fresh data,
1604 but coerced to the correct value of INTEGERS."
1605 (or (and new
1606 (progn
1607 (set-match-data new)
1608 (and (eq new reuse)
1609 (eq (null integers) (markerp (car reuse)))
1610 new)))
1611 (match-data integers reuse t)))
1613 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1614 "Make a replacement with `replace-match', editing `\\?'.
1615 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1616 check for `\\?' is made to save time. MATCH-DATA is used for the
1617 replacement. In case editing is done, it is changed to use markers.
1619 The return value is non-nil if there has been no `\\?' or NOEDIT was
1620 passed in. If LITERAL is set, no checking is done, anyway."
1621 (unless (or literal noedit)
1622 (setq noedit t)
1623 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1624 newtext)
1625 (setq newtext
1626 (read-string "Edit replacement string: "
1627 (prog1
1628 (cons
1629 (replace-match "" t t newtext 3)
1630 (1+ (match-beginning 3)))
1631 (setq match-data
1632 (replace-match-data
1633 nil match-data match-data))))
1634 noedit nil)))
1635 (set-match-data match-data)
1636 (replace-match newtext fixedcase literal)
1637 noedit)
1639 (defvar replace-search-function 'search-forward
1640 "Function to use when searching for strings to replace.
1641 It is used by `query-replace' and `replace-string', and is called
1642 with three arguments, as if it were `search-forward'.")
1644 (defvar replace-re-search-function 're-search-forward
1645 "Function to use when searching for regexps to replace.
1646 It is used by `query-replace-regexp', `replace-regexp',
1647 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1648 It is called with three arguments, as if it were
1649 `re-search-forward'.")
1651 (defun perform-replace (from-string replacements
1652 query-flag regexp-flag delimited-flag
1653 &optional repeat-count map start end)
1654 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1655 Don't use this in your own program unless you want to query and set the mark
1656 just as `query-replace' does. Instead, write a simple loop like this:
1658 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1659 (replace-match \"foobar\" nil nil))
1661 which will run faster and probably do exactly what you want. Please
1662 see the documentation of `replace-match' to find out how to simulate
1663 `case-replace'.
1665 This function returns nil if and only if there were no matches to
1666 make, or the user didn't cancel the call."
1667 (or map (setq map query-replace-map))
1668 (and query-flag minibuffer-auto-raise
1669 (raise-frame (window-frame (minibuffer-window))))
1670 (let* ((case-fold-search
1671 (if (and case-fold-search search-upper-case)
1672 (isearch-no-upper-case-p from-string regexp-flag)
1673 case-fold-search))
1674 (nocasify (not (and case-replace case-fold-search)))
1675 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1676 (search-function
1677 (if regexp-flag
1678 replace-re-search-function
1679 replace-search-function))
1680 (search-string from-string)
1681 (real-match-data nil) ; The match data for the current match.
1682 (next-replacement nil)
1683 ;; This is non-nil if we know there is nothing for the user
1684 ;; to edit in the replacement.
1685 (noedit nil)
1686 (keep-going t)
1687 (stack nil)
1688 (replace-count 0)
1689 (nonempty-match nil)
1690 (multi-buffer nil)
1691 (recenter-last-op nil) ; Start cycling order with initial position.
1693 ;; If non-nil, it is marker saying where in the buffer to stop.
1694 (limit nil)
1696 ;; Data for the next match. If a cons, it has the same format as
1697 ;; (match-data); otherwise it is t if a match is possible at point.
1698 (match-again t)
1700 (message
1701 (if query-flag
1702 (apply 'propertize
1703 (substitute-command-keys
1704 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1705 minibuffer-prompt-properties))))
1707 ;; If region is active, in Transient Mark mode, operate on region.
1708 (when start
1709 (setq limit (copy-marker (max start end)))
1710 (goto-char (min start end))
1711 (deactivate-mark))
1713 ;; If last typed key in previous call of multi-buffer perform-replace
1714 ;; was `automatic-all', don't ask more questions in next files
1715 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
1716 (setq query-flag nil multi-buffer t))
1718 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1719 ;; containing a function and its first argument. The function is
1720 ;; called to generate each replacement like this:
1721 ;; (funcall (car replacements) (cdr replacements) replace-count)
1722 ;; It must return a string.
1723 (cond
1724 ((stringp replacements)
1725 (setq next-replacement replacements
1726 replacements nil))
1727 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1728 (or repeat-count (setq repeat-count 1))
1729 (setq replacements (cons 'replace-loop-through-replacements
1730 (vector repeat-count repeat-count
1731 replacements replacements)))))
1733 (if delimited-flag
1734 (setq search-function 're-search-forward
1735 search-string (concat "\\b"
1736 (if regexp-flag from-string
1737 (regexp-quote from-string))
1738 "\\b")))
1739 (when query-replace-lazy-highlight
1740 (setq isearch-lazy-highlight-last-string nil))
1742 (push-mark)
1743 (undo-boundary)
1744 (unwind-protect
1745 ;; Loop finding occurrences that perhaps should be replaced.
1746 (while (and keep-going
1747 (not (or (eobp) (and limit (>= (point) limit))))
1748 ;; Use the next match if it is already known;
1749 ;; otherwise, search for a match after moving forward
1750 ;; one char if progress is required.
1751 (setq real-match-data
1752 (cond ((consp match-again)
1753 (goto-char (nth 1 match-again))
1754 (replace-match-data
1755 t real-match-data match-again))
1756 ;; MATCH-AGAIN non-nil means accept an
1757 ;; adjacent match.
1758 (match-again
1759 (and
1760 (funcall search-function search-string
1761 limit t)
1762 ;; For speed, use only integers and
1763 ;; reuse the list used last time.
1764 (replace-match-data t real-match-data)))
1765 ((and (< (1+ (point)) (point-max))
1766 (or (null limit)
1767 (< (1+ (point)) limit)))
1768 ;; If not accepting adjacent matches,
1769 ;; move one char to the right before
1770 ;; searching again. Undo the motion
1771 ;; if the search fails.
1772 (let ((opoint (point)))
1773 (forward-char 1)
1774 (if (funcall
1775 search-function search-string
1776 limit t)
1777 (replace-match-data
1778 t real-match-data)
1779 (goto-char opoint)
1780 nil))))))
1782 ;; Record whether the match is nonempty, to avoid an infinite loop
1783 ;; repeatedly matching the same empty string.
1784 (setq nonempty-match
1785 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1787 ;; If the match is empty, record that the next one can't be
1788 ;; adjacent.
1790 ;; Otherwise, if matching a regular expression, do the next
1791 ;; match now, since the replacement for this match may
1792 ;; affect whether the next match is adjacent to this one.
1793 ;; If that match is empty, don't use it.
1794 (setq match-again
1795 (and nonempty-match
1796 (or (not regexp-flag)
1797 (and (looking-at search-string)
1798 (let ((match (match-data)))
1799 (and (/= (nth 0 match) (nth 1 match))
1800 match))))))
1802 ;; Optionally ignore matches that have a read-only property.
1803 (unless (and query-replace-skip-read-only
1804 (text-property-not-all
1805 (nth 0 real-match-data) (nth 1 real-match-data)
1806 'read-only nil))
1808 ;; Calculate the replacement string, if necessary.
1809 (when replacements
1810 (set-match-data real-match-data)
1811 (setq next-replacement
1812 (funcall (car replacements) (cdr replacements)
1813 replace-count)))
1814 (if (not query-flag)
1815 (progn
1816 (unless (or literal noedit)
1817 (replace-highlight
1818 (nth 0 real-match-data) (nth 1 real-match-data)
1819 start end search-string
1820 (or delimited-flag regexp-flag) case-fold-search))
1821 (setq noedit
1822 (replace-match-maybe-edit
1823 next-replacement nocasify literal
1824 noedit real-match-data)
1825 replace-count (1+ replace-count)))
1826 (undo-boundary)
1827 (let (done replaced key def)
1828 ;; Loop reading commands until one of them sets done,
1829 ;; which means it has finished handling this
1830 ;; occurrence. Any command that sets `done' should
1831 ;; leave behind proper match data for the stack.
1832 ;; Commands not setting `done' need to adjust
1833 ;; `real-match-data'.
1834 (while (not done)
1835 (set-match-data real-match-data)
1836 (replace-highlight
1837 (match-beginning 0) (match-end 0)
1838 start end search-string
1839 (or delimited-flag regexp-flag) case-fold-search)
1840 ;; Bind message-log-max so we don't fill up the message log
1841 ;; with a bunch of identical messages.
1842 (let ((message-log-max nil)
1843 (replacement-presentation
1844 (if query-replace-show-replacement
1845 (save-match-data
1846 (set-match-data real-match-data)
1847 (match-substitute-replacement next-replacement
1848 nocasify literal))
1849 next-replacement)))
1850 (message message
1851 (query-replace-descr from-string)
1852 (query-replace-descr replacement-presentation)))
1853 (setq key (read-event))
1854 ;; Necessary in case something happens during read-event
1855 ;; that clobbers the match data.
1856 (set-match-data real-match-data)
1857 (setq key (vector key))
1858 (setq def (lookup-key map key))
1859 ;; Restore the match data while we process the command.
1860 (cond ((eq def 'help)
1861 (with-output-to-temp-buffer "*Help*"
1862 (princ
1863 (concat "Query replacing "
1864 (if delimited-flag "word " "")
1865 (if regexp-flag "regexp " "")
1866 from-string " with "
1867 next-replacement ".\n\n"
1868 (substitute-command-keys
1869 query-replace-help)))
1870 (with-current-buffer standard-output
1871 (help-mode))))
1872 ((eq def 'exit)
1873 (setq keep-going nil)
1874 (setq done t))
1875 ((eq def 'exit-current)
1876 (setq multi-buffer t keep-going nil done t))
1877 ((eq def 'backup)
1878 (if stack
1879 (let ((elt (pop stack)))
1880 (goto-char (nth 0 elt))
1881 (setq replaced (nth 1 elt)
1882 real-match-data
1883 (replace-match-data
1884 t real-match-data
1885 (nth 2 elt))))
1886 (message "No previous match")
1887 (ding 'no-terminate)
1888 (sit-for 1)))
1889 ((eq def 'act)
1890 (or replaced
1891 (setq noedit
1892 (replace-match-maybe-edit
1893 next-replacement nocasify literal
1894 noedit real-match-data)
1895 replace-count (1+ replace-count)))
1896 (setq done t replaced t))
1897 ((eq def 'act-and-exit)
1898 (or replaced
1899 (setq noedit
1900 (replace-match-maybe-edit
1901 next-replacement nocasify literal
1902 noedit real-match-data)
1903 replace-count (1+ replace-count)))
1904 (setq keep-going nil)
1905 (setq done t replaced t))
1906 ((eq def 'act-and-show)
1907 (if (not replaced)
1908 (setq noedit
1909 (replace-match-maybe-edit
1910 next-replacement nocasify literal
1911 noedit real-match-data)
1912 replace-count (1+ replace-count)
1913 real-match-data (replace-match-data
1914 t real-match-data)
1915 replaced t)))
1916 ((or (eq def 'automatic) (eq def 'automatic-all))
1917 (or replaced
1918 (setq noedit
1919 (replace-match-maybe-edit
1920 next-replacement nocasify literal
1921 noedit real-match-data)
1922 replace-count (1+ replace-count)))
1923 (setq done t query-flag nil replaced t)
1924 (if (eq def 'automatic-all) (setq multi-buffer t)))
1925 ((eq def 'skip)
1926 (setq done t))
1927 ((eq def 'recenter)
1928 ;; `this-command' has the value `query-replace',
1929 ;; so we need to bind it to `recenter-top-bottom'
1930 ;; to allow it to detect a sequence of `C-l'.
1931 (let ((this-command 'recenter-top-bottom)
1932 (last-command 'recenter-top-bottom))
1933 (recenter-top-bottom)))
1934 ((eq def 'edit)
1935 (let ((opos (point-marker)))
1936 (setq real-match-data (replace-match-data
1937 nil real-match-data
1938 real-match-data))
1939 (goto-char (match-beginning 0))
1940 (save-excursion
1941 (save-window-excursion
1942 (recursive-edit)))
1943 (goto-char opos)
1944 (set-marker opos nil))
1945 ;; Before we make the replacement,
1946 ;; decide whether the search string
1947 ;; can match again just after this match.
1948 (if (and regexp-flag nonempty-match)
1949 (setq match-again (and (looking-at search-string)
1950 (match-data)))))
1951 ;; Edit replacement.
1952 ((eq def 'edit-replacement)
1953 (setq real-match-data (replace-match-data
1954 nil real-match-data
1955 real-match-data)
1956 next-replacement
1957 (read-string "Edit replacement string: "
1958 next-replacement)
1959 noedit nil)
1960 (if replaced
1961 (set-match-data real-match-data)
1962 (setq noedit
1963 (replace-match-maybe-edit
1964 next-replacement nocasify literal noedit
1965 real-match-data)
1966 replaced t))
1967 (setq done t))
1969 ((eq def 'delete-and-edit)
1970 (replace-match "" t t)
1971 (setq real-match-data (replace-match-data
1972 nil real-match-data))
1973 (replace-dehighlight)
1974 (save-excursion (recursive-edit))
1975 (setq replaced t))
1976 ;; Note: we do not need to treat `exit-prefix'
1977 ;; specially here, since we reread
1978 ;; any unrecognized character.
1980 (setq this-command 'mode-exited)
1981 (setq keep-going nil)
1982 (setq unread-command-events
1983 (append (listify-key-sequence key)
1984 unread-command-events))
1985 (setq done t)))
1986 (when query-replace-lazy-highlight
1987 ;; Force lazy rehighlighting only after replacements.
1988 (if (not (memq def '(skip backup)))
1989 (setq isearch-lazy-highlight-last-string nil)))
1990 (unless (eq def 'recenter)
1991 ;; Reset recenter cycling order to initial position.
1992 (setq recenter-last-op nil)))
1993 ;; Record previous position for ^ when we move on.
1994 ;; Change markers to numbers in the match data
1995 ;; since lots of markers slow down editing.
1996 (push (list (point) replaced
1997 ;;; If the replacement has already happened, all we need is the
1998 ;;; current match start and end. We could get this with a trivial
1999 ;;; match like
2000 ;;; (save-excursion (goto-char (match-beginning 0))
2001 ;;; (search-forward (match-string 0))
2002 ;;; (match-data t))
2003 ;;; if we really wanted to avoid manually constructing match data.
2004 ;;; Adding current-buffer is necessary so that match-data calls can
2005 ;;; return markers which are appropriate for editing.
2006 (if replaced
2007 (list
2008 (match-beginning 0)
2009 (match-end 0)
2010 (current-buffer))
2011 (match-data t)))
2012 stack)))))
2014 (replace-dehighlight))
2015 (or unread-command-events
2016 (message "Replaced %d occurrence%s"
2017 replace-count
2018 (if (= replace-count 1) "" "s")))
2019 (or (and keep-going stack) multi-buffer)))
2021 (defvar isearch-error)
2022 (defvar isearch-forward)
2023 (defvar isearch-case-fold-search)
2024 (defvar isearch-string)
2026 (defvar replace-overlay nil)
2028 (defun replace-highlight (match-beg match-end range-beg range-end
2029 string regexp case-fold)
2030 (if query-replace-highlight
2031 (if replace-overlay
2032 (move-overlay replace-overlay match-beg match-end (current-buffer))
2033 (setq replace-overlay (make-overlay match-beg match-end))
2034 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2035 (overlay-put replace-overlay 'face 'query-replace)))
2036 (if query-replace-lazy-highlight
2037 (let ((isearch-string string)
2038 (isearch-regexp regexp)
2039 (search-whitespace-regexp nil)
2040 (isearch-case-fold-search case-fold)
2041 (isearch-forward t)
2042 (isearch-error nil))
2043 ;; Set isearch-word to nil because word-replace is regexp-based,
2044 ;; so `isearch-search-fun' should not use `word-search-forward'.
2045 (if (and isearch-word isearch-regexp) (setq isearch-word nil))
2046 (isearch-lazy-highlight-new-loop range-beg range-end))))
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)))
2055 ;;; replace.el ends here