* lisp/vc/vc-svn.el (vc-svn-diff): Use `diff-command' instead of the
[emacs.git] / lisp / replace.el
blobd89a511a0982433d323c481cb6915f8c136f02d1
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 (defun query-replace-descr (string)
102 (mapconcat 'isearch-text-char-description string ""))
104 (defun query-replace-read-from (prompt regexp-flag)
105 "Query and return the `from' argument of a query-replace operation.
106 The return value can also be a pair (FROM . TO) indicating that the user
107 wants to replace FROM with TO."
108 (if query-replace-interactive
109 (car (if regexp-flag regexp-search-ring search-ring))
110 (let* ((history-add-new-input nil)
111 (from
112 ;; The save-excursion here is in case the user marks and copies
113 ;; a region in order to specify the minibuffer input.
114 ;; That should not clobber the region for the query-replace itself.
115 (save-excursion
116 (read-from-minibuffer
117 (if query-replace-defaults
118 (format "%s (default %s -> %s): " prompt
119 (query-replace-descr (car query-replace-defaults))
120 (query-replace-descr (cdr query-replace-defaults)))
121 (format "%s: " prompt))
122 nil nil nil
123 query-replace-from-history-variable
124 nil t))))
125 (if (and (zerop (length from)) query-replace-defaults)
126 (cons (car query-replace-defaults)
127 (query-replace-compile-replacement
128 (cdr query-replace-defaults) regexp-flag))
129 (add-to-history query-replace-from-history-variable from nil t)
130 ;; Warn if user types \n or \t, but don't reject the input.
131 (and regexp-flag
132 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
133 (let ((match (match-string 3 from)))
134 (cond
135 ((string= match "\\n")
136 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
137 ((string= match "\\t")
138 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
139 (sit-for 2)))
140 from))))
142 (defun query-replace-compile-replacement (to regexp-flag)
143 "Maybe convert a regexp replacement TO to Lisp.
144 Returns a list suitable for `perform-replace' if necessary,
145 the original string if not."
146 (if (and regexp-flag
147 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
148 (let (pos list char)
149 (while
150 (progn
151 (setq pos (match-end 0))
152 (push (substring to 0 (- pos 2)) list)
153 (setq char (aref to (1- pos))
154 to (substring to pos))
155 (cond ((eq char ?\#)
156 (push '(number-to-string replace-count) list))
157 ((eq char ?\,)
158 (setq pos (read-from-string to))
159 (push `(replace-quote ,(car pos)) list)
160 (let ((end
161 ;; Swallow a space after a symbol
162 ;; if there is a space.
163 (if (and (or (symbolp (car pos))
164 ;; Swallow a space after 'foo
165 ;; but not after (quote foo).
166 (and (eq (car-safe (car pos)) 'quote)
167 (not (= ?\( (aref to 0)))))
168 (eq (string-match " " to (cdr pos))
169 (cdr pos)))
170 (1+ (cdr pos))
171 (cdr pos))))
172 (setq to (substring to end)))))
173 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
174 (setq to (nreverse (delete "" (cons to list))))
175 (replace-match-string-symbols to)
176 (cons 'replace-eval-replacement
177 (if (cdr to)
178 (cons 'concat to)
179 (car to))))
180 to))
183 (defun query-replace-read-to (from prompt regexp-flag)
184 "Query and return the `to' argument of a query-replace operation."
185 (query-replace-compile-replacement
186 (save-excursion
187 (let* ((history-add-new-input nil)
188 (to (read-from-minibuffer
189 (format "%s %s with: " prompt (query-replace-descr from))
190 nil nil nil
191 query-replace-to-history-variable from t)))
192 (add-to-history query-replace-to-history-variable to nil t)
193 (setq query-replace-defaults (cons from to))
194 to))
195 regexp-flag))
197 (defun query-replace-read-args (prompt regexp-flag &optional noerror)
198 (unless noerror
199 (barf-if-buffer-read-only))
200 (let* ((from (query-replace-read-from prompt regexp-flag))
201 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
202 (query-replace-read-to from prompt regexp-flag))))
203 (list from to current-prefix-arg)))
205 (defun query-replace (from-string to-string &optional delimited start end)
206 "Replace some occurrences of FROM-STRING with TO-STRING.
207 As each match is found, the user must type a character saying
208 what to do with it. For directions, type \\[help-command] at that time.
210 In Transient Mark mode, if the mark is active, operate on the contents
211 of the region. Otherwise, operate from point to the end of the buffer.
213 If `query-replace-interactive' is non-nil, the last incremental search
214 string is used as FROM-STRING--you don't have to specify it with the
215 minibuffer.
217 Matching is independent of case if `case-fold-search' is non-nil and
218 FROM-STRING has no uppercase letters. Replacement transfers the case
219 pattern of the old text to the new text, if `case-replace' and
220 `case-fold-search' are non-nil and FROM-STRING has no uppercase
221 letters. \(Transferring the case pattern means that if the old text
222 matched is all caps, or capitalized, then its replacement is upcased
223 or capitalized.)
225 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
226 only matches surrounded by word boundaries.
227 Fourth and fifth arg START and END specify the region to operate on.
229 To customize possible responses, change the \"bindings\" in `query-replace-map'."
230 (interactive
231 (let ((common
232 (query-replace-read-args
233 (concat "Query replace"
234 (if current-prefix-arg " word" "")
235 (if (and transient-mark-mode mark-active) " in region" ""))
236 nil)))
237 (list (nth 0 common) (nth 1 common) (nth 2 common)
238 ;; These are done separately here
239 ;; so that command-history will record these expressions
240 ;; rather than the values they had this time.
241 (if (and transient-mark-mode mark-active)
242 (region-beginning))
243 (if (and transient-mark-mode mark-active)
244 (region-end)))))
245 (perform-replace from-string to-string t nil delimited nil nil start end))
247 (define-key esc-map "%" 'query-replace)
249 (defun query-replace-regexp (regexp to-string &optional delimited start end)
250 "Replace some things after point matching REGEXP with TO-STRING.
251 As each match is found, the user must type a character saying
252 what to do with it. For directions, type \\[help-command] at that time.
254 In Transient Mark mode, if the mark is active, operate on the contents
255 of the region. Otherwise, operate from point to the end of the buffer.
257 If `query-replace-interactive' is non-nil, the last incremental search
258 regexp is used as REGEXP--you don't have to specify it with the
259 minibuffer.
261 Matching is independent of case if `case-fold-search' is non-nil and
262 REGEXP has no uppercase letters. Replacement transfers the case
263 pattern of the old text to the new text, if `case-replace' and
264 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
265 \(Transferring the case pattern means that if the old text matched is
266 all caps, or capitalized, then its replacement is upcased or
267 capitalized.)
269 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
270 only matches surrounded by word boundaries.
271 Fourth and fifth arg START and END specify the region to operate on.
273 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
274 and `\\=\\N' (where N is a digit) stands for
275 whatever what matched the Nth `\\(...\\)' in REGEXP.
276 `\\?' lets you edit the replacement text in the minibuffer
277 at the given position for each replacement.
279 In interactive calls, the replacement text can contain `\\,'
280 followed by a Lisp expression. Each
281 replacement evaluates that expression to compute the replacement
282 string. Inside of that expression, `\\&' is a string denoting the
283 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
284 for the whole or a partial match converted to a number with
285 `string-to-number', and `\\#' itself for the number of replacements
286 done so far (starting with zero).
288 If the replacement expression is a symbol, write a space after it
289 to terminate it. One space there, if any, will be discarded.
291 When using those Lisp features interactively in the replacement
292 text, TO-STRING is actually made a list instead of a string.
293 Use \\[repeat-complex-command] after this command for details."
294 (interactive
295 (let ((common
296 (query-replace-read-args
297 (concat "Query replace"
298 (if current-prefix-arg " word" "")
299 " regexp"
300 (if (and transient-mark-mode mark-active) " in region" ""))
301 t)))
302 (list (nth 0 common) (nth 1 common) (nth 2 common)
303 ;; These are done separately here
304 ;; so that command-history will record these expressions
305 ;; rather than the values they had this time.
306 (if (and transient-mark-mode mark-active)
307 (region-beginning))
308 (if (and transient-mark-mode mark-active)
309 (region-end)))))
310 (perform-replace regexp to-string t t delimited nil nil start end))
312 (define-key esc-map [?\C-%] 'query-replace-regexp)
314 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
315 "Replace some things after point matching REGEXP with the result of TO-EXPR.
317 Interactive use of this function is deprecated in favor of the
318 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
319 using `search-forward-regexp' and `replace-match' is preferred.
321 As each match is found, the user must type a character saying
322 what to do with it. For directions, type \\[help-command] at that time.
324 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
325 reference `replace-count' to get the number of replacements already made.
326 If the result of TO-EXPR is not a string, it is converted to one using
327 `prin1-to-string' with the NOESCAPE argument (which see).
329 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
330 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
331 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
332 Use `\\#&' or `\\#N' if you want a number instead of a string.
333 In interactive use, `\\#' in itself stands for `replace-count'.
335 In Transient Mark mode, if the mark is active, operate on the contents
336 of the region. Otherwise, operate from point to the end of the buffer.
338 If `query-replace-interactive' is non-nil, the last incremental search
339 regexp is used as REGEXP--you don't have to specify it with the
340 minibuffer.
342 Preserves case in each replacement if `case-replace' and `case-fold-search'
343 are non-nil and REGEXP has no uppercase letters.
345 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
346 only matches that are surrounded by word boundaries.
347 Fourth and fifth arg START and END specify the region to operate on."
348 (interactive
349 (progn
350 (barf-if-buffer-read-only)
351 (let* ((from
352 ;; Let-bind the history var to disable the "foo -> bar" default.
353 ;; Maybe we shouldn't disable this default, but for now I'll
354 ;; leave it off. --Stef
355 (let ((query-replace-to-history-variable nil))
356 (query-replace-read-from "Query replace regexp" t)))
357 (to (list (read-from-minibuffer
358 (format "Query replace regexp %s with eval: "
359 (query-replace-descr from))
360 nil nil t query-replace-to-history-variable from t))))
361 ;; We make TO a list because replace-match-string-symbols requires one,
362 ;; and the user might enter a single token.
363 (replace-match-string-symbols to)
364 (list from (car to) current-prefix-arg
365 (if (and transient-mark-mode mark-active)
366 (region-beginning))
367 (if (and transient-mark-mode mark-active)
368 (region-end))))))
369 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
370 t 'literal delimited nil nil start end))
372 (make-obsolete 'query-replace-regexp-eval
373 "for interactive use, use the special `\\,' feature of
374 `query-replace-regexp' instead. Non-interactively, a loop
375 using `search-forward-regexp' and `replace-match' is preferred." "22.1")
377 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
378 "Replace some matches for REGEXP with various strings, in rotation.
379 The second argument TO-STRINGS contains the replacement strings, separated
380 by spaces. This command works like `query-replace-regexp' except that
381 each successive replacement uses the next successive replacement string,
382 wrapping around from the last such string to the first.
384 In Transient Mark mode, if the mark is active, operate on the contents
385 of the region. Otherwise, operate from point to the end of the buffer.
387 Non-interactively, TO-STRINGS may be a list of replacement strings.
389 If `query-replace-interactive' is non-nil, the last incremental search
390 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
392 A prefix argument N says to use each replacement string N times
393 before rotating to the next.
394 Fourth and fifth arg START and END specify the region to operate on."
395 (interactive
396 (let* ((from (if query-replace-interactive
397 (car regexp-search-ring)
398 (read-from-minibuffer "Map query replace (regexp): "
399 nil nil nil
400 query-replace-from-history-variable
401 nil t)))
402 (to (read-from-minibuffer
403 (format "Query replace %s with (space-separated strings): "
404 (query-replace-descr from))
405 nil nil nil
406 query-replace-to-history-variable from t)))
407 (list from to
408 (and current-prefix-arg
409 (prefix-numeric-value current-prefix-arg))
410 (if (and transient-mark-mode mark-active)
411 (region-beginning))
412 (if (and transient-mark-mode mark-active)
413 (region-end)))))
414 (let (replacements)
415 (if (listp to-strings)
416 (setq replacements to-strings)
417 (while (/= (length to-strings) 0)
418 (if (string-match " " to-strings)
419 (setq replacements
420 (append replacements
421 (list (substring to-strings 0
422 (string-match " " to-strings))))
423 to-strings (substring to-strings
424 (1+ (string-match " " to-strings))))
425 (setq replacements (append replacements (list to-strings))
426 to-strings ""))))
427 (perform-replace regexp replacements t t nil n nil start end)))
429 (defun replace-string (from-string to-string &optional delimited start end)
430 "Replace occurrences of FROM-STRING with TO-STRING.
431 Preserve case in each match if `case-replace' and `case-fold-search'
432 are non-nil and FROM-STRING has no uppercase letters.
433 \(Preserving case means that if the string matched is all caps, or capitalized,
434 then its replacement is upcased or capitalized.)
436 In Transient Mark mode, if the mark is active, operate on the contents
437 of the region. Otherwise, operate from point to the end of the buffer.
439 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
440 only matches surrounded by word boundaries.
441 Fourth and fifth arg START and END specify the region to operate on.
443 If `query-replace-interactive' is non-nil, the last incremental search
444 string is used as FROM-STRING--you don't have to specify it with the
445 minibuffer.
447 This function is usually the wrong thing to use in a Lisp program.
448 What you probably want is a loop like this:
449 (while (search-forward FROM-STRING nil t)
450 (replace-match TO-STRING nil t))
451 which will run faster and will not set the mark or print anything.
452 \(You may need a more complex loop if FROM-STRING can match the null string
453 and TO-STRING is also null.)"
454 (interactive
455 (let ((common
456 (query-replace-read-args
457 (concat "Replace"
458 (if current-prefix-arg " word" "")
459 " string"
460 (if (and transient-mark-mode mark-active) " in region" ""))
461 nil)))
462 (list (nth 0 common) (nth 1 common) (nth 2 common)
463 (if (and transient-mark-mode mark-active)
464 (region-beginning))
465 (if (and transient-mark-mode mark-active)
466 (region-end)))))
467 (perform-replace from-string to-string nil nil delimited nil nil start end))
469 (defun replace-regexp (regexp to-string &optional delimited start end)
470 "Replace things after point matching REGEXP with TO-STRING.
471 Preserve case in each match if `case-replace' and `case-fold-search'
472 are non-nil and REGEXP has no uppercase letters.
474 In Transient Mark mode, if the mark is active, operate on the contents
475 of the region. Otherwise, operate from point to the end of the buffer.
477 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
478 only matches surrounded by word boundaries.
479 Fourth and fifth arg START and END specify the region to operate on.
481 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
482 and `\\=\\N' (where N is a digit) stands for
483 whatever what matched the Nth `\\(...\\)' in REGEXP.
484 `\\?' lets you edit the replacement text in the minibuffer
485 at the given position for each replacement.
487 In interactive calls, the replacement text may contain `\\,'
488 followed by a Lisp expression used as part of the replacement
489 text. Inside of that expression, `\\&' is a string denoting the
490 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
491 numeric values from `string-to-number', and `\\#' itself for
492 `replace-count', the number of replacements occurred so far.
494 If your Lisp expression is an identifier and the next letter in
495 the replacement string would be interpreted as part of it, you
496 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
497 for this particular case you may also enter `\\#' in the
498 replacement text directly.
500 When using those Lisp features interactively in the replacement
501 text, TO-STRING is actually made a list instead of a string.
502 Use \\[repeat-complex-command] after this command for details.
504 If `query-replace-interactive' is non-nil, the last incremental search
505 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
507 This function is usually the wrong thing to use in a Lisp program.
508 What you probably want is a loop like this:
509 (while (re-search-forward REGEXP nil t)
510 (replace-match TO-STRING nil nil))
511 which will run faster and will not set the mark or print anything."
512 (interactive
513 (let ((common
514 (query-replace-read-args
515 (concat "Replace"
516 (if current-prefix-arg " word" "")
517 " regexp"
518 (if (and transient-mark-mode mark-active) " in region" ""))
519 t)))
520 (list (nth 0 common) (nth 1 common) (nth 2 common)
521 (if (and transient-mark-mode mark-active)
522 (region-beginning))
523 (if (and transient-mark-mode mark-active)
524 (region-end)))))
525 (perform-replace regexp to-string nil t delimited nil nil start end))
528 (defvar regexp-history nil
529 "History list for some commands that read regular expressions.
531 Maximum length of the history list is determined by the value
532 of `history-length', which see.")
534 (defvar occur-collect-regexp-history '("\\1")
535 "History of regexp for occur's collect operation")
537 (defun read-regexp (prompt &optional default-value)
538 "Read regexp as a string using the regexp history and some useful defaults.
539 Prompt for a regular expression with PROMPT (without a colon and
540 space) in the minibuffer. The optional argument DEFAULT-VALUE
541 provides the value to display in the minibuffer prompt that is
542 returned if the user just types RET.
543 Values available via M-n are the string at point, the last isearch
544 regexp, the last isearch string, and the last replacement regexp."
545 (let* ((defaults
546 (list (regexp-quote
547 (or (funcall (or find-tag-default-function
548 (get major-mode 'find-tag-default-function)
549 'find-tag-default))
550 ""))
551 (car regexp-search-ring)
552 (regexp-quote (or (car search-ring) ""))
553 (car (symbol-value
554 query-replace-from-history-variable))))
555 (defaults (delete-dups (delq nil (delete "" defaults))))
556 ;; Don't add automatically the car of defaults for empty input
557 (history-add-new-input nil)
558 (input
559 (read-from-minibuffer
560 (if default-value
561 (format "%s (default %s): " prompt
562 (query-replace-descr default-value))
563 (format "%s: " prompt))
564 nil nil nil 'regexp-history defaults t)))
565 (if (equal input "")
566 (or default-value input)
567 (prog1 input
568 (add-to-history 'regexp-history input)))))
571 (defalias 'delete-non-matching-lines 'keep-lines)
572 (defalias 'delete-matching-lines 'flush-lines)
573 (defalias 'count-matches 'how-many)
576 (defun keep-lines-read-args (prompt)
577 "Read arguments for `keep-lines' and friends.
578 Prompt for a regexp with PROMPT.
579 Value is a list, (REGEXP)."
580 (list (read-regexp prompt) nil nil t))
582 (defun keep-lines (regexp &optional rstart rend interactive)
583 "Delete all lines except those containing matches for REGEXP.
584 A match split across lines preserves all the lines it lies in.
585 When called from Lisp (and usually interactively as well, see below)
586 applies to all lines starting after point.
588 If REGEXP contains upper case characters (excluding those preceded by `\\')
589 and `search-upper-case' is non-nil, the matching is case-sensitive.
591 Second and third arg RSTART and REND specify the region to operate on.
592 This command operates on (the accessible part of) all lines whose
593 accessible part is entirely contained in the region determined by RSTART
594 and REND. (A newline ending a line counts as part of that line.)
596 Interactively, in Transient Mark mode when the mark is active, operate
597 on all lines whose accessible part is entirely contained in the region.
598 Otherwise, the command applies to all lines starting after point.
599 When calling this function from Lisp, you can pretend that it was
600 called interactively by passing a non-nil INTERACTIVE argument.
602 This function starts looking for the next match from the end of
603 the previous match. Hence, it ignores matches that overlap
604 a previously found match."
606 (interactive
607 (progn
608 (barf-if-buffer-read-only)
609 (keep-lines-read-args "Keep lines containing match for regexp")))
610 (if rstart
611 (progn
612 (goto-char (min rstart rend))
613 (setq rend
614 (progn
615 (save-excursion
616 (goto-char (max rstart rend))
617 (unless (or (bolp) (eobp))
618 (forward-line 0))
619 (point-marker)))))
620 (if (and interactive transient-mark-mode mark-active)
621 (setq rstart (region-beginning)
622 rend (progn
623 (goto-char (region-end))
624 (unless (or (bolp) (eobp))
625 (forward-line 0))
626 (point-marker)))
627 (setq rstart (point)
628 rend (point-max-marker)))
629 (goto-char rstart))
630 (save-excursion
631 (or (bolp) (forward-line 1))
632 (let ((start (point))
633 (case-fold-search
634 (if (and case-fold-search search-upper-case)
635 (isearch-no-upper-case-p regexp t)
636 case-fold-search)))
637 (while (< (point) rend)
638 ;; Start is first char not preserved by previous match.
639 (if (not (re-search-forward regexp rend 'move))
640 (delete-region start rend)
641 (let ((end (save-excursion (goto-char (match-beginning 0))
642 (forward-line 0)
643 (point))))
644 ;; Now end is first char preserved by the new match.
645 (if (< start end)
646 (delete-region start end))))
648 (setq start (save-excursion (forward-line 1) (point)))
649 ;; If the match was empty, avoid matching again at same place.
650 (and (< (point) rend)
651 (= (match-beginning 0) (match-end 0))
652 (forward-char 1)))))
653 (set-marker rend nil)
654 nil)
657 (defun flush-lines (regexp &optional rstart rend interactive)
658 "Delete lines containing matches for REGEXP.
659 When called from Lisp (and usually when called interactively as
660 well, see below), applies to the part of the buffer after point.
661 The line point is in is deleted if and only if it contains a
662 match for regexp starting after point.
664 If REGEXP contains upper case characters (excluding those preceded by `\\')
665 and `search-upper-case' is non-nil, the matching is case-sensitive.
667 Second and third arg RSTART and REND specify the region to operate on.
668 Lines partially contained in this region are deleted if and only if
669 they contain a match entirely contained in it.
671 Interactively, in Transient Mark mode when the mark is active, operate
672 on the contents of the region. Otherwise, operate from point to the
673 end of (the accessible portion of) the buffer. When calling this function
674 from Lisp, you can pretend that it was called interactively by passing
675 a non-nil INTERACTIVE argument.
677 If a match is split across lines, all the lines it lies in are deleted.
678 They are deleted _before_ looking for the next match. Hence, a match
679 starting on the same line at which another match ended is ignored."
681 (interactive
682 (progn
683 (barf-if-buffer-read-only)
684 (keep-lines-read-args "Flush lines containing match for regexp")))
685 (if rstart
686 (progn
687 (goto-char (min rstart rend))
688 (setq rend (copy-marker (max rstart rend))))
689 (if (and interactive transient-mark-mode mark-active)
690 (setq rstart (region-beginning)
691 rend (copy-marker (region-end)))
692 (setq rstart (point)
693 rend (point-max-marker)))
694 (goto-char rstart))
695 (let ((case-fold-search
696 (if (and case-fold-search search-upper-case)
697 (isearch-no-upper-case-p regexp t)
698 case-fold-search)))
699 (save-excursion
700 (while (and (< (point) rend)
701 (re-search-forward regexp rend t))
702 (delete-region (save-excursion (goto-char (match-beginning 0))
703 (forward-line 0)
704 (point))
705 (progn (forward-line 1) (point))))))
706 (set-marker rend nil)
707 nil)
710 (defun how-many (regexp &optional rstart rend interactive)
711 "Print and return number of matches for REGEXP following point.
712 When called from Lisp and INTERACTIVE is omitted or nil, just return
713 the number, do not print it; if INTERACTIVE is t, the function behaves
714 in all respects as if it had been called interactively.
716 If REGEXP contains upper case characters (excluding those preceded by `\\')
717 and `search-upper-case' is non-nil, the matching is case-sensitive.
719 Second and third arg RSTART and REND specify the region to operate on.
721 Interactively, in Transient Mark mode when the mark is active, operate
722 on the contents of the region. Otherwise, operate from point to the
723 end of (the accessible portion of) the buffer.
725 This function starts looking for the next match from the end of
726 the previous match. Hence, it ignores matches that overlap
727 a previously found match."
729 (interactive
730 (keep-lines-read-args "How many matches for regexp"))
731 (save-excursion
732 (if rstart
733 (progn
734 (goto-char (min rstart rend))
735 (setq rend (max rstart rend)))
736 (if (and interactive transient-mark-mode mark-active)
737 (setq rstart (region-beginning)
738 rend (region-end))
739 (setq rstart (point)
740 rend (point-max)))
741 (goto-char rstart))
742 (let ((count 0)
743 opoint
744 (case-fold-search
745 (if (and case-fold-search search-upper-case)
746 (isearch-no-upper-case-p regexp t)
747 case-fold-search)))
748 (while (and (< (point) rend)
749 (progn (setq opoint (point))
750 (re-search-forward regexp rend t)))
751 (if (= opoint (point))
752 (forward-char 1)
753 (setq count (1+ count))))
754 (when interactive (message "%d occurrence%s"
755 count
756 (if (= count 1) "" "s")))
757 count)))
760 (defvar occur-mode-map
761 (let ((map (make-sparse-keymap)))
762 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
763 (define-key map [mouse-2] 'occur-mode-mouse-goto)
764 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
765 (define-key map "\C-m" 'occur-mode-goto-occurrence)
766 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
767 (define-key map "\C-o" 'occur-mode-display-occurrence)
768 (define-key map "\M-n" 'occur-next)
769 (define-key map "\M-p" 'occur-prev)
770 (define-key map "r" 'occur-rename-buffer)
771 (define-key map "c" 'clone-buffer)
772 (define-key map "g" 'revert-buffer)
773 (define-key map "q" 'quit-window)
774 (define-key map "z" 'kill-this-buffer)
775 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
776 (define-key map [menu-bar] (make-sparse-keymap))
777 (define-key map [menu-bar occur]
778 `(cons ,(purecopy "Occur") map))
779 (define-key map [next-error-follow-minor-mode]
780 (menu-bar-make-mm-toggle next-error-follow-minor-mode
781 "Auto Occurrence Display"
782 "Display another occurrence when moving the cursor"))
783 (define-key map [separator-1] menu-bar-separator)
784 (define-key map [kill-this-buffer]
785 `(menu-item ,(purecopy "Kill occur buffer") kill-this-buffer
786 :help ,(purecopy "Kill the current *Occur* buffer")))
787 (define-key map [quit-window]
788 `(menu-item ,(purecopy "Quit occur window") quit-window
789 :help ,(purecopy "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame")))
790 (define-key map [revert-buffer]
791 `(menu-item ,(purecopy "Revert occur buffer") revert-buffer
792 :help ,(purecopy "Replace the text in the *Occur* buffer with the results of rerunning occur")))
793 (define-key map [clone-buffer]
794 `(menu-item ,(purecopy "Clone occur buffer") clone-buffer
795 :help ,(purecopy "Create and return a twin copy of the current *Occur* buffer")))
796 (define-key map [occur-rename-buffer]
797 `(menu-item ,(purecopy "Rename occur buffer") occur-rename-buffer
798 :help ,(purecopy "Rename the current *Occur* buffer to *Occur: original-buffer-name*.")))
799 (define-key map [separator-2] menu-bar-separator)
800 (define-key map [occur-mode-goto-occurrence-other-window]
801 `(menu-item ,(purecopy "Go To Occurrence Other Window") occur-mode-goto-occurrence-other-window
802 :help ,(purecopy "Go to the occurrence the current line describes, in another window")))
803 (define-key map [occur-mode-goto-occurrence]
804 `(menu-item ,(purecopy "Go To Occurrence") occur-mode-goto-occurrence
805 :help ,(purecopy "Go to the occurrence the current line describes")))
806 (define-key map [occur-mode-display-occurrence]
807 `(menu-item ,(purecopy "Display Occurrence") occur-mode-display-occurrence
808 :help ,(purecopy "Display in another window the occurrence the current line describes")))
809 (define-key map [occur-next]
810 `(menu-item ,(purecopy "Move to next match") occur-next
811 :help ,(purecopy "Move to the Nth (default 1) next match in an Occur mode buffer")))
812 (define-key map [occur-prev]
813 `(menu-item ,(purecopy "Move to previous match") occur-prev
814 :help ,(purecopy "Move to the Nth (default 1) previous match in an Occur mode buffer")))
815 map)
816 "Keymap for `occur-mode'.")
818 (defvar occur-revert-arguments nil
819 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
820 See `occur-revert-function'.")
822 (defcustom occur-mode-hook '(turn-on-font-lock)
823 "Hook run when entering Occur mode."
824 :type 'hook
825 :group 'matching)
827 (defcustom occur-hook nil
828 "Hook run by Occur when there are any matches."
829 :type 'hook
830 :group 'matching)
832 (defcustom occur-mode-find-occurrence-hook nil
833 "Hook run by Occur after locating an occurrence.
834 This will be called with the cursor position at the occurrence. An application
835 for this is to reveal context in an outline-mode when the occurrence is hidden."
836 :type 'hook
837 :group 'matching)
839 (put 'occur-mode 'mode-class 'special)
840 (defun occur-mode ()
841 "Major mode for output from \\[occur].
842 \\<occur-mode-map>Move point to one of the items in this buffer, then use
843 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
844 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
846 \\{occur-mode-map}"
847 (interactive)
848 (kill-all-local-variables)
849 (use-local-map occur-mode-map)
850 (setq major-mode 'occur-mode)
851 (setq mode-name "Occur")
852 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
853 (make-local-variable 'occur-revert-arguments)
854 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
855 (setq next-error-function 'occur-next-error)
856 (run-mode-hooks 'occur-mode-hook))
858 (defun occur-revert-function (ignore1 ignore2)
859 "Handle `revert-buffer' for Occur mode buffers."
860 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
862 (defun occur-mode-find-occurrence ()
863 (let ((pos (get-text-property (point) 'occur-target)))
864 (unless pos
865 (error "No occurrence on this line"))
866 (unless (buffer-live-p (marker-buffer pos))
867 (error "Buffer for this occurrence was killed"))
868 pos))
870 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
871 (defun occur-mode-goto-occurrence (&optional event)
872 "Go to the occurrence the current line describes."
873 (interactive (list last-nonmenu-event))
874 (let ((pos
875 (if (null event)
876 ;; Actually `event-end' works correctly with a nil argument as
877 ;; well, so we could dispense with this test, but let's not
878 ;; rely on this undocumented behavior.
879 (occur-mode-find-occurrence)
880 (with-current-buffer (window-buffer (posn-window (event-end event)))
881 (save-excursion
882 (goto-char (posn-point (event-end event)))
883 (occur-mode-find-occurrence)))))
884 same-window-buffer-names
885 same-window-regexps)
886 (pop-to-buffer (marker-buffer pos))
887 (goto-char pos)
888 (run-hooks 'occur-mode-find-occurrence-hook)))
890 (defun occur-mode-goto-occurrence-other-window ()
891 "Go to the occurrence the current line describes, in another window."
892 (interactive)
893 (let ((pos (occur-mode-find-occurrence)))
894 (switch-to-buffer-other-window (marker-buffer pos))
895 (goto-char pos)
896 (run-hooks 'occur-mode-find-occurrence-hook)))
898 (defun occur-mode-display-occurrence ()
899 "Display in another window the occurrence the current line describes."
900 (interactive)
901 (let ((pos (occur-mode-find-occurrence))
902 window
903 ;; Bind these to ensure `display-buffer' puts it in another window.
904 same-window-buffer-names
905 same-window-regexps)
906 (setq window (display-buffer (marker-buffer pos)))
907 ;; This is the way to set point in the proper window.
908 (save-selected-window
909 (select-window window)
910 (goto-char pos)
911 (run-hooks 'occur-mode-find-occurrence-hook))))
913 (defun occur-find-match (n search message)
914 (if (not n) (setq n 1))
915 (let ((r))
916 (while (> n 0)
917 (setq r (funcall search (point) 'occur-match))
918 (and r
919 (get-text-property r 'occur-match)
920 (setq r (funcall search r 'occur-match)))
921 (if r
922 (goto-char r)
923 (error message))
924 (setq n (1- n)))))
926 (defun occur-next (&optional n)
927 "Move to the Nth (default 1) next match in an Occur mode buffer."
928 (interactive "p")
929 (occur-find-match n #'next-single-property-change "No more matches"))
931 (defun occur-prev (&optional n)
932 "Move to the Nth (default 1) previous match in an Occur mode buffer."
933 (interactive "p")
934 (occur-find-match n #'previous-single-property-change "No earlier matches"))
936 (defun occur-next-error (&optional argp reset)
937 "Move to the Nth (default 1) next match in an Occur mode buffer.
938 Compatibility function for \\[next-error] invocations."
939 (interactive "p")
940 ;; we need to run occur-find-match from within the Occur buffer
941 (with-current-buffer
942 ;; Choose the buffer and make it current.
943 (if (next-error-buffer-p (current-buffer))
944 (current-buffer)
945 (next-error-find-buffer nil nil
946 (lambda ()
947 (eq major-mode 'occur-mode))))
949 (goto-char (cond (reset (point-min))
950 ((< argp 0) (line-beginning-position))
951 ((> argp 0) (line-end-position))
952 ((point))))
953 (occur-find-match
954 (abs argp)
955 (if (> 0 argp)
956 #'previous-single-property-change
957 #'next-single-property-change)
958 "No more matches")
959 ;; In case the *Occur* buffer is visible in a nonselected window.
960 (let ((win (get-buffer-window (current-buffer) t)))
961 (if win (set-window-point win (point))))
962 (occur-mode-goto-occurrence)))
964 (defface match
965 '((((class color) (min-colors 88) (background light))
966 :background "yellow1")
967 (((class color) (min-colors 88) (background dark))
968 :background "RoyalBlue3")
969 (((class color) (min-colors 8) (background light))
970 :background "yellow" :foreground "black")
971 (((class color) (min-colors 8) (background dark))
972 :background "blue" :foreground "white")
973 (((type tty) (class mono))
974 :inverse-video t)
975 (t :background "gray"))
976 "Face used to highlight matches permanently."
977 :group 'matching
978 :version "22.1")
980 (defcustom list-matching-lines-default-context-lines 0
981 "Default number of context lines included around `list-matching-lines' matches.
982 A negative number means to include that many lines before the match.
983 A positive number means to include that many lines both before and after."
984 :type 'integer
985 :group 'matching)
987 (defalias 'list-matching-lines 'occur)
989 (defcustom list-matching-lines-face 'match
990 "Face used by \\[list-matching-lines] to show the text that matches.
991 If the value is nil, don't highlight the matching portions specially."
992 :type 'face
993 :group 'matching)
995 (defcustom list-matching-lines-buffer-name-face 'underline
996 "Face used by \\[list-matching-lines] to show the names of buffers.
997 If the value is nil, don't highlight the buffer names specially."
998 :type 'face
999 :group 'matching)
1001 (defcustom occur-excluded-properties
1002 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1003 yank-handler follow-link)
1004 "Text properties to discard when copying lines to the *Occur* buffer.
1005 The value should be a list of text properties to discard or t,
1006 which means to discard all text properties."
1007 :type '(choice (const :tag "All" t) (repeat symbol))
1008 :group 'matching
1009 :version "22.1")
1011 (defun occur-read-primary-args ()
1012 (let* ((perform-collect (consp current-prefix-arg))
1013 (regexp (read-regexp (if perform-collect
1014 "Collect strings matching regexp"
1015 "List lines matching regexp")
1016 (car regexp-history))))
1017 (list regexp
1018 (if perform-collect
1019 ;; Perform collect operation
1020 (if (zerop (regexp-opt-depth regexp))
1021 ;; No subexpression so collect the entire match.
1022 "\\&"
1023 ;; Get the regexp for collection pattern.
1024 (let ((default (car occur-collect-regexp-history)))
1025 (read-string
1026 (format "Regexp to collect (default %s): " default)
1027 nil 'occur-collect-regexp-history default)))
1028 ;; Otherwise normal occur takes numerical prefix argument.
1029 (when current-prefix-arg
1030 (prefix-numeric-value current-prefix-arg))))))
1032 (defun occur-rename-buffer (&optional unique-p interactive-p)
1033 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1034 Here `original-buffer-name' is the buffer name where Occur was originally run.
1035 When given the prefix argument, or called non-interactively, the renaming
1036 will not clobber the existing buffer(s) of that name, but use
1037 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1038 if you always want a separate *Occur* buffer for each buffer where you
1039 invoke `occur'."
1040 (interactive "P\np")
1041 (with-current-buffer
1042 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1043 (rename-buffer (concat "*Occur: "
1044 (mapconcat #'buffer-name
1045 (car (cddr occur-revert-arguments)) "/")
1046 "*")
1047 (or unique-p (not interactive-p)))))
1049 (defun occur (regexp &optional nlines)
1050 "Show all lines in the current buffer containing a match for REGEXP.
1051 If a match spreads across multiple lines, all those lines are shown.
1053 Each line is displayed with NLINES lines before and after, or -NLINES
1054 before if NLINES is negative.
1055 NLINES defaults to `list-matching-lines-default-context-lines'.
1056 Interactively it is the prefix arg.
1058 The lines are shown in a buffer named `*Occur*'.
1059 It serves as a menu to find any of the occurrences in this buffer.
1060 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1062 If REGEXP contains upper case characters (excluding those preceded by `\\')
1063 and `search-upper-case' is non-nil, the matching is case-sensitive.
1065 When NLINES is a string or when the function is called
1066 interactively with prefix argument without a number (`C-u' alone
1067 as prefix) the matching strings are collected into the `*Occur*'
1068 buffer by using NLINES as a replacement regexp. NLINES may
1069 contain \\& and \\N which convention follows `replace-match'.
1070 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1071 \"\\1\" for NLINES collects all the function names in a lisp
1072 program. When there is no parenthesized subexpressions in REGEXP
1073 the entire match is collected. In any case the searched buffers
1074 are not modified."
1075 (interactive (occur-read-primary-args))
1076 (occur-1 regexp nlines (list (current-buffer))))
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-search
1214 title-face prefix-face match-face keep-props)
1215 (with-current-buffer out-buf
1216 (let ((globalcount 0)
1217 (coding nil))
1218 ;; Map over all the buffers
1219 (dolist (buf buffers)
1220 (when (buffer-live-p buf)
1221 (let ((matches 0) ;; count of matched lines
1222 (lines 1) ;; line count
1223 (prev-after-lines nil) ;; context lines of prev match
1224 (prev-lines nil) ;; line number of prev match endpt
1225 (matchbeg 0)
1226 (origpt nil)
1227 (begpt nil)
1228 (endpt nil)
1229 (marker nil)
1230 (curstring "")
1231 (ret nil)
1232 (inhibit-field-text-motion t)
1233 (headerpt (with-current-buffer out-buf (point))))
1234 (with-current-buffer buf
1235 (or coding
1236 ;; Set CODING only if the current buffer locally
1237 ;; binds buffer-file-coding-system.
1238 (not (local-variable-p 'buffer-file-coding-system))
1239 (setq coding buffer-file-coding-system))
1240 (save-excursion
1241 (goto-char (point-min)) ;; begin searching in the buffer
1242 (while (not (eobp))
1243 (setq origpt (point))
1244 (when (setq endpt (re-search-forward regexp nil t))
1245 (setq matches (1+ matches)) ;; increment match count
1246 (setq matchbeg (match-beginning 0))
1247 ;; Get beginning of first match line and end of the last.
1248 (save-excursion
1249 (goto-char matchbeg)
1250 (setq begpt (line-beginning-position))
1251 (goto-char endpt)
1252 (setq endpt (line-end-position)))
1253 ;; Sum line numbers up to the first match line.
1254 (setq lines (+ lines (count-lines origpt begpt)))
1255 (setq marker (make-marker))
1256 (set-marker marker matchbeg)
1257 (setq curstring (occur-engine-line begpt endpt keep-props))
1258 ;; Highlight the matches
1259 (let ((len (length curstring))
1260 (start 0))
1261 (while (and (< start len)
1262 (string-match regexp curstring start))
1263 (add-text-properties
1264 (match-beginning 0) (match-end 0)
1265 (append
1266 `(occur-match t)
1267 (when match-face
1268 ;; Use `face' rather than `font-lock-face' here
1269 ;; so as to override faces copied from the buffer.
1270 `(face ,match-face)))
1271 curstring)
1272 (setq start (match-end 0))))
1273 ;; Generate the string to insert for this match
1274 (let* ((match-prefix
1275 ;; Using 7 digits aligns tabs properly.
1276 (apply #'propertize (format "%7d:" lines)
1277 (append
1278 (when prefix-face
1279 `(font-lock-face prefix-face))
1280 `(occur-prefix t mouse-face (highlight)
1281 occur-target ,marker follow-link t
1282 help-echo "mouse-2: go to this occurrence"))))
1283 (match-str
1284 ;; We don't put `mouse-face' on the newline,
1285 ;; because that loses. And don't put it
1286 ;; on context lines to reduce flicker.
1287 (propertize curstring 'mouse-face (list 'highlight)
1288 'occur-target marker
1289 'follow-link t
1290 'help-echo
1291 "mouse-2: go to this occurrence"))
1292 (out-line
1293 (concat
1294 match-prefix
1295 ;; Add non-numeric prefix to all non-first lines
1296 ;; of multi-line matches.
1297 (replace-regexp-in-string
1298 "\n"
1299 "\n :"
1300 match-str)
1301 ;; Add marker at eol, but no mouse props.
1302 (propertize "\n" 'occur-target marker)))
1303 (data
1304 (if (= nlines 0)
1305 ;; The simple display style
1306 out-line
1307 ;; The complex multi-line display style.
1308 (setq ret (occur-context-lines
1309 out-line nlines keep-props begpt endpt
1310 lines prev-lines prev-after-lines))
1311 ;; Set first elem of the returned list to `data',
1312 ;; and the second elem to `prev-after-lines'.
1313 (setq prev-after-lines (nth 1 ret))
1314 (nth 0 ret))))
1315 ;; Actually insert the match display data
1316 (with-current-buffer out-buf
1317 (let ((beg (point))
1318 (end (progn (insert data) (point)))))))
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 preceeded 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 replace-count)
1567 (let ((replacement (eval expression)))
1568 (if (stringp replacement)
1569 replacement
1570 (prin1-to-string replacement t))))
1572 (defun replace-quote (replacement)
1573 "Quote a replacement string.
1574 This just doubles all backslashes in REPLACEMENT and
1575 returns the resulting string. If REPLACEMENT is not
1576 a string, it is first passed through `prin1-to-string'
1577 with the `noescape' argument set.
1579 `match-data' is preserved across the call."
1580 (save-match-data
1581 (replace-regexp-in-string "\\\\" "\\\\"
1582 (if (stringp replacement)
1583 replacement
1584 (prin1-to-string replacement t))
1585 t t)))
1587 (defun replace-loop-through-replacements (data replace-count)
1588 ;; DATA is a vector contaning the following values:
1589 ;; 0 next-rotate-count
1590 ;; 1 repeat-count
1591 ;; 2 next-replacement
1592 ;; 3 replacements
1593 (if (= (aref data 0) replace-count)
1594 (progn
1595 (aset data 0 (+ replace-count (aref data 1)))
1596 (let ((next (cdr (aref data 2))))
1597 (aset data 2 (if (consp next) next (aref data 3))))))
1598 (car (aref data 2)))
1600 (defun replace-match-data (integers reuse &optional new)
1601 "Like `match-data', but markers in REUSE get invalidated.
1602 If NEW is non-nil, it is set and returned instead of fresh data,
1603 but coerced to the correct value of INTEGERS."
1604 (or (and new
1605 (progn
1606 (set-match-data new)
1607 (and (eq new reuse)
1608 (eq (null integers) (markerp (car reuse)))
1609 new)))
1610 (match-data integers reuse t)))
1612 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1613 "Make a replacement with `replace-match', editing `\\?'.
1614 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1615 check for `\\?' is made to save time. MATCH-DATA is used for the
1616 replacement. In case editing is done, it is changed to use markers.
1618 The return value is non-nil if there has been no `\\?' or NOEDIT was
1619 passed in. If LITERAL is set, no checking is done, anyway."
1620 (unless (or literal noedit)
1621 (setq noedit t)
1622 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1623 newtext)
1624 (setq newtext
1625 (read-string "Edit replacement string: "
1626 (prog1
1627 (cons
1628 (replace-match "" t t newtext 3)
1629 (1+ (match-beginning 3)))
1630 (setq match-data
1631 (replace-match-data
1632 nil match-data match-data))))
1633 noedit nil)))
1634 (set-match-data match-data)
1635 (replace-match newtext fixedcase literal)
1636 noedit)
1638 (defvar replace-search-function 'search-forward
1639 "Function to use when searching for strings to replace.
1640 It is used by `query-replace' and `replace-string', and is called
1641 with three arguments, as if it were `search-forward'.")
1643 (defvar replace-re-search-function 're-search-forward
1644 "Function to use when searching for regexps to replace.
1645 It is used by `query-replace-regexp', `replace-regexp',
1646 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1647 It is called with three arguments, as if it were
1648 `re-search-forward'.")
1650 (defun perform-replace (from-string replacements
1651 query-flag regexp-flag delimited-flag
1652 &optional repeat-count map start end)
1653 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1654 Don't use this in your own program unless you want to query and set the mark
1655 just as `query-replace' does. Instead, write a simple loop like this:
1657 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1658 (replace-match \"foobar\" nil nil))
1660 which will run faster and probably do exactly what you want. Please
1661 see the documentation of `replace-match' to find out how to simulate
1662 `case-replace'.
1664 This function returns nil if and only if there were no matches to
1665 make, or the user didn't cancel the call."
1666 (or map (setq map query-replace-map))
1667 (and query-flag minibuffer-auto-raise
1668 (raise-frame (window-frame (minibuffer-window))))
1669 (let* ((case-fold-search
1670 (if (and case-fold-search search-upper-case)
1671 (isearch-no-upper-case-p from-string regexp-flag)
1672 case-fold-search))
1673 (nocasify (not (and case-replace case-fold-search)))
1674 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1675 (search-function
1676 (if regexp-flag
1677 replace-re-search-function
1678 replace-search-function))
1679 (search-string from-string)
1680 (real-match-data nil) ; The match data for the current match.
1681 (next-replacement nil)
1682 ;; This is non-nil if we know there is nothing for the user
1683 ;; to edit in the replacement.
1684 (noedit nil)
1685 (keep-going t)
1686 (stack nil)
1687 (replace-count 0)
1688 (nonempty-match nil)
1689 (multi-buffer nil)
1690 (recenter-last-op nil) ; Start cycling order with initial position.
1692 ;; If non-nil, it is marker saying where in the buffer to stop.
1693 (limit nil)
1695 ;; Data for the next match. If a cons, it has the same format as
1696 ;; (match-data); otherwise it is t if a match is possible at point.
1697 (match-again t)
1699 (message
1700 (if query-flag
1701 (apply 'propertize
1702 (substitute-command-keys
1703 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1704 minibuffer-prompt-properties))))
1706 ;; If region is active, in Transient Mark mode, operate on region.
1707 (when start
1708 (setq limit (copy-marker (max start end)))
1709 (goto-char (min start end))
1710 (deactivate-mark))
1712 ;; If last typed key in previous call of multi-buffer perform-replace
1713 ;; was `automatic-all', don't ask more questions in next files
1714 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
1715 (setq query-flag nil multi-buffer t))
1717 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1718 ;; containing a function and its first argument. The function is
1719 ;; called to generate each replacement like this:
1720 ;; (funcall (car replacements) (cdr replacements) replace-count)
1721 ;; It must return a string.
1722 (cond
1723 ((stringp replacements)
1724 (setq next-replacement replacements
1725 replacements nil))
1726 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1727 (or repeat-count (setq repeat-count 1))
1728 (setq replacements (cons 'replace-loop-through-replacements
1729 (vector repeat-count repeat-count
1730 replacements replacements)))))
1732 (if delimited-flag
1733 (setq search-function 're-search-forward
1734 search-string (concat "\\b"
1735 (if regexp-flag from-string
1736 (regexp-quote from-string))
1737 "\\b")))
1738 (when query-replace-lazy-highlight
1739 (setq isearch-lazy-highlight-last-string nil))
1741 (push-mark)
1742 (undo-boundary)
1743 (unwind-protect
1744 ;; Loop finding occurrences that perhaps should be replaced.
1745 (while (and keep-going
1746 (not (or (eobp) (and limit (>= (point) limit))))
1747 ;; Use the next match if it is already known;
1748 ;; otherwise, search for a match after moving forward
1749 ;; one char if progress is required.
1750 (setq real-match-data
1751 (cond ((consp match-again)
1752 (goto-char (nth 1 match-again))
1753 (replace-match-data
1754 t real-match-data match-again))
1755 ;; MATCH-AGAIN non-nil means accept an
1756 ;; adjacent match.
1757 (match-again
1758 (and
1759 (funcall search-function search-string
1760 limit t)
1761 ;; For speed, use only integers and
1762 ;; reuse the list used last time.
1763 (replace-match-data t real-match-data)))
1764 ((and (< (1+ (point)) (point-max))
1765 (or (null limit)
1766 (< (1+ (point)) limit)))
1767 ;; If not accepting adjacent matches,
1768 ;; move one char to the right before
1769 ;; searching again. Undo the motion
1770 ;; if the search fails.
1771 (let ((opoint (point)))
1772 (forward-char 1)
1773 (if (funcall
1774 search-function search-string
1775 limit t)
1776 (replace-match-data
1777 t real-match-data)
1778 (goto-char opoint)
1779 nil))))))
1781 ;; Record whether the match is nonempty, to avoid an infinite loop
1782 ;; repeatedly matching the same empty string.
1783 (setq nonempty-match
1784 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1786 ;; If the match is empty, record that the next one can't be
1787 ;; adjacent.
1789 ;; Otherwise, if matching a regular expression, do the next
1790 ;; match now, since the replacement for this match may
1791 ;; affect whether the next match is adjacent to this one.
1792 ;; If that match is empty, don't use it.
1793 (setq match-again
1794 (and nonempty-match
1795 (or (not regexp-flag)
1796 (and (looking-at search-string)
1797 (let ((match (match-data)))
1798 (and (/= (nth 0 match) (nth 1 match))
1799 match))))))
1801 ;; Optionally ignore matches that have a read-only property.
1802 (unless (and query-replace-skip-read-only
1803 (text-property-not-all
1804 (nth 0 real-match-data) (nth 1 real-match-data)
1805 'read-only nil))
1807 ;; Calculate the replacement string, if necessary.
1808 (when replacements
1809 (set-match-data real-match-data)
1810 (setq next-replacement
1811 (funcall (car replacements) (cdr replacements)
1812 replace-count)))
1813 (if (not query-flag)
1814 (progn
1815 (unless (or literal noedit)
1816 (replace-highlight
1817 (nth 0 real-match-data) (nth 1 real-match-data)
1818 start end search-string
1819 (or delimited-flag regexp-flag) case-fold-search))
1820 (setq noedit
1821 (replace-match-maybe-edit
1822 next-replacement nocasify literal
1823 noedit real-match-data)
1824 replace-count (1+ replace-count)))
1825 (undo-boundary)
1826 (let (done replaced key def)
1827 ;; Loop reading commands until one of them sets done,
1828 ;; which means it has finished handling this
1829 ;; occurrence. Any command that sets `done' should
1830 ;; leave behind proper match data for the stack.
1831 ;; Commands not setting `done' need to adjust
1832 ;; `real-match-data'.
1833 (while (not done)
1834 (set-match-data real-match-data)
1835 (replace-highlight
1836 (match-beginning 0) (match-end 0)
1837 start end search-string
1838 (or delimited-flag regexp-flag) case-fold-search)
1839 ;; Bind message-log-max so we don't fill up the message log
1840 ;; with a bunch of identical messages.
1841 (let ((message-log-max nil)
1842 (replacement-presentation
1843 (if query-replace-show-replacement
1844 (save-match-data
1845 (set-match-data real-match-data)
1846 (match-substitute-replacement next-replacement
1847 nocasify literal))
1848 next-replacement)))
1849 (message message
1850 (query-replace-descr from-string)
1851 (query-replace-descr replacement-presentation)))
1852 (setq key (read-event))
1853 ;; Necessary in case something happens during read-event
1854 ;; that clobbers the match data.
1855 (set-match-data real-match-data)
1856 (setq key (vector key))
1857 (setq def (lookup-key map key))
1858 ;; Restore the match data while we process the command.
1859 (cond ((eq def 'help)
1860 (with-output-to-temp-buffer "*Help*"
1861 (princ
1862 (concat "Query replacing "
1863 (if delimited-flag "word " "")
1864 (if regexp-flag "regexp " "")
1865 from-string " with "
1866 next-replacement ".\n\n"
1867 (substitute-command-keys
1868 query-replace-help)))
1869 (with-current-buffer standard-output
1870 (help-mode))))
1871 ((eq def 'exit)
1872 (setq keep-going nil)
1873 (setq done t))
1874 ((eq def 'exit-current)
1875 (setq multi-buffer t keep-going nil done t))
1876 ((eq def 'backup)
1877 (if stack
1878 (let ((elt (pop stack)))
1879 (goto-char (nth 0 elt))
1880 (setq replaced (nth 1 elt)
1881 real-match-data
1882 (replace-match-data
1883 t real-match-data
1884 (nth 2 elt))))
1885 (message "No previous match")
1886 (ding 'no-terminate)
1887 (sit-for 1)))
1888 ((eq def 'act)
1889 (or replaced
1890 (setq noedit
1891 (replace-match-maybe-edit
1892 next-replacement nocasify literal
1893 noedit real-match-data)
1894 replace-count (1+ replace-count)))
1895 (setq done t replaced t))
1896 ((eq def 'act-and-exit)
1897 (or replaced
1898 (setq noedit
1899 (replace-match-maybe-edit
1900 next-replacement nocasify literal
1901 noedit real-match-data)
1902 replace-count (1+ replace-count)))
1903 (setq keep-going nil)
1904 (setq done t replaced t))
1905 ((eq def 'act-and-show)
1906 (if (not replaced)
1907 (setq noedit
1908 (replace-match-maybe-edit
1909 next-replacement nocasify literal
1910 noedit real-match-data)
1911 replace-count (1+ replace-count)
1912 real-match-data (replace-match-data
1913 t real-match-data)
1914 replaced t)))
1915 ((or (eq def 'automatic) (eq def 'automatic-all))
1916 (or replaced
1917 (setq noedit
1918 (replace-match-maybe-edit
1919 next-replacement nocasify literal
1920 noedit real-match-data)
1921 replace-count (1+ replace-count)))
1922 (setq done t query-flag nil replaced t)
1923 (if (eq def 'automatic-all) (setq multi-buffer t)))
1924 ((eq def 'skip)
1925 (setq done t))
1926 ((eq def 'recenter)
1927 ;; `this-command' has the value `query-replace',
1928 ;; so we need to bind it to `recenter-top-bottom'
1929 ;; to allow it to detect a sequence of `C-l'.
1930 (let ((this-command 'recenter-top-bottom)
1931 (last-command 'recenter-top-bottom))
1932 (recenter-top-bottom)))
1933 ((eq def 'edit)
1934 (let ((opos (point-marker)))
1935 (setq real-match-data (replace-match-data
1936 nil real-match-data
1937 real-match-data))
1938 (goto-char (match-beginning 0))
1939 (save-excursion
1940 (save-window-excursion
1941 (recursive-edit)))
1942 (goto-char opos)
1943 (set-marker opos nil))
1944 ;; Before we make the replacement,
1945 ;; decide whether the search string
1946 ;; can match again just after this match.
1947 (if (and regexp-flag nonempty-match)
1948 (setq match-again (and (looking-at search-string)
1949 (match-data)))))
1950 ;; Edit replacement.
1951 ((eq def 'edit-replacement)
1952 (setq real-match-data (replace-match-data
1953 nil real-match-data
1954 real-match-data)
1955 next-replacement
1956 (read-string "Edit replacement string: "
1957 next-replacement)
1958 noedit nil)
1959 (if replaced
1960 (set-match-data real-match-data)
1961 (setq noedit
1962 (replace-match-maybe-edit
1963 next-replacement nocasify literal noedit
1964 real-match-data)
1965 replaced t))
1966 (setq done t))
1968 ((eq def 'delete-and-edit)
1969 (replace-match "" t t)
1970 (setq real-match-data (replace-match-data
1971 nil real-match-data))
1972 (replace-dehighlight)
1973 (save-excursion (recursive-edit))
1974 (setq replaced t))
1975 ;; Note: we do not need to treat `exit-prefix'
1976 ;; specially here, since we reread
1977 ;; any unrecognized character.
1979 (setq this-command 'mode-exited)
1980 (setq keep-going nil)
1981 (setq unread-command-events
1982 (append (listify-key-sequence key)
1983 unread-command-events))
1984 (setq done t)))
1985 (when query-replace-lazy-highlight
1986 ;; Force lazy rehighlighting only after replacements.
1987 (if (not (memq def '(skip backup)))
1988 (setq isearch-lazy-highlight-last-string nil)))
1989 (unless (eq def 'recenter)
1990 ;; Reset recenter cycling order to initial position.
1991 (setq recenter-last-op nil)))
1992 ;; Record previous position for ^ when we move on.
1993 ;; Change markers to numbers in the match data
1994 ;; since lots of markers slow down editing.
1995 (push (list (point) replaced
1996 ;;; If the replacement has already happened, all we need is the
1997 ;;; current match start and end. We could get this with a trivial
1998 ;;; match like
1999 ;;; (save-excursion (goto-char (match-beginning 0))
2000 ;;; (search-forward (match-string 0))
2001 ;;; (match-data t))
2002 ;;; if we really wanted to avoid manually constructing match data.
2003 ;;; Adding current-buffer is necessary so that match-data calls can
2004 ;;; return markers which are appropriate for editing.
2005 (if replaced
2006 (list
2007 (match-beginning 0)
2008 (match-end 0)
2009 (current-buffer))
2010 (match-data t)))
2011 stack)))))
2013 (replace-dehighlight))
2014 (or unread-command-events
2015 (message "Replaced %d occurrence%s"
2016 replace-count
2017 (if (= replace-count 1) "" "s")))
2018 (or (and keep-going stack) multi-buffer)))
2020 (defvar replace-overlay nil)
2022 (defun replace-highlight (match-beg match-end range-beg range-end
2023 string regexp case-fold)
2024 (if query-replace-highlight
2025 (if replace-overlay
2026 (move-overlay replace-overlay match-beg match-end (current-buffer))
2027 (setq replace-overlay (make-overlay match-beg match-end))
2028 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2029 (overlay-put replace-overlay 'face 'query-replace)))
2030 (if query-replace-lazy-highlight
2031 (let ((isearch-string string)
2032 (isearch-regexp regexp)
2033 (search-whitespace-regexp nil)
2034 (isearch-case-fold-search case-fold)
2035 (isearch-forward t)
2036 (isearch-error nil))
2037 ;; Set isearch-word to nil because word-replace is regexp-based,
2038 ;; so `isearch-search-fun' should not use `word-search-forward'.
2039 (if (and isearch-word isearch-regexp) (setq isearch-word nil))
2040 (isearch-lazy-highlight-new-loop range-beg range-end))))
2042 (defun replace-dehighlight ()
2043 (when replace-overlay
2044 (delete-overlay replace-overlay))
2045 (when query-replace-lazy-highlight
2046 (lazy-highlight-cleanup lazy-highlight-cleanup)
2047 (setq isearch-lazy-highlight-last-string nil)))
2049 ;;; replace.el ends here