Regenerate.
[emacs.git] / lisp / replace.el
blob28f3a845c2a4bb23fb8e7da1f7f4b64fa8dc569c
1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1992, 1994, 1996, 1997, 2000, 2001,
4 ;; 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
5 ;; Free Software Foundation, Inc.
7 ;; Maintainer: FSF
8 ;; Package: emacs
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; This package supplies the string and regular-expression replace functions
28 ;; documented in the Emacs user's manual.
30 ;;; Code:
32 (defcustom case-replace t
33 "Non-nil means `query-replace' should preserve case in replacements."
34 :type 'boolean
35 :group 'matching)
37 (defvar query-replace-history nil
38 "Default history list for query-replace commands.
39 See `query-replace-from-history-variable' and
40 `query-replace-to-history-variable'.")
42 (defvar query-replace-defaults nil
43 "Default values of FROM-STRING and TO-STRING for `query-replace'.
44 This is a cons cell (FROM-STRING . TO-STRING), or nil if there is
45 no default value.")
47 (defvar query-replace-interactive nil
48 "Non-nil means `query-replace' uses the last search string.
49 That becomes the \"string to replace\".")
51 (defcustom query-replace-from-history-variable 'query-replace-history
52 "History list to use for the FROM argument of `query-replace' commands.
53 The value of this variable should be a symbol; that symbol
54 is used as a variable to hold a history list for the strings
55 or patterns to be replaced."
56 :group 'matching
57 :type 'symbol
58 :version "20.3")
60 (defcustom query-replace-to-history-variable 'query-replace-history
61 "History list to use for the TO argument of `query-replace' commands.
62 The value of this variable should be a symbol; that symbol
63 is used as a variable to hold a history list for replacement
64 strings or patterns."
65 :group 'matching
66 :type 'symbol
67 :version "20.3")
69 (defcustom query-replace-skip-read-only nil
70 "Non-nil means `query-replace' and friends ignore read-only matches."
71 :type 'boolean
72 :group 'matching
73 :version "22.1")
75 (defcustom query-replace-show-replacement t
76 "Non-nil means to show what actual replacement text will be."
77 :type 'boolean
78 :group 'matching
79 :version "23.1")
81 (defcustom query-replace-highlight t
82 "Non-nil means to highlight matches during query replacement."
83 :type 'boolean
84 :group 'matching)
86 (defcustom query-replace-lazy-highlight t
87 "Controls the lazy-highlighting during query replacements.
88 When non-nil, all text in the buffer matching the current match
89 is highlighted lazily using isearch lazy highlighting (see
90 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
91 :type 'boolean
92 :group 'lazy-highlight
93 :group 'matching
94 :version "22.1")
96 (defface query-replace
97 '((t (:inherit isearch)))
98 "Face for highlighting query replacement matches."
99 :group 'matching
100 :version "22.1")
102 (defun query-replace-descr (string)
103 (mapconcat 'isearch-text-char-description string ""))
105 (defun query-replace-read-from (prompt regexp-flag)
106 "Query and return the `from' argument of a query-replace operation.
107 The return value can also be a pair (FROM . TO) indicating that the user
108 wants to replace FROM with TO."
109 (if query-replace-interactive
110 (car (if regexp-flag regexp-search-ring search-ring))
111 (let* ((history-add-new-input nil)
112 (from
113 ;; The save-excursion here is in case the user marks and copies
114 ;; a region in order to specify the minibuffer input.
115 ;; That should not clobber the region for the query-replace itself.
116 (save-excursion
117 (read-from-minibuffer
118 (if query-replace-defaults
119 (format "%s (default %s -> %s): " prompt
120 (query-replace-descr (car query-replace-defaults))
121 (query-replace-descr (cdr query-replace-defaults)))
122 (format "%s: " prompt))
123 nil nil nil
124 query-replace-from-history-variable
125 nil t))))
126 (if (and (zerop (length from)) query-replace-defaults)
127 (cons (car query-replace-defaults)
128 (query-replace-compile-replacement
129 (cdr query-replace-defaults) regexp-flag))
130 (add-to-history query-replace-from-history-variable from nil t)
131 ;; Warn if user types \n or \t, but don't reject the input.
132 (and regexp-flag
133 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
134 (let ((match (match-string 3 from)))
135 (cond
136 ((string= match "\\n")
137 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
138 ((string= match "\\t")
139 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
140 (sit-for 2)))
141 from))))
143 (defun query-replace-compile-replacement (to regexp-flag)
144 "Maybe convert a regexp replacement TO to Lisp.
145 Returns a list suitable for `perform-replace' if necessary,
146 the original string if not."
147 (if (and regexp-flag
148 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
149 (let (pos list char)
150 (while
151 (progn
152 (setq pos (match-end 0))
153 (push (substring to 0 (- pos 2)) list)
154 (setq char (aref to (1- pos))
155 to (substring to pos))
156 (cond ((eq char ?\#)
157 (push '(number-to-string replace-count) list))
158 ((eq char ?\,)
159 (setq pos (read-from-string to))
160 (push `(replace-quote ,(car pos)) list)
161 (let ((end
162 ;; Swallow a space after a symbol
163 ;; if there is a space.
164 (if (and (or (symbolp (car pos))
165 ;; Swallow a space after 'foo
166 ;; but not after (quote foo).
167 (and (eq (car-safe (car pos)) 'quote)
168 (not (= ?\( (aref to 0)))))
169 (eq (string-match " " to (cdr pos))
170 (cdr pos)))
171 (1+ (cdr pos))
172 (cdr pos))))
173 (setq to (substring to end)))))
174 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
175 (setq to (nreverse (delete "" (cons to list))))
176 (replace-match-string-symbols to)
177 (cons 'replace-eval-replacement
178 (if (cdr to)
179 (cons 'concat to)
180 (car to))))
181 to))
184 (defun query-replace-read-to (from prompt regexp-flag)
185 "Query and return the `to' argument of a query-replace operation."
186 (query-replace-compile-replacement
187 (save-excursion
188 (let* ((history-add-new-input nil)
189 (to (read-from-minibuffer
190 (format "%s %s with: " prompt (query-replace-descr from))
191 nil nil nil
192 query-replace-to-history-variable from t)))
193 (add-to-history query-replace-to-history-variable to nil t)
194 (setq query-replace-defaults (cons from to))
195 to))
196 regexp-flag))
198 (defun query-replace-read-args (prompt regexp-flag &optional noerror)
199 (unless noerror
200 (barf-if-buffer-read-only))
201 (let* ((from (query-replace-read-from prompt regexp-flag))
202 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
203 (query-replace-read-to from prompt regexp-flag))))
204 (list from to current-prefix-arg)))
206 (defun query-replace (from-string to-string &optional delimited start end)
207 "Replace some occurrences of FROM-STRING with TO-STRING.
208 As each match is found, the user must type a character saying
209 what to do with it. For directions, type \\[help-command] at that time.
211 In Transient Mark mode, if the mark is active, operate on the contents
212 of the region. Otherwise, operate from point to the end of the buffer.
214 If `query-replace-interactive' is non-nil, the last incremental search
215 string is used as FROM-STRING--you don't have to specify it with the
216 minibuffer.
218 Matching is independent of case if `case-fold-search' is non-nil and
219 FROM-STRING has no uppercase letters. Replacement transfers the case
220 pattern of the old text to the new text, if `case-replace' and
221 `case-fold-search' are non-nil and FROM-STRING has no uppercase
222 letters. \(Transferring the case pattern means that if the old text
223 matched is all caps, or capitalized, then its replacement is upcased
224 or capitalized.)
226 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
227 only matches surrounded by word boundaries.
228 Fourth and fifth arg START and END specify the region to operate on.
230 To customize possible responses, change the \"bindings\" in `query-replace-map'."
231 (interactive
232 (let ((common
233 (query-replace-read-args
234 (concat "Query replace"
235 (if current-prefix-arg " word" "")
236 (if (and transient-mark-mode mark-active) " in region" ""))
237 nil)))
238 (list (nth 0 common) (nth 1 common) (nth 2 common)
239 ;; These are done separately here
240 ;; so that command-history will record these expressions
241 ;; rather than the values they had this time.
242 (if (and transient-mark-mode mark-active)
243 (region-beginning))
244 (if (and transient-mark-mode mark-active)
245 (region-end)))))
246 (perform-replace from-string to-string t nil delimited nil nil start end))
248 (define-key esc-map "%" 'query-replace)
250 (defun query-replace-regexp (regexp to-string &optional delimited start end)
251 "Replace some things after point matching REGEXP with TO-STRING.
252 As each match is found, the user must type a character saying
253 what to do with it. For directions, type \\[help-command] at that time.
255 In Transient Mark mode, if the mark is active, operate on the contents
256 of the region. Otherwise, operate from point to the end of the buffer.
258 If `query-replace-interactive' is non-nil, the last incremental search
259 regexp is used as REGEXP--you don't have to specify it with the
260 minibuffer.
262 Matching is independent of case if `case-fold-search' is non-nil and
263 REGEXP has no uppercase letters. Replacement transfers the case
264 pattern of the old text to the new text, if `case-replace' and
265 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
266 \(Transferring the case pattern means that if the old text matched is
267 all caps, or capitalized, then its replacement is upcased or
268 capitalized.)
270 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
271 only matches surrounded by word boundaries.
272 Fourth and fifth arg START and END specify the region to operate on.
274 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
275 and `\\=\\N' (where N is a digit) stands for
276 whatever what matched the Nth `\\(...\\)' in REGEXP.
277 `\\?' lets you edit the replacement text in the minibuffer
278 at the given position for each replacement.
280 In interactive calls, the replacement text can contain `\\,'
281 followed by a Lisp expression. Each
282 replacement evaluates that expression to compute the replacement
283 string. Inside of that expression, `\\&' is a string denoting the
284 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
285 for the whole or a partial match converted to a number with
286 `string-to-number', and `\\#' itself for the number of replacements
287 done so far (starting with zero).
289 If the replacement expression is a symbol, write a space after it
290 to terminate it. One space there, if any, will be discarded.
292 When using those Lisp features interactively in the replacement
293 text, TO-STRING is actually made a list instead of a string.
294 Use \\[repeat-complex-command] after this command for details."
295 (interactive
296 (let ((common
297 (query-replace-read-args
298 (concat "Query replace"
299 (if current-prefix-arg " word" "")
300 " regexp"
301 (if (and transient-mark-mode mark-active) " in region" ""))
302 t)))
303 (list (nth 0 common) (nth 1 common) (nth 2 common)
304 ;; These are done separately here
305 ;; so that command-history will record these expressions
306 ;; rather than the values they had this time.
307 (if (and transient-mark-mode mark-active)
308 (region-beginning))
309 (if (and transient-mark-mode mark-active)
310 (region-end)))))
311 (perform-replace regexp to-string t t delimited nil nil start end))
313 (define-key esc-map [?\C-%] 'query-replace-regexp)
315 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
316 "Replace some things after point matching REGEXP with the result of TO-EXPR.
318 Interactive use of this function is deprecated in favor of the
319 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
320 using `search-forward-regexp' and `replace-match' is preferred.
322 As each match is found, the user must type a character saying
323 what to do with it. For directions, type \\[help-command] at that time.
325 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
326 reference `replace-count' to get the number of replacements already made.
327 If the result of TO-EXPR is not a string, it is converted to one using
328 `prin1-to-string' with the NOESCAPE argument (which see).
330 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
331 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
332 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
333 Use `\\#&' or `\\#N' if you want a number instead of a string.
334 In interactive use, `\\#' in itself stands for `replace-count'.
336 In Transient Mark mode, if the mark is active, operate on the contents
337 of the region. Otherwise, operate from point to the end of the buffer.
339 If `query-replace-interactive' is non-nil, the last incremental search
340 regexp is used as REGEXP--you don't have to specify it with the
341 minibuffer.
343 Preserves case in each replacement if `case-replace' and `case-fold-search'
344 are non-nil and REGEXP has no uppercase letters.
346 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
347 only matches that are surrounded by word boundaries.
348 Fourth and fifth arg START and END specify the region to operate on."
349 (interactive
350 (progn
351 (barf-if-buffer-read-only)
352 (let* ((from
353 ;; Let-bind the history var to disable the "foo -> bar" default.
354 ;; Maybe we shouldn't disable this default, but for now I'll
355 ;; leave it off. --Stef
356 (let ((query-replace-to-history-variable nil))
357 (query-replace-read-from "Query replace regexp" t)))
358 (to (list (read-from-minibuffer
359 (format "Query replace regexp %s with eval: "
360 (query-replace-descr from))
361 nil nil t query-replace-to-history-variable from t))))
362 ;; We make TO a list because replace-match-string-symbols requires one,
363 ;; and the user might enter a single token.
364 (replace-match-string-symbols to)
365 (list from (car to) current-prefix-arg
366 (if (and transient-mark-mode mark-active)
367 (region-beginning))
368 (if (and transient-mark-mode mark-active)
369 (region-end))))))
370 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
371 t 'literal delimited nil nil start end))
373 (make-obsolete 'query-replace-regexp-eval
374 "for interactive use, use the special `\\,' feature of
375 `query-replace-regexp' instead. Non-interactively, a loop
376 using `search-forward-regexp' and `replace-match' is preferred." "22.1")
378 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
379 "Replace some matches for REGEXP with various strings, in rotation.
380 The second argument TO-STRINGS contains the replacement strings, separated
381 by spaces. This command works like `query-replace-regexp' except that
382 each successive replacement uses the next successive replacement string,
383 wrapping around from the last such string to the first.
385 In Transient Mark mode, if the mark is active, operate on the contents
386 of the region. Otherwise, operate from point to the end of the buffer.
388 Non-interactively, TO-STRINGS may be a list of replacement strings.
390 If `query-replace-interactive' is non-nil, the last incremental search
391 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
393 A prefix argument N says to use each replacement string N times
394 before rotating to the next.
395 Fourth and fifth arg START and END specify the region to operate on."
396 (interactive
397 (let* ((from (if query-replace-interactive
398 (car regexp-search-ring)
399 (read-from-minibuffer "Map query replace (regexp): "
400 nil nil nil
401 query-replace-from-history-variable
402 nil t)))
403 (to (read-from-minibuffer
404 (format "Query replace %s with (space-separated strings): "
405 (query-replace-descr from))
406 nil nil nil
407 query-replace-to-history-variable from t)))
408 (list from to
409 (and current-prefix-arg
410 (prefix-numeric-value current-prefix-arg))
411 (if (and transient-mark-mode mark-active)
412 (region-beginning))
413 (if (and transient-mark-mode mark-active)
414 (region-end)))))
415 (let (replacements)
416 (if (listp to-strings)
417 (setq replacements to-strings)
418 (while (/= (length to-strings) 0)
419 (if (string-match " " to-strings)
420 (setq replacements
421 (append replacements
422 (list (substring to-strings 0
423 (string-match " " to-strings))))
424 to-strings (substring to-strings
425 (1+ (string-match " " to-strings))))
426 (setq replacements (append replacements (list to-strings))
427 to-strings ""))))
428 (perform-replace regexp replacements t t nil n nil start end)))
430 (defun replace-string (from-string to-string &optional delimited start end)
431 "Replace occurrences of FROM-STRING with TO-STRING.
432 Preserve case in each match if `case-replace' and `case-fold-search'
433 are non-nil and FROM-STRING has no uppercase letters.
434 \(Preserving case means that if the string matched is all caps, or capitalized,
435 then its replacement is upcased or capitalized.)
437 In Transient Mark mode, if the mark is active, operate on the contents
438 of the region. Otherwise, operate from point to the end of the buffer.
440 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
441 only matches surrounded by word boundaries.
442 Fourth and fifth arg START and END specify the region to operate on.
444 If `query-replace-interactive' is non-nil, the last incremental search
445 string is used as FROM-STRING--you don't have to specify it with the
446 minibuffer.
448 This function is usually the wrong thing to use in a Lisp program.
449 What you probably want is a loop like this:
450 (while (search-forward FROM-STRING nil t)
451 (replace-match TO-STRING nil t))
452 which will run faster and will not set the mark or print anything.
453 \(You may need a more complex loop if FROM-STRING can match the null string
454 and TO-STRING is also null.)"
455 (interactive
456 (let ((common
457 (query-replace-read-args
458 (concat "Replace"
459 (if current-prefix-arg " word" "")
460 " string"
461 (if (and transient-mark-mode mark-active) " in region" ""))
462 nil)))
463 (list (nth 0 common) (nth 1 common) (nth 2 common)
464 (if (and transient-mark-mode mark-active)
465 (region-beginning))
466 (if (and transient-mark-mode mark-active)
467 (region-end)))))
468 (perform-replace from-string to-string nil nil delimited nil nil start end))
470 (defun replace-regexp (regexp to-string &optional delimited start end)
471 "Replace things after point matching REGEXP with TO-STRING.
472 Preserve case in each match if `case-replace' and `case-fold-search'
473 are non-nil and REGEXP has no uppercase letters.
475 In Transient Mark mode, if the mark is active, operate on the contents
476 of the region. Otherwise, operate from point to the end of the buffer.
478 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
479 only matches surrounded by word boundaries.
480 Fourth and fifth arg START and END specify the region to operate on.
482 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
483 and `\\=\\N' (where N is a digit) stands for
484 whatever what matched the Nth `\\(...\\)' in REGEXP.
485 `\\?' lets you edit the replacement text in the minibuffer
486 at the given position for each replacement.
488 In interactive calls, the replacement text may contain `\\,'
489 followed by a Lisp expression used as part of the replacement
490 text. Inside of that expression, `\\&' is a string denoting the
491 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
492 numeric values from `string-to-number', and `\\#' itself for
493 `replace-count', the number of replacements occurred so far.
495 If your Lisp expression is an identifier and the next letter in
496 the replacement string would be interpreted as part of it, you
497 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
498 for this particular case you may also enter `\\#' in the
499 replacement text directly.
501 When using those Lisp features interactively in the replacement
502 text, TO-STRING is actually made a list instead of a string.
503 Use \\[repeat-complex-command] after this command for details.
505 If `query-replace-interactive' is non-nil, the last incremental search
506 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
508 This function is usually the wrong thing to use in a Lisp program.
509 What you probably want is a loop like this:
510 (while (re-search-forward REGEXP nil t)
511 (replace-match TO-STRING nil nil))
512 which will run faster and will not set the mark or print anything."
513 (interactive
514 (let ((common
515 (query-replace-read-args
516 (concat "Replace"
517 (if current-prefix-arg " word" "")
518 " regexp"
519 (if (and transient-mark-mode mark-active) " in region" ""))
520 t)))
521 (list (nth 0 common) (nth 1 common) (nth 2 common)
522 (if (and transient-mark-mode mark-active)
523 (region-beginning))
524 (if (and transient-mark-mode mark-active)
525 (region-end)))))
526 (perform-replace regexp to-string nil t delimited nil nil start end))
529 (defvar regexp-history nil
530 "History list for some commands that read regular expressions.
532 Maximum length of the history list is determined by the value
533 of `history-length', which see.")
535 (defvar occur-collect-regexp-history '("\\1")
536 "History of regexp for occur's collect operation")
538 (defun read-regexp (prompt &optional default-value)
539 "Read regexp as a string using the regexp history and some useful defaults.
540 Prompt for a regular expression with PROMPT (without a colon and
541 space) in the minibuffer. The optional argument DEFAULT-VALUE
542 provides the value to display in the minibuffer prompt that is
543 returned if the user just types RET.
544 Values available via M-n are the string at point, the last isearch
545 regexp, the last isearch string, and the last replacement regexp."
546 (let* ((defaults
547 (list (regexp-quote
548 (or (funcall (or find-tag-default-function
549 (get major-mode 'find-tag-default-function)
550 'find-tag-default))
551 ""))
552 (car regexp-search-ring)
553 (regexp-quote (or (car search-ring) ""))
554 (car (symbol-value
555 query-replace-from-history-variable))))
556 (defaults (delete-dups (delq nil (delete "" defaults))))
557 ;; Don't add automatically the car of defaults for empty input
558 (history-add-new-input nil)
559 (input
560 (read-from-minibuffer
561 (if default-value
562 (format "%s (default %s): " prompt
563 (query-replace-descr default-value))
564 (format "%s: " prompt))
565 nil nil nil 'regexp-history defaults t)))
566 (if (equal input "")
567 (or default-value input)
568 (prog1 input
569 (add-to-history 'regexp-history input)))))
572 (defalias 'delete-non-matching-lines 'keep-lines)
573 (defalias 'delete-matching-lines 'flush-lines)
574 (defalias 'count-matches 'how-many)
577 (defun keep-lines-read-args (prompt)
578 "Read arguments for `keep-lines' and friends.
579 Prompt for a regexp with PROMPT.
580 Value is a list, (REGEXP)."
581 (list (read-regexp prompt) nil nil t))
583 (defun keep-lines (regexp &optional rstart rend interactive)
584 "Delete all lines except those containing matches for REGEXP.
585 A match split across lines preserves all the lines it lies in.
586 When called from Lisp (and usually interactively as well, see below)
587 applies to all lines starting after point.
589 If REGEXP contains upper case characters (excluding those preceded by `\\')
590 and `search-upper-case' is non-nil, the matching is case-sensitive.
592 Second and third arg RSTART and REND specify the region to operate on.
593 This command operates on (the accessible part of) all lines whose
594 accessible part is entirely contained in the region determined by RSTART
595 and REND. (A newline ending a line counts as part of that line.)
597 Interactively, in Transient Mark mode when the mark is active, operate
598 on all lines whose accessible part is entirely contained in the region.
599 Otherwise, the command applies to all lines starting after point.
600 When calling this function from Lisp, you can pretend that it was
601 called interactively by passing a non-nil INTERACTIVE argument.
603 This function starts looking for the next match from the end of
604 the previous match. Hence, it ignores matches that overlap
605 a previously found match."
607 (interactive
608 (progn
609 (barf-if-buffer-read-only)
610 (keep-lines-read-args "Keep lines containing match for regexp")))
611 (if rstart
612 (progn
613 (goto-char (min rstart rend))
614 (setq rend
615 (progn
616 (save-excursion
617 (goto-char (max rstart rend))
618 (unless (or (bolp) (eobp))
619 (forward-line 0))
620 (point-marker)))))
621 (if (and interactive transient-mark-mode mark-active)
622 (setq rstart (region-beginning)
623 rend (progn
624 (goto-char (region-end))
625 (unless (or (bolp) (eobp))
626 (forward-line 0))
627 (point-marker)))
628 (setq rstart (point)
629 rend (point-max-marker)))
630 (goto-char rstart))
631 (save-excursion
632 (or (bolp) (forward-line 1))
633 (let ((start (point))
634 (case-fold-search
635 (if (and case-fold-search search-upper-case)
636 (isearch-no-upper-case-p regexp t)
637 case-fold-search)))
638 (while (< (point) rend)
639 ;; Start is first char not preserved by previous match.
640 (if (not (re-search-forward regexp rend 'move))
641 (delete-region start rend)
642 (let ((end (save-excursion (goto-char (match-beginning 0))
643 (forward-line 0)
644 (point))))
645 ;; Now end is first char preserved by the new match.
646 (if (< start end)
647 (delete-region start end))))
649 (setq start (save-excursion (forward-line 1) (point)))
650 ;; If the match was empty, avoid matching again at same place.
651 (and (< (point) rend)
652 (= (match-beginning 0) (match-end 0))
653 (forward-char 1)))))
654 (set-marker rend nil)
655 nil)
658 (defun flush-lines (regexp &optional rstart rend interactive)
659 "Delete lines containing matches for REGEXP.
660 When called from Lisp (and usually when called interactively as
661 well, see below), applies to the part of the buffer after point.
662 The line point is in is deleted if and only if it contains a
663 match for regexp starting after point.
665 If REGEXP contains upper case characters (excluding those preceded by `\\')
666 and `search-upper-case' is non-nil, the matching is case-sensitive.
668 Second and third arg RSTART and REND specify the region to operate on.
669 Lines partially contained in this region are deleted if and only if
670 they contain a match entirely contained in it.
672 Interactively, in Transient Mark mode when the mark is active, operate
673 on the contents of the region. Otherwise, operate from point to the
674 end of (the accessible portion of) the buffer. When calling this function
675 from Lisp, you can pretend that it was called interactively by passing
676 a non-nil INTERACTIVE argument.
678 If a match is split across lines, all the lines it lies in are deleted.
679 They are deleted _before_ looking for the next match. Hence, a match
680 starting on the same line at which another match ended is ignored."
682 (interactive
683 (progn
684 (barf-if-buffer-read-only)
685 (keep-lines-read-args "Flush lines containing match for regexp")))
686 (if rstart
687 (progn
688 (goto-char (min rstart rend))
689 (setq rend (copy-marker (max rstart rend))))
690 (if (and interactive transient-mark-mode mark-active)
691 (setq rstart (region-beginning)
692 rend (copy-marker (region-end)))
693 (setq rstart (point)
694 rend (point-max-marker)))
695 (goto-char rstart))
696 (let ((case-fold-search
697 (if (and case-fold-search search-upper-case)
698 (isearch-no-upper-case-p regexp t)
699 case-fold-search)))
700 (save-excursion
701 (while (and (< (point) rend)
702 (re-search-forward regexp rend t))
703 (delete-region (save-excursion (goto-char (match-beginning 0))
704 (forward-line 0)
705 (point))
706 (progn (forward-line 1) (point))))))
707 (set-marker rend nil)
708 nil)
711 (defun how-many (regexp &optional rstart rend interactive)
712 "Print and return number of matches for REGEXP following point.
713 When called from Lisp and INTERACTIVE is omitted or nil, just return
714 the number, do not print it; if INTERACTIVE is t, the function behaves
715 in all respects as if it had been called interactively.
717 If REGEXP contains upper case characters (excluding those preceded by `\\')
718 and `search-upper-case' is non-nil, the matching is case-sensitive.
720 Second and third arg RSTART and REND specify the region to operate on.
722 Interactively, in Transient Mark mode when the mark is active, operate
723 on the contents of the region. Otherwise, operate from point to the
724 end of (the accessible portion of) the buffer.
726 This function starts looking for the next match from the end of
727 the previous match. Hence, it ignores matches that overlap
728 a previously found match."
730 (interactive
731 (keep-lines-read-args "How many matches for regexp"))
732 (save-excursion
733 (if rstart
734 (progn
735 (goto-char (min rstart rend))
736 (setq rend (max rstart rend)))
737 (if (and interactive transient-mark-mode mark-active)
738 (setq rstart (region-beginning)
739 rend (region-end))
740 (setq rstart (point)
741 rend (point-max)))
742 (goto-char rstart))
743 (let ((count 0)
744 opoint
745 (case-fold-search
746 (if (and case-fold-search search-upper-case)
747 (isearch-no-upper-case-p regexp t)
748 case-fold-search)))
749 (while (and (< (point) rend)
750 (progn (setq opoint (point))
751 (re-search-forward regexp rend t)))
752 (if (= opoint (point))
753 (forward-char 1)
754 (setq count (1+ count))))
755 (when interactive (message "%d occurrence%s"
756 count
757 (if (= count 1) "" "s")))
758 count)))
761 (defvar occur-mode-map
762 (let ((map (make-sparse-keymap)))
763 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
764 (define-key map [mouse-2] 'occur-mode-mouse-goto)
765 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
766 (define-key map "\C-m" 'occur-mode-goto-occurrence)
767 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
768 (define-key map "\C-o" 'occur-mode-display-occurrence)
769 (define-key map "\M-n" 'occur-next)
770 (define-key map "\M-p" 'occur-prev)
771 (define-key map "r" 'occur-rename-buffer)
772 (define-key map "c" 'clone-buffer)
773 (define-key map "g" 'revert-buffer)
774 (define-key map "q" 'quit-window)
775 (define-key map "z" 'kill-this-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-bar-make-mm-toggle next-error-follow-minor-mode
782 "Auto Occurrence Display"
783 "Display another occurrence when moving the cursor"))
784 (define-key map [separator-1] menu-bar-separator)
785 (define-key map [kill-this-buffer]
786 `(menu-item ,(purecopy "Kill occur buffer") kill-this-buffer
787 :help ,(purecopy "Kill the current *Occur* buffer")))
788 (define-key map [quit-window]
789 `(menu-item ,(purecopy "Quit occur window") quit-window
790 :help ,(purecopy "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame")))
791 (define-key map [revert-buffer]
792 `(menu-item ,(purecopy "Revert occur buffer") revert-buffer
793 :help ,(purecopy "Replace the text in the *Occur* buffer with the results of rerunning occur")))
794 (define-key map [clone-buffer]
795 `(menu-item ,(purecopy "Clone occur buffer") clone-buffer
796 :help ,(purecopy "Create and return a twin copy of the current *Occur* buffer")))
797 (define-key map [occur-rename-buffer]
798 `(menu-item ,(purecopy "Rename occur buffer") occur-rename-buffer
799 :help ,(purecopy "Rename the current *Occur* buffer to *Occur: original-buffer-name*.")))
800 (define-key map [separator-2] menu-bar-separator)
801 (define-key map [occur-mode-goto-occurrence-other-window]
802 `(menu-item ,(purecopy "Go To Occurrence Other Window") occur-mode-goto-occurrence-other-window
803 :help ,(purecopy "Go to the occurrence the current line describes, in another window")))
804 (define-key map [occur-mode-goto-occurrence]
805 `(menu-item ,(purecopy "Go To Occurrence") occur-mode-goto-occurrence
806 :help ,(purecopy "Go to the occurrence the current line describes")))
807 (define-key map [occur-mode-display-occurrence]
808 `(menu-item ,(purecopy "Display Occurrence") occur-mode-display-occurrence
809 :help ,(purecopy "Display in another window the occurrence the current line describes")))
810 (define-key map [occur-next]
811 `(menu-item ,(purecopy "Move to next match") occur-next
812 :help ,(purecopy "Move to the Nth (default 1) next match in an Occur mode buffer")))
813 (define-key map [occur-prev]
814 `(menu-item ,(purecopy "Move to previous match") occur-prev
815 :help ,(purecopy "Move to the Nth (default 1) previous match in an Occur mode buffer")))
816 map)
817 "Keymap for `occur-mode'.")
819 (defvar occur-revert-arguments nil
820 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
821 See `occur-revert-function'.")
823 (defcustom occur-mode-hook '(turn-on-font-lock)
824 "Hook run when entering Occur mode."
825 :type 'hook
826 :group 'matching)
828 (defcustom occur-hook nil
829 "Hook run by Occur when there are any matches."
830 :type 'hook
831 :group 'matching)
833 (defcustom occur-mode-find-occurrence-hook nil
834 "Hook run by Occur after locating an occurrence.
835 This will be called with the cursor position at the occurrence. An application
836 for this is to reveal context in an outline-mode when the occurrence is hidden."
837 :type 'hook
838 :group 'matching)
840 (put 'occur-mode 'mode-class 'special)
841 (defun occur-mode ()
842 "Major mode for output from \\[occur].
843 \\<occur-mode-map>Move point to one of the items in this buffer, then use
844 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
845 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
847 \\{occur-mode-map}"
848 (interactive)
849 (kill-all-local-variables)
850 (use-local-map occur-mode-map)
851 (setq major-mode 'occur-mode)
852 (setq mode-name "Occur")
853 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
854 (make-local-variable 'occur-revert-arguments)
855 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
856 (setq next-error-function 'occur-next-error)
857 (run-mode-hooks 'occur-mode-hook))
859 (defun occur-revert-function (ignore1 ignore2)
860 "Handle `revert-buffer' for Occur mode buffers."
861 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
863 (defun occur-mode-find-occurrence ()
864 (let ((pos (get-text-property (point) 'occur-target)))
865 (unless pos
866 (error "No occurrence on this line"))
867 (unless (buffer-live-p (marker-buffer pos))
868 (error "Buffer for this occurrence was killed"))
869 pos))
871 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
872 (defun occur-mode-goto-occurrence (&optional event)
873 "Go to the occurrence the current line describes."
874 (interactive (list last-nonmenu-event))
875 (let ((pos
876 (if (null event)
877 ;; Actually `event-end' works correctly with a nil argument as
878 ;; well, so we could dispense with this test, but let's not
879 ;; rely on this undocumented behavior.
880 (occur-mode-find-occurrence)
881 (with-current-buffer (window-buffer (posn-window (event-end event)))
882 (save-excursion
883 (goto-char (posn-point (event-end event)))
884 (occur-mode-find-occurrence)))))
885 same-window-buffer-names
886 same-window-regexps)
887 (pop-to-buffer (marker-buffer pos))
888 (goto-char pos)
889 (run-hooks 'occur-mode-find-occurrence-hook)))
891 (defun occur-mode-goto-occurrence-other-window ()
892 "Go to the occurrence the current line describes, in another window."
893 (interactive)
894 (let ((pos (occur-mode-find-occurrence)))
895 (switch-to-buffer-other-window (marker-buffer pos))
896 (goto-char pos)
897 (run-hooks 'occur-mode-find-occurrence-hook)))
899 (defun occur-mode-display-occurrence ()
900 "Display in another window the occurrence the current line describes."
901 (interactive)
902 (let ((pos (occur-mode-find-occurrence))
903 window
904 ;; Bind these to ensure `display-buffer' puts it in another window.
905 same-window-buffer-names
906 same-window-regexps)
907 (setq window (display-buffer (marker-buffer pos)))
908 ;; This is the way to set point in the proper window.
909 (save-selected-window
910 (select-window window)
911 (goto-char pos)
912 (run-hooks 'occur-mode-find-occurrence-hook))))
914 (defun occur-find-match (n search message)
915 (if (not n) (setq n 1))
916 (let ((r))
917 (while (> n 0)
918 (setq r (funcall search (point) 'occur-match))
919 (and r
920 (get-text-property r 'occur-match)
921 (setq r (funcall search r 'occur-match)))
922 (if r
923 (goto-char r)
924 (error message))
925 (setq n (1- n)))))
927 (defun occur-next (&optional n)
928 "Move to the Nth (default 1) next match in an Occur mode buffer."
929 (interactive "p")
930 (occur-find-match n #'next-single-property-change "No more matches"))
932 (defun occur-prev (&optional n)
933 "Move to the Nth (default 1) previous match in an Occur mode buffer."
934 (interactive "p")
935 (occur-find-match n #'previous-single-property-change "No earlier matches"))
937 (defun occur-next-error (&optional argp reset)
938 "Move to the Nth (default 1) next match in an Occur mode buffer.
939 Compatibility function for \\[next-error] invocations."
940 (interactive "p")
941 ;; we need to run occur-find-match from within the Occur buffer
942 (with-current-buffer
943 ;; Choose the buffer and make it current.
944 (if (next-error-buffer-p (current-buffer))
945 (current-buffer)
946 (next-error-find-buffer nil nil
947 (lambda ()
948 (eq major-mode 'occur-mode))))
950 (goto-char (cond (reset (point-min))
951 ((< argp 0) (line-beginning-position))
952 ((> argp 0) (line-end-position))
953 ((point))))
954 (occur-find-match
955 (abs argp)
956 (if (> 0 argp)
957 #'previous-single-property-change
958 #'next-single-property-change)
959 "No more matches")
960 ;; In case the *Occur* buffer is visible in a nonselected window.
961 (let ((win (get-buffer-window (current-buffer) t)))
962 (if win (set-window-point win (point))))
963 (occur-mode-goto-occurrence)))
965 (defface match
966 '((((class color) (min-colors 88) (background light))
967 :background "yellow1")
968 (((class color) (min-colors 88) (background dark))
969 :background "RoyalBlue3")
970 (((class color) (min-colors 8) (background light))
971 :background "yellow" :foreground "black")
972 (((class color) (min-colors 8) (background dark))
973 :background "blue" :foreground "white")
974 (((type tty) (class mono))
975 :inverse-video t)
976 (t :background "gray"))
977 "Face used to highlight matches permanently."
978 :group 'matching
979 :version "22.1")
981 (defcustom list-matching-lines-default-context-lines 0
982 "Default number of context lines included around `list-matching-lines' matches.
983 A negative number means to include that many lines before the match.
984 A positive number means to include that many lines both before and after."
985 :type 'integer
986 :group 'matching)
988 (defalias 'list-matching-lines 'occur)
990 (defcustom list-matching-lines-face 'match
991 "Face used by \\[list-matching-lines] to show the text that matches.
992 If the value is nil, don't highlight the matching portions specially."
993 :type 'face
994 :group 'matching)
996 (defcustom list-matching-lines-buffer-name-face 'underline
997 "Face used by \\[list-matching-lines] to show the names of buffers.
998 If the value is nil, don't highlight the buffer names specially."
999 :type 'face
1000 :group 'matching)
1002 (defcustom occur-excluded-properties
1003 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1004 yank-handler follow-link)
1005 "Text properties to discard when copying lines to the *Occur* buffer.
1006 The value should be a list of text properties to discard or t,
1007 which means to discard all text properties."
1008 :type '(choice (const :tag "All" t) (repeat symbol))
1009 :group 'matching
1010 :version "22.1")
1012 (defun occur-read-primary-args ()
1013 (let* ((perform-collect (consp current-prefix-arg))
1014 (regexp (read-regexp (if perform-collect
1015 "Collect strings matching regexp"
1016 "List lines matching regexp")
1017 (car regexp-history))))
1018 (list regexp
1019 (if perform-collect
1020 ;; Perform collect operation
1021 (if (zerop (regexp-opt-depth regexp))
1022 ;; No subexpression so collect the entire match.
1023 "\\&"
1024 ;; Get the regexp for collection pattern.
1025 (let ((default (car occur-collect-regexp-history)))
1026 (read-string
1027 (format "Regexp to collect (default %s): " default)
1028 nil 'occur-collect-regexp-history default)))
1029 ;; Otherwise normal occur takes numerical prefix argument.
1030 (when current-prefix-arg
1031 (prefix-numeric-value current-prefix-arg))))))
1033 (defun occur-rename-buffer (&optional unique-p interactive-p)
1034 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1035 Here `original-buffer-name' is the buffer name where Occur was originally run.
1036 When given the prefix argument, or called non-interactively, the renaming
1037 will not clobber the existing buffer(s) of that name, but use
1038 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1039 if you always want a separate *Occur* buffer for each buffer where you
1040 invoke `occur'."
1041 (interactive "P\np")
1042 (with-current-buffer
1043 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1044 (rename-buffer (concat "*Occur: "
1045 (mapconcat #'buffer-name
1046 (car (cddr occur-revert-arguments)) "/")
1047 "*")
1048 (or unique-p (not interactive-p)))))
1050 (defun occur (regexp &optional nlines)
1051 "Show all lines in the current buffer containing a match for REGEXP.
1052 If a match spreads across multiple lines, all those lines are shown.
1054 Each line is displayed with NLINES lines before and after, or -NLINES
1055 before if NLINES is negative.
1056 NLINES defaults to `list-matching-lines-default-context-lines'.
1057 Interactively it is the prefix arg.
1059 The lines are shown in a buffer named `*Occur*'.
1060 It serves as a menu to find any of the occurrences in this buffer.
1061 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1063 If REGEXP contains upper case characters (excluding those preceded by `\\')
1064 and `search-upper-case' is non-nil, the matching is case-sensitive.
1066 When NLINES is a string or when the function is called
1067 interactively with prefix argument without a number (`C-u' alone
1068 as prefix) the matching strings are collected into the `*Occur*'
1069 buffer by using NLINES as a replacement regexp. NLINES may
1070 contain \\& and \\N which convention follows `replace-match'.
1071 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1072 \"\\1\" for NLINES collects all the function names in a lisp
1073 program. When there is no parenthesized subexpressions in REGEXP
1074 the entire match is collected. In any case the searched buffers
1075 are not modified."
1076 (interactive (occur-read-primary-args))
1077 (occur-1 regexp nlines (list (current-buffer))))
1079 (defun multi-occur (bufs regexp &optional nlines)
1080 "Show all lines in buffers BUFS containing a match for REGEXP.
1081 This function acts on multiple buffers; otherwise, it is exactly like
1082 `occur'. When you invoke this command interactively, you must specify
1083 the buffer names that you want, one by one."
1084 (interactive
1085 (cons
1086 (let* ((bufs (list (read-buffer "First buffer to search: "
1087 (current-buffer) t)))
1088 (buf nil)
1089 (ido-ignore-item-temp-list bufs))
1090 (while (not (string-equal
1091 (setq buf (read-buffer
1092 (if (eq read-buffer-function 'ido-read-buffer)
1093 "Next buffer to search (C-j to end): "
1094 "Next buffer to search (RET to end): ")
1095 nil t))
1096 ""))
1097 (add-to-list 'bufs buf)
1098 (setq ido-ignore-item-temp-list bufs))
1099 (nreverse (mapcar #'get-buffer bufs)))
1100 (occur-read-primary-args)))
1101 (occur-1 regexp nlines bufs))
1103 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1104 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1105 Normally BUFREGEXP matches against each buffer's visited file name,
1106 but if you specify a prefix argument, it matches against the buffer name.
1107 See also `multi-occur'."
1108 (interactive
1109 (cons
1110 (let* ((default (car regexp-history))
1111 (input
1112 (read-from-minibuffer
1113 (if current-prefix-arg
1114 "List lines in buffers whose names match regexp: "
1115 "List lines in buffers whose filenames match regexp: ")
1119 'regexp-history)))
1120 (if (equal input "")
1121 default
1122 input))
1123 (occur-read-primary-args)))
1124 (when bufregexp
1125 (occur-1 regexp nil
1126 (delq nil
1127 (mapcar (lambda (buf)
1128 (when (if allbufs
1129 (string-match bufregexp
1130 (buffer-name buf))
1131 (and (buffer-file-name buf)
1132 (string-match bufregexp
1133 (buffer-file-name buf))))
1134 buf))
1135 (buffer-list))))))
1137 (defun occur-1 (regexp nlines bufs &optional buf-name)
1138 (unless (and regexp (not (equal regexp "")))
1139 (error "Occur doesn't work with the empty regexp"))
1140 (unless buf-name
1141 (setq buf-name "*Occur*"))
1142 (let (occur-buf
1143 (active-bufs (delq nil (mapcar #'(lambda (buf)
1144 (when (buffer-live-p buf) buf))
1145 bufs))))
1146 ;; Handle the case where one of the buffers we're searching is the
1147 ;; output buffer. Just rename it.
1148 (when (member buf-name (mapcar 'buffer-name active-bufs))
1149 (with-current-buffer (get-buffer buf-name)
1150 (rename-uniquely)))
1152 ;; Now find or create the output buffer.
1153 ;; If we just renamed that buffer, we will make a new one here.
1154 (setq occur-buf (get-buffer-create buf-name))
1156 (with-current-buffer occur-buf
1157 (if (stringp nlines)
1158 (fundamental-mode) ;; This is for collect opeartion.
1159 (occur-mode))
1160 (let ((inhibit-read-only t)
1161 ;; Don't generate undo entries for creation of the initial contents.
1162 (buffer-undo-list t))
1163 (erase-buffer)
1164 (let ((count
1165 (if (stringp nlines)
1166 ;; Treat nlines as a regexp to collect.
1167 (let ((bufs active-bufs)
1168 (count 0))
1169 (while bufs
1170 (with-current-buffer (car bufs)
1171 (save-excursion
1172 (goto-char (point-min))
1173 (while (re-search-forward regexp nil t)
1174 ;; Insert the replacement regexp.
1175 (let ((str (match-substitute-replacement nlines)))
1176 (if str
1177 (with-current-buffer occur-buf
1178 (insert str)
1179 (setq count (1+ count))
1180 (or (zerop (current-column))
1181 (insert "\n"))))))))
1182 (setq bufs (cdr bufs)))
1183 count)
1184 ;; Perform normal occur.
1185 (occur-engine
1186 regexp active-bufs occur-buf
1187 (or nlines list-matching-lines-default-context-lines)
1188 (if (and case-fold-search search-upper-case)
1189 (isearch-no-upper-case-p regexp t)
1190 case-fold-search)
1191 list-matching-lines-buffer-name-face
1192 nil list-matching-lines-face
1193 (not (eq occur-excluded-properties t))))))
1194 (let* ((bufcount (length active-bufs))
1195 (diff (- (length bufs) bufcount)))
1196 (message "Searched %d buffer%s%s; %s match%s%s"
1197 bufcount (if (= bufcount 1) "" "s")
1198 (if (zerop diff) "" (format " (%d killed)" diff))
1199 (if (zerop count) "no" (format "%d" count))
1200 (if (= count 1) "" "es")
1201 ;; Don't display regexp if with remaining text
1202 ;; it is longer than window-width.
1203 (if (> (+ (length regexp) 42) (window-width))
1204 "" (format " for `%s'" (query-replace-descr regexp)))))
1205 (setq occur-revert-arguments (list regexp nlines bufs))
1206 (if (= count 0)
1207 (kill-buffer occur-buf)
1208 (display-buffer occur-buf)
1209 (setq next-error-last-buffer occur-buf)
1210 (setq buffer-read-only t)
1211 (set-buffer-modified-p nil)
1212 (run-hooks 'occur-hook)))))))
1214 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
1215 title-face prefix-face match-face keep-props)
1216 (with-current-buffer out-buf
1217 (let ((globalcount 0)
1218 (coding nil))
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 (let ((beg (point))
1319 (end (progn (insert data) (point)))))))
1320 (goto-char endpt))
1321 (if endpt
1322 (progn
1323 ;; Sum line numbers between first and last match lines.
1324 (setq lines (+ lines (count-lines begpt endpt)
1325 ;; Add 1 for empty last match line since
1326 ;; count-lines returns 1 line less.
1327 (if (and (bolp) (eolp)) 1 0)))
1328 ;; On to the next match...
1329 (forward-line 1))
1330 (goto-char (point-max)))
1331 (setq prev-lines (1- lines)))
1332 ;; Flush remaining context after-lines.
1333 (when prev-after-lines
1334 (with-current-buffer out-buf
1335 (insert (apply #'concat (occur-engine-add-prefix
1336 prev-after-lines)))))))
1337 (when (not (zerop matches)) ;; is the count zero?
1338 (setq globalcount (+ globalcount matches))
1339 (with-current-buffer out-buf
1340 (goto-char headerpt)
1341 (let ((beg (point))
1342 end)
1343 (insert (format "%d match%s%s in buffer: %s\n"
1344 matches (if (= matches 1) "" "es")
1345 ;; Don't display regexp for multi-buffer.
1346 (if (> (length buffers) 1)
1347 "" (format " for \"%s\""
1348 (query-replace-descr regexp)))
1349 (buffer-name buf)))
1350 (setq end (point))
1351 (add-text-properties beg end
1352 (append
1353 (when title-face
1354 `(font-lock-face ,title-face))
1355 `(occur-title ,buf))))
1356 (goto-char (point-min)))))))
1357 ;; Display total match count and regexp for multi-buffer.
1358 (when (and (not (zerop globalcount)) (> (length buffers) 1))
1359 (goto-char (point-min))
1360 (let ((beg (point))
1361 end)
1362 (insert (format "%d match%s total for \"%s\":\n"
1363 globalcount (if (= globalcount 1) "" "es")
1364 (query-replace-descr regexp)))
1365 (setq end (point))
1366 (add-text-properties beg end (when title-face
1367 `(font-lock-face ,title-face))))
1368 (goto-char (point-min)))
1369 (if coding
1370 ;; CODING is buffer-file-coding-system of the first buffer
1371 ;; that locally binds it. Let's use it also for the output
1372 ;; buffer.
1373 (set-buffer-file-coding-system coding))
1374 ;; Return the number of matches
1375 globalcount)))
1377 (defun occur-engine-line (beg end &optional keep-props)
1378 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1379 (text-property-not-all beg end 'fontified t))
1380 (if (fboundp 'jit-lock-fontify-now)
1381 (jit-lock-fontify-now beg end)))
1382 (if (and keep-props (not (eq occur-excluded-properties t)))
1383 (let ((str (buffer-substring beg end)))
1384 (remove-list-of-text-properties
1385 0 (length str) occur-excluded-properties str)
1386 str)
1387 (buffer-substring-no-properties beg end)))
1389 (defun occur-engine-add-prefix (lines)
1390 (mapcar
1391 #'(lambda (line)
1392 (concat " :" line "\n"))
1393 lines))
1395 (defun occur-accumulate-lines (count &optional keep-props pt)
1396 (save-excursion
1397 (when pt
1398 (goto-char pt))
1399 (let ((forwardp (> count 0))
1400 result beg end moved)
1401 (while (not (or (zerop count)
1402 (if forwardp
1403 (eobp)
1404 (and (bobp) (not moved)))))
1405 (setq count (+ count (if forwardp -1 1)))
1406 (setq beg (line-beginning-position)
1407 end (line-end-position))
1408 (push (occur-engine-line beg end keep-props) result)
1409 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1410 (nreverse result))))
1412 ;; Generate context display for occur.
1413 ;; OUT-LINE is the line where the match is.
1414 ;; NLINES and KEEP-PROPS are args to occur-engine.
1415 ;; LINES is line count of the current match,
1416 ;; PREV-LINES is line count of the previous match,
1417 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1418 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1419 ;; then concatenate them all together.
1420 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1421 lines prev-lines prev-after-lines)
1422 ;; Find after- and before-context lines of the current match.
1423 (let ((before-lines
1424 (nreverse (cdr (occur-accumulate-lines
1425 (- (1+ (abs nlines))) keep-props begpt))))
1426 (after-lines
1427 (cdr (occur-accumulate-lines
1428 (1+ nlines) keep-props endpt)))
1429 separator)
1431 ;; Combine after-lines of the previous match
1432 ;; with before-lines of the current match.
1434 (when prev-after-lines
1435 ;; Don't overlap prev after-lines with current before-lines.
1436 (if (>= (+ prev-lines (length prev-after-lines))
1437 (- lines (length before-lines)))
1438 (setq prev-after-lines
1439 (butlast prev-after-lines
1440 (- (length prev-after-lines)
1441 (- lines prev-lines (length before-lines) 1))))
1442 ;; Separate non-overlapping context lines with a dashed line.
1443 (setq separator "-------\n")))
1445 (when prev-lines
1446 ;; Don't overlap current before-lines with previous match line.
1447 (if (<= (- lines (length before-lines))
1448 prev-lines)
1449 (setq before-lines
1450 (nthcdr (- (length before-lines)
1451 (- lines prev-lines 1))
1452 before-lines))
1453 ;; Separate non-overlapping before-context lines.
1454 (unless (> nlines 0)
1455 (setq separator "-------\n"))))
1457 (list
1458 ;; Return a list where the first element is the output line.
1459 (apply #'concat
1460 (append
1461 (and prev-after-lines
1462 (occur-engine-add-prefix prev-after-lines))
1463 (and separator (list separator))
1464 (occur-engine-add-prefix before-lines)
1465 (list out-line)))
1466 ;; And the second element is the list of context after-lines.
1467 (if (> nlines 0) after-lines))))
1470 ;; It would be nice to use \\[...], but there is no reasonable way
1471 ;; to make that display both SPC and Y.
1472 (defconst query-replace-help
1473 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1474 RET or `q' to exit, Period to replace one match and exit,
1475 Comma to replace but not move point immediately,
1476 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1477 C-w to delete match and recursive edit,
1478 C-l to clear the screen, redisplay, and offer same replacement again,
1479 ! to replace all remaining matches with no more questions,
1480 ^ to move point back to previous match,
1481 E to edit the replacement string"
1482 "Help message while in `query-replace'.")
1484 (defvar query-replace-map
1485 (let ((map (make-sparse-keymap)))
1486 (define-key map " " 'act)
1487 (define-key map "\d" 'skip)
1488 (define-key map [delete] 'skip)
1489 (define-key map [backspace] 'skip)
1490 (define-key map "y" 'act)
1491 (define-key map "n" 'skip)
1492 (define-key map "Y" 'act)
1493 (define-key map "N" 'skip)
1494 (define-key map "e" 'edit-replacement)
1495 (define-key map "E" 'edit-replacement)
1496 (define-key map "," 'act-and-show)
1497 (define-key map "q" 'exit)
1498 (define-key map "\r" 'exit)
1499 (define-key map [return] 'exit)
1500 (define-key map "." 'act-and-exit)
1501 (define-key map "\C-r" 'edit)
1502 (define-key map "\C-w" 'delete-and-edit)
1503 (define-key map "\C-l" 'recenter)
1504 (define-key map "!" 'automatic)
1505 (define-key map "^" 'backup)
1506 (define-key map "\C-h" 'help)
1507 (define-key map [f1] 'help)
1508 (define-key map [help] 'help)
1509 (define-key map "?" 'help)
1510 (define-key map "\C-g" 'quit)
1511 (define-key map "\C-]" 'quit)
1512 (define-key map "\e" 'exit-prefix)
1513 (define-key map [escape] 'exit-prefix)
1514 map)
1515 "Keymap that defines the responses to questions in `query-replace'.
1516 The \"bindings\" in this map are not commands; they are answers.
1517 The valid answers include `act', `skip', `act-and-show',
1518 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1519 `automatic', `backup', `exit-prefix', and `help'.")
1521 (defvar multi-query-replace-map
1522 (let ((map (make-sparse-keymap)))
1523 (set-keymap-parent map query-replace-map)
1524 (define-key map "Y" 'automatic-all)
1525 (define-key map "N" 'exit-current)
1526 map)
1527 "Keymap that defines additional bindings for multi-buffer replacements.
1528 It extends its parent map `query-replace-map' with new bindings to
1529 operate on a set of buffers/files. The difference with its parent map
1530 is the additional answers `automatic-all' to replace all remaining
1531 matches in all remaining buffers with no more questions, and
1532 `exit-current' to skip remaining matches in the current buffer
1533 and to continue with the next buffer in the sequence.")
1535 (defun replace-match-string-symbols (n)
1536 "Process a list (and any sub-lists), expanding certain symbols.
1537 Symbol Expands To
1538 N (match-string N) (where N is a string of digits)
1539 #N (string-to-number (match-string N))
1540 & (match-string 0)
1541 #& (string-to-number (match-string 0))
1542 # replace-count
1544 Note that these symbols must be preceeded by a backslash in order to
1545 type them using Lisp syntax."
1546 (while (consp n)
1547 (cond
1548 ((consp (car n))
1549 (replace-match-string-symbols (car n))) ;Process sub-list
1550 ((symbolp (car n))
1551 (let ((name (symbol-name (car n))))
1552 (cond
1553 ((string-match "^[0-9]+$" name)
1554 (setcar n (list 'match-string (string-to-number name))))
1555 ((string-match "^#[0-9]+$" name)
1556 (setcar n (list 'string-to-number
1557 (list 'match-string
1558 (string-to-number (substring name 1))))))
1559 ((string= "&" name)
1560 (setcar n '(match-string 0)))
1561 ((string= "#&" name)
1562 (setcar n '(string-to-number (match-string 0))))
1563 ((string= "#" name)
1564 (setcar n 'replace-count))))))
1565 (setq n (cdr n))))
1567 (defun replace-eval-replacement (expression replace-count)
1568 (let ((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 replace-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) replace-count)
1595 (progn
1596 (aset data 0 (+ replace-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 replace-overlay nil)
2023 (defun replace-highlight (match-beg match-end range-beg range-end
2024 string regexp case-fold)
2025 (if query-replace-highlight
2026 (if replace-overlay
2027 (move-overlay replace-overlay match-beg match-end (current-buffer))
2028 (setq replace-overlay (make-overlay match-beg match-end))
2029 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2030 (overlay-put replace-overlay 'face 'query-replace)))
2031 (if query-replace-lazy-highlight
2032 (let ((isearch-string string)
2033 (isearch-regexp regexp)
2034 (search-whitespace-regexp nil)
2035 (isearch-case-fold-search case-fold)
2036 (isearch-forward t)
2037 (isearch-error nil))
2038 ;; Set isearch-word to nil because word-replace is regexp-based,
2039 ;; so `isearch-search-fun' should not use `word-search-forward'.
2040 (if (and isearch-word isearch-regexp) (setq isearch-word nil))
2041 (isearch-lazy-highlight-new-loop range-beg range-end))))
2043 (defun replace-dehighlight ()
2044 (when replace-overlay
2045 (delete-overlay replace-overlay))
2046 (when query-replace-lazy-highlight
2047 (lazy-highlight-cleanup lazy-highlight-cleanup)
2048 (setq isearch-lazy-highlight-last-string nil)))
2050 ;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
2051 ;;; replace.el ends here