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 Free Software Foundation, Inc.
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
27 ;; This package supplies the string and regular-expression replace functions
28 ;; documented in the Emacs user's manual.
32 (defcustom case-replace t
33 "*Non-nil means `query-replace' should preserve case in replacements."
37 (defvar query-replace-history nil
)
39 (defvar query-replace-defaults nil
40 "Default values of FROM-STRING and TO-STRING for `query-replace'.
41 This is a cons cell (FROM-STRING . TO-STRING), or nil if there is
44 (defvar query-replace-interactive nil
45 "Non-nil means `query-replace' uses the last search string.
46 That becomes the \"string to replace\".")
48 (defcustom query-replace-from-history-variable
'query-replace-history
49 "History list to use for the FROM argument of `query-replace' commands.
50 The value of this variable should be a symbol; that symbol
51 is used as a variable to hold a history list for the strings
52 or patterns to be replaced."
57 (defcustom query-replace-to-history-variable
'query-replace-history
58 "History list to use for the TO argument of `query-replace' commands.
59 The value of this variable should be a symbol; that symbol
60 is used as a variable to hold a history list for replacement
66 (defcustom query-replace-skip-read-only nil
67 "*Non-nil means `query-replace' and friends ignore read-only matches."
72 (defcustom query-replace-highlight t
73 "*Non-nil means to highlight matches during query replacement."
77 (defcustom query-replace-lazy-highlight t
78 "*Controls the lazy-highlighting during query replacements.
79 When non-nil, all text in the buffer matching the current match
80 is highlighted lazily using isearch lazy highlighting (see
81 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
83 :group
'lazy-highlight
87 (defface query-replace
88 '((t (:inherit isearch
)))
89 "Face for highlighting query replacement matches."
93 (defun query-replace-descr (string)
94 (mapconcat 'isearch-text-char-description string
""))
96 (defun query-replace-read-from (prompt regexp-flag
)
97 "Query and return the `from' argument of a query-replace operation.
98 The return value can also be a pair (FROM . TO) indicating that the user
99 wants to replace FROM with TO."
100 (if query-replace-interactive
101 (car (if regexp-flag regexp-search-ring search-ring
))
102 (let* ((history-add-new-input nil
)
104 ;; The save-excursion here is in case the user marks and copies
105 ;; a region in order to specify the minibuffer input.
106 ;; That should not clobber the region for the query-replace itself.
108 (read-from-minibuffer
109 (if query-replace-defaults
110 (format "%s (default %s -> %s): " prompt
111 (query-replace-descr (car query-replace-defaults
))
112 (query-replace-descr (cdr query-replace-defaults
)))
113 (format "%s: " prompt
))
115 query-replace-from-history-variable
117 (if (and (zerop (length from
)) query-replace-defaults
)
118 (cons (car query-replace-defaults
)
119 (query-replace-compile-replacement
120 (cdr query-replace-defaults
) regexp-flag
))
121 (add-to-history query-replace-from-history-variable from nil t
)
122 ;; Warn if user types \n or \t, but don't reject the input.
124 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
125 (let ((match (match-string 3 from
)))
127 ((string= match
"\\n")
128 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
129 ((string= match
"\\t")
130 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
134 (defun query-replace-compile-replacement (to regexp-flag
)
135 "Maybe convert a regexp replacement TO to Lisp.
136 Returns a list suitable for `perform-replace' if necessary,
137 the original string if not."
139 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
))
143 (setq pos
(match-end 0))
144 (push (substring to
0 (- pos
2)) list
)
145 (setq char
(aref to
(1- pos
))
146 to
(substring to pos
))
148 (push '(number-to-string replace-count
) list
))
150 (setq pos
(read-from-string to
))
151 (push `(replace-quote ,(car pos
)) list
)
153 ;; Swallow a space after a symbol
154 ;; if there is a space.
155 (if (and (or (symbolp (car pos
))
156 ;; Swallow a space after 'foo
157 ;; but not after (quote foo).
158 (and (eq (car-safe (car pos
)) 'quote
)
159 (not (= ?\
( (aref to
0)))))
160 (eq (string-match " " to
(cdr pos
))
164 (setq to
(substring to end
)))))
165 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
)))
166 (setq to
(nreverse (delete "" (cons to list
))))
167 (replace-match-string-symbols to
)
168 (cons 'replace-eval-replacement
175 (defun query-replace-read-to (from prompt regexp-flag
)
176 "Query and return the `to' argument of a query-replace operation."
177 (query-replace-compile-replacement
179 (let* ((history-add-new-input nil
)
180 (to (read-from-minibuffer
181 (format "%s %s with: " prompt
(query-replace-descr from
))
183 query-replace-to-history-variable from t
)))
184 (add-to-history query-replace-to-history-variable to nil t
)
185 (setq query-replace-defaults
(cons from to
))
189 (defun query-replace-read-args (prompt regexp-flag
&optional noerror
)
191 (barf-if-buffer-read-only))
192 (let* ((from (query-replace-read-from prompt regexp-flag
))
193 (to (if (consp from
) (prog1 (cdr from
) (setq from
(car from
)))
194 (query-replace-read-to from prompt regexp-flag
))))
195 (list from to current-prefix-arg
)))
197 (defun query-replace (from-string to-string
&optional delimited start end
)
198 "Replace some occurrences of FROM-STRING with TO-STRING.
199 As each match is found, the user must type a character saying
200 what to do with it. For directions, type \\[help-command] at that time.
202 In Transient Mark mode, if the mark is active, operate on the contents
203 of the region. Otherwise, operate from point to the end of the buffer.
205 If `query-replace-interactive' is non-nil, the last incremental search
206 string is used as FROM-STRING--you don't have to specify it with the
209 Matching is independent of case if `case-fold-search' is non-nil and
210 FROM-STRING has no uppercase letters. Replacement transfers the case
211 pattern of the old text to the new text, if `case-replace' and
212 `case-fold-search' are non-nil and FROM-STRING has no uppercase
213 letters. \(Transferring the case pattern means that if the old text
214 matched is all caps, or capitalized, then its replacement is upcased
217 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
218 only matches surrounded by word boundaries.
219 Fourth and fifth arg START and END specify the region to operate on.
221 To customize possible responses, change the \"bindings\" in `query-replace-map'."
222 (interactive (let ((common
223 (query-replace-read-args
224 (if (and transient-mark-mode mark-active
)
225 "Query replace in region"
228 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
229 ;; These are done separately here
230 ;; so that command-history will record these expressions
231 ;; rather than the values they had this time.
232 (if (and transient-mark-mode mark-active
)
234 (if (and transient-mark-mode mark-active
)
236 (perform-replace from-string to-string t nil delimited nil nil start end
))
238 (define-key esc-map
"%" 'query-replace
)
240 (defun query-replace-regexp (regexp to-string
&optional delimited start end
)
241 "Replace some things after point matching REGEXP with TO-STRING.
242 As each match is found, the user must type a character saying
243 what to do with it. For directions, type \\[help-command] at that time.
245 In Transient Mark mode, if the mark is active, operate on the contents
246 of the region. Otherwise, operate from point to the end of the buffer.
248 If `query-replace-interactive' is non-nil, the last incremental search
249 regexp is used as REGEXP--you don't have to specify it with the
252 Matching is independent of case if `case-fold-search' is non-nil and
253 REGEXP has no uppercase letters. Replacement transfers the case
254 pattern of the old text to the new text, if `case-replace' and
255 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
256 \(Transferring the case pattern means that if the old text matched is
257 all caps, or capitalized, then its replacement is upcased or
260 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
261 only matches surrounded by word boundaries.
262 Fourth and fifth arg START and END specify the region to operate on.
264 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
265 and `\\=\\N' (where N is a digit) stands for
266 whatever what matched the Nth `\\(...\\)' in REGEXP.
267 `\\?' lets you edit the replacement text in the minibuffer
268 at the given position for each replacement.
270 In interactive calls, the replacement text can contain `\\,'
271 followed by a Lisp expression. Each
272 replacement evaluates that expression to compute the replacement
273 string. Inside of that expression, `\\&' is a string denoting the
274 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
275 for the whole or a partial match converted to a number with
276 `string-to-number', and `\\#' itself for the number of replacements
277 done so far (starting with zero).
279 If the replacement expression is a symbol, write a space after it
280 to terminate it. One space there, if any, will be discarded.
282 When using those Lisp features interactively in the replacement
283 text, TO-STRING is actually made a list instead of a string.
284 Use \\[repeat-complex-command] after this command for details."
287 (query-replace-read-args
288 (if (and transient-mark-mode mark-active
)
289 "Query replace regexp in region"
290 "Query replace regexp")
292 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
293 ;; These are done separately here
294 ;; so that command-history will record these expressions
295 ;; rather than the values they had this time.
296 (if (and transient-mark-mode mark-active
)
298 (if (and transient-mark-mode mark-active
)
300 (perform-replace regexp to-string t t delimited nil nil start end
))
302 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
304 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
305 "Replace some things after point matching REGEXP with the result of TO-EXPR.
306 As each match is found, the user must type a character saying
307 what to do with it. For directions, type \\[help-command] at that time.
309 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
310 reference `replace-count' to get the number of replacements already made.
311 If the result of TO-EXPR is not a string, it is converted to one using
312 `prin1-to-string' with the NOESCAPE argument (which see).
314 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
315 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
316 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
317 Use `\\#&' or `\\#N' if you want a number instead of a string.
318 In interactive use, `\\#' in itself stands for `replace-count'.
320 In Transient Mark mode, if the mark is active, operate on the contents
321 of the region. Otherwise, operate from point to the end of the buffer.
323 If `query-replace-interactive' is non-nil, the last incremental search
324 regexp is used as REGEXP--you don't have to specify it with the
327 Preserves case in each replacement if `case-replace' and `case-fold-search'
328 are non-nil and REGEXP has no uppercase letters.
330 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
331 only matches that are surrounded by word boundaries.
332 Fourth and fifth arg START and END specify the region to operate on."
335 (barf-if-buffer-read-only)
337 ;; Let-bind the history var to disable the "foo -> bar" default.
338 ;; Maybe we shouldn't disable this default, but for now I'll
339 ;; leave it off. --Stef
340 (let ((query-replace-to-history-variable nil
))
341 (query-replace-read-from "Query replace regexp" t
)))
342 (to (list (read-from-minibuffer
343 (format "Query replace regexp %s with eval: "
344 (query-replace-descr from
))
345 nil nil t query-replace-to-history-variable from t
))))
346 ;; We make TO a list because replace-match-string-symbols requires one,
347 ;; and the user might enter a single token.
348 (replace-match-string-symbols to
)
349 (list from
(car to
) current-prefix-arg
350 (if (and transient-mark-mode mark-active
)
352 (if (and transient-mark-mode mark-active
)
354 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
355 t
'literal delimited nil nil start end
))
357 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
358 "Replace some matches for REGEXP with various strings, in rotation.
359 The second argument TO-STRINGS contains the replacement strings,
360 separated by spaces. Third arg DELIMITED (prefix arg if interactive),
361 if non-nil, means replace only matches surrounded by word boundaries.
362 This command works like `query-replace-regexp' except that each
363 successive replacement uses the next successive replacement string,
364 wrapping around from the last such string to the first.
366 In Transient Mark mode, if the mark is active, operate on the contents
367 of the region. Otherwise, operate from point to the end of the buffer.
369 Non-interactively, TO-STRINGS may be a list of replacement strings.
371 If `query-replace-interactive' is non-nil, the last incremental search
372 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
374 A prefix argument N says to use each replacement string N times
375 before rotating to the next.
376 Fourth and fifth arg START and END specify the region to operate on."
378 (let* ((from (if query-replace-interactive
379 (car regexp-search-ring
)
380 (read-from-minibuffer "Map query replace (regexp): "
382 'query-replace-history nil t
)))
383 (to (read-from-minibuffer
384 (format "Query replace %s with (space-separated strings): "
385 (query-replace-descr from
))
387 'query-replace-history from t
)))
389 (and current-prefix-arg
390 (prefix-numeric-value current-prefix-arg
))
391 (if (and transient-mark-mode mark-active
)
393 (if (and transient-mark-mode mark-active
)
396 (if (listp to-strings
)
397 (setq replacements to-strings
)
398 (while (/= (length to-strings
) 0)
399 (if (string-match " " to-strings
)
402 (list (substring to-strings
0
403 (string-match " " to-strings
))))
404 to-strings
(substring to-strings
405 (1+ (string-match " " to-strings
))))
406 (setq replacements
(append replacements
(list to-strings
))
408 (perform-replace regexp replacements t t nil n nil start end
)))
410 (defun replace-string (from-string to-string
&optional delimited start end
)
411 "Replace occurrences of FROM-STRING with TO-STRING.
412 Preserve case in each match if `case-replace' and `case-fold-search'
413 are non-nil and FROM-STRING has no uppercase letters.
414 \(Preserving case means that if the string matched is all caps, or capitalized,
415 then its replacement is upcased or capitalized.)
417 In Transient Mark mode, if the mark is active, operate on the contents
418 of the region. Otherwise, operate from point to the end of the buffer.
420 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
421 only matches surrounded by word boundaries.
422 Fourth and fifth arg START and END specify the region to operate on.
424 If `query-replace-interactive' is non-nil, the last incremental search
425 string is used as FROM-STRING--you don't have to specify it with the
428 This function is usually the wrong thing to use in a Lisp program.
429 What you probably want is a loop like this:
430 (while (search-forward FROM-STRING nil t)
431 (replace-match TO-STRING nil t))
432 which will run faster and will not set the mark or print anything.
433 \(You may need a more complex loop if FROM-STRING can match the null string
434 and TO-STRING is also null.)"
437 (query-replace-read-args
438 (if (and transient-mark-mode mark-active
)
439 "Replace string in region"
442 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
443 (if (and transient-mark-mode mark-active
)
445 (if (and transient-mark-mode mark-active
)
447 (perform-replace from-string to-string nil nil delimited nil nil start end
))
449 (defun replace-regexp (regexp to-string
&optional delimited start end
)
450 "Replace things after point matching REGEXP with TO-STRING.
451 Preserve case in each match if `case-replace' and `case-fold-search'
452 are non-nil and REGEXP has no uppercase letters.
454 In Transient Mark mode, if the mark is active, operate on the contents
455 of the region. Otherwise, operate from point to the end of the buffer.
457 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
458 only matches surrounded by word boundaries.
459 Fourth and fifth arg START and END specify the region to operate on.
461 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
462 and `\\=\\N' (where N is a digit) stands for
463 whatever what matched the Nth `\\(...\\)' in REGEXP.
464 `\\?' lets you edit the replacement text in the minibuffer
465 at the given position for each replacement.
467 In interactive calls, the replacement text may contain `\\,'
468 followed by a Lisp expression used as part of the replacement
469 text. Inside of that expression, `\\&' is a string denoting the
470 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
471 numeric values from `string-to-number', and `\\#' itself for
472 `replace-count', the number of replacements occurred so far.
474 If your Lisp expression is an identifier and the next letter in
475 the replacement string would be interpreted as part of it, you
476 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
477 for this particular case you may also enter `\\#' in the
478 replacement text directly.
480 When using those Lisp features interactively in the replacement
481 text, TO-STRING is actually made a list instead of a string.
482 Use \\[repeat-complex-command] after this command for details.
484 If `query-replace-interactive' is non-nil, the last incremental search
485 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
487 This function is usually the wrong thing to use in a Lisp program.
488 What you probably want is a loop like this:
489 (while (re-search-forward REGEXP nil t)
490 (replace-match TO-STRING nil nil))
491 which will run faster and will not set the mark or print anything."
494 (query-replace-read-args
495 (if (and transient-mark-mode mark-active
)
496 "Replace regexp in region"
499 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
500 (if (and transient-mark-mode mark-active
)
502 (if (and transient-mark-mode mark-active
)
504 (perform-replace regexp to-string nil t delimited nil nil start end
))
507 (defvar regexp-history nil
508 "History list for some commands that read regular expressions.")
511 (defalias 'delete-non-matching-lines
'keep-lines
)
512 (defalias 'delete-matching-lines
'flush-lines
)
513 (defalias 'count-matches
'how-many
)
516 (defun keep-lines-read-args (prompt)
517 "Read arguments for `keep-lines' and friends.
518 Prompt for a regexp with PROMPT.
519 Value is a list, (REGEXP)."
520 (list (read-from-minibuffer prompt nil nil nil
521 'regexp-history nil t
)
524 (defun keep-lines (regexp &optional rstart rend interactive
)
525 "Delete all lines except those containing matches for REGEXP.
526 A match split across lines preserves all the lines it lies in.
527 When called from Lisp (and usually interactively as well, see below)
528 applies to all lines starting after point.
530 If REGEXP contains upper case characters (excluding those preceded by `\\'),
531 the matching is case-sensitive.
533 Second and third arg RSTART and REND specify the region to operate on.
534 This command operates on (the accessible part of) all lines whose
535 accessible part is entirely contained in the region determined by RSTART
536 and REND. (A newline ending a line counts as part of that line.)
538 Interactively, in Transient Mark mode when the mark is active, operate
539 on all lines whose accessible part is entirely contained in the region.
540 Otherwise, the command applies to all lines starting after point.
541 When calling this function from Lisp, you can pretend that it was
542 called interactively by passing a non-nil INTERACTIVE argument.
544 This function starts looking for the next match from the end of
545 the previous match. Hence, it ignores matches that overlap
546 a previously found match."
550 (barf-if-buffer-read-only)
551 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
554 (goto-char (min rstart rend
))
558 (goto-char (max rstart rend
))
559 (unless (or (bolp) (eobp))
562 (if (and interactive transient-mark-mode mark-active
)
563 (setq rstart
(region-beginning)
565 (goto-char (region-end))
566 (unless (or (bolp) (eobp))
570 rend
(point-max-marker)))
573 (or (bolp) (forward-line 1))
574 (let ((start (point))
575 (case-fold-search (and case-fold-search
576 (isearch-no-upper-case-p regexp t
))))
577 (while (< (point) rend
)
578 ;; Start is first char not preserved by previous match.
579 (if (not (re-search-forward regexp rend
'move
))
580 (delete-region start rend
)
581 (let ((end (save-excursion (goto-char (match-beginning 0))
584 ;; Now end is first char preserved by the new match.
586 (delete-region start end
))))
588 (setq start
(save-excursion (forward-line 1) (point)))
589 ;; If the match was empty, avoid matching again at same place.
590 (and (< (point) rend
)
591 (= (match-beginning 0) (match-end 0))
593 (set-marker rend nil
)
597 (defun flush-lines (regexp &optional rstart rend interactive
)
598 "Delete lines containing matches for REGEXP.
599 When called from Lisp (and usually when called interactively as
600 well, see below), applies to the part of the buffer after point.
601 The line point is in is deleted if and only if it contains a
602 match for regexp starting after point.
604 If REGEXP contains upper case characters (excluding those preceded by `\\'),
605 the matching is case-sensitive.
607 Second and third arg RSTART and REND specify the region to operate on.
608 Lines partially contained in this region are deleted if and only if
609 they contain a match entirely contained in it.
611 Interactively, in Transient Mark mode when the mark is active, operate
612 on the contents of the region. Otherwise, operate from point to the
613 end of (the accessible portion of) the buffer. When calling this function
614 from Lisp, you can pretend that it was called interactively by passing
615 a non-nil INTERACTIVE argument.
617 If a match is split across lines, all the lines it lies in are deleted.
618 They are deleted _before_ looking for the next match. Hence, a match
619 starting on the same line at which another match ended is ignored."
623 (barf-if-buffer-read-only)
624 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
627 (goto-char (min rstart rend
))
628 (setq rend
(copy-marker (max rstart rend
))))
629 (if (and interactive transient-mark-mode mark-active
)
630 (setq rstart
(region-beginning)
631 rend
(copy-marker (region-end)))
633 rend
(point-max-marker)))
635 (let ((case-fold-search (and case-fold-search
636 (isearch-no-upper-case-p regexp t
))))
638 (while (and (< (point) rend
)
639 (re-search-forward regexp rend t
))
640 (delete-region (save-excursion (goto-char (match-beginning 0))
643 (progn (forward-line 1) (point))))))
644 (set-marker rend nil
)
648 (defun how-many (regexp &optional rstart rend interactive
)
649 "Print and return number of matches for REGEXP following point.
650 When called from Lisp and INTERACTIVE is omitted or nil, just return
651 the number, do not print it; if INTERACTIVE is t, the function behaves
652 in all respects has if it had been called interactively.
654 If REGEXP contains upper case characters (excluding those preceded by `\\'),
655 the matching is case-sensitive.
657 Second and third arg RSTART and REND specify the region to operate on.
659 Interactively, in Transient Mark mode when the mark is active, operate
660 on the contents of the region. Otherwise, operate from point to the
661 end of (the accessible portion of) the buffer.
663 This function starts looking for the next match from the end of
664 the previous match. Hence, it ignores matches that overlap
665 a previously found match."
668 (keep-lines-read-args "How many matches for (regexp): "))
672 (goto-char (min rstart rend
))
673 (setq rend
(max rstart rend
)))
674 (if (and interactive transient-mark-mode mark-active
)
675 (setq rstart
(region-beginning)
682 (case-fold-search (and case-fold-search
683 (isearch-no-upper-case-p regexp t
))))
684 (while (and (< (point) rend
)
685 (progn (setq opoint
(point))
686 (re-search-forward regexp rend t
)))
687 (if (= opoint
(point))
689 (setq count
(1+ count
))))
690 (when interactive
(message "%d occurrence%s"
692 (if (= count
1) "" "s")))
696 (defvar occur-mode-map
697 (let ((map (make-sparse-keymap)))
698 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
699 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
700 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
701 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
702 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
703 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
704 (define-key map
"\M-n" 'occur-next
)
705 (define-key map
"\M-p" 'occur-prev
)
706 (define-key map
"r" 'occur-rename-buffer
)
707 (define-key map
"c" 'clone-buffer
)
708 (define-key map
"g" 'revert-buffer
)
709 (define-key map
"q" 'quit-window
)
710 (define-key map
"z" 'kill-this-buffer
)
711 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
713 "Keymap for `occur-mode'.")
715 (defvar occur-revert-arguments nil
716 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
717 See `occur-revert-function'.")
719 (defcustom occur-mode-hook
'(turn-on-font-lock)
720 "Hook run when entering Occur mode."
724 (defcustom occur-hook nil
725 "Hook run by Occur when there are any matches."
729 (put 'occur-mode
'mode-class
'special
)
731 "Major mode for output from \\[occur].
732 \\<occur-mode-map>Move point to one of the items in this buffer, then use
733 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
734 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
738 (kill-all-local-variables)
739 (use-local-map occur-mode-map
)
740 (setq major-mode
'occur-mode
)
741 (setq mode-name
"Occur")
742 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
743 (make-local-variable 'occur-revert-arguments
)
744 (add-hook 'change-major-mode-hook
'font-lock-defontify nil t
)
745 (setq next-error-function
'occur-next-error
)
746 (run-mode-hooks 'occur-mode-hook
))
748 (defun occur-revert-function (ignore1 ignore2
)
749 "Handle `revert-buffer' for Occur mode buffers."
750 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
752 (defun occur-mode-find-occurrence ()
753 (let ((pos (get-text-property (point) 'occur-target
)))
755 (error "No occurrence on this line"))
756 (unless (buffer-live-p (marker-buffer pos
))
757 (error "Buffer for this occurrence was killed"))
760 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
761 (defun occur-mode-goto-occurrence (&optional event
)
762 "Go to the occurrence the current line describes."
763 (interactive (list last-nonmenu-event
))
766 ;; Actually `event-end' works correctly with a nil argument as
767 ;; well, so we could dispense with this test, but let's not
768 ;; rely on this undocumented behavior.
769 (occur-mode-find-occurrence)
770 (with-current-buffer (window-buffer (posn-window (event-end event
)))
772 (goto-char (posn-point (event-end event
)))
773 (occur-mode-find-occurrence)))))
774 same-window-buffer-names
776 (pop-to-buffer (marker-buffer pos
))
779 (defun occur-mode-goto-occurrence-other-window ()
780 "Go to the occurrence the current line describes, in another window."
782 (let ((pos (occur-mode-find-occurrence)))
783 (switch-to-buffer-other-window (marker-buffer pos
))
786 (defun occur-mode-display-occurrence ()
787 "Display in another window the occurrence the current line describes."
789 (let ((pos (occur-mode-find-occurrence))
791 ;; Bind these to ensure `display-buffer' puts it in another window.
792 same-window-buffer-names
794 (setq window
(display-buffer (marker-buffer pos
)))
795 ;; This is the way to set point in the proper window.
796 (save-selected-window
797 (select-window window
)
800 (defun occur-find-match (n search message
)
801 (if (not n
) (setq n
1))
804 (setq r
(funcall search
(point) 'occur-match
))
806 (get-text-property r
'occur-match
)
807 (setq r
(funcall search r
'occur-match
)))
813 (defun occur-next (&optional n
)
814 "Move to the Nth (default 1) next match in an Occur mode buffer."
816 (occur-find-match n
#'next-single-property-change
"No more matches"))
818 (defun occur-prev (&optional n
)
819 "Move to the Nth (default 1) previous match in an Occur mode buffer."
821 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
823 (defun occur-next-error (&optional argp reset
)
824 "Move to the Nth (default 1) next match in an Occur mode buffer.
825 Compatibility function for \\[next-error] invocations."
827 ;; we need to run occur-find-match from within the Occur buffer
829 ;; Choose the buffer and make it current.
830 (if (next-error-buffer-p (current-buffer))
832 (next-error-find-buffer nil nil
834 (eq major-mode
'occur-mode
))))
836 (goto-char (cond (reset (point-min))
837 ((< argp
0) (line-beginning-position))
838 ((> argp
0) (line-end-position))
843 #'previous-single-property-change
844 #'next-single-property-change
)
846 ;; In case the *Occur* buffer is visible in a nonselected window.
847 (set-window-point (get-buffer-window (current-buffer)) (point))
848 (occur-mode-goto-occurrence)))
851 '((((class color
) (min-colors 88) (background light
))
852 :background
"yellow")
853 (((class color
) (min-colors 88) (background dark
))
854 :background
"RoyalBlue3")
855 (((class color
) (min-colors 8) (background light
))
856 :background
"yellow" :foreground
"black")
857 (((class color
) (min-colors 8) (background dark
))
858 :background
"blue" :foreground
"white")
859 (((type tty
) (class mono
))
861 (t :background
"gray"))
862 "Face used to highlight matches permanently."
866 (defcustom list-matching-lines-default-context-lines
0
867 "*Default number of context lines included around `list-matching-lines' matches.
868 A negative number means to include that many lines before the match.
869 A positive number means to include that many lines both before and after."
873 (defalias 'list-matching-lines
'occur
)
875 (defcustom list-matching-lines-face
'match
876 "*Face used by \\[list-matching-lines] to show the text that matches.
877 If the value is nil, don't highlight the matching portions specially."
881 (defcustom list-matching-lines-buffer-name-face
'underline
882 "*Face used by \\[list-matching-lines] to show the names of buffers.
883 If the value is nil, don't highlight the buffer names specially."
887 (defcustom occur-excluded-properties
888 '(read-only invisible intangible field mouse-face help-echo local-map keymap
889 yank-handler follow-link
)
890 "*Text properties to discard when copying lines to the *Occur* buffer.
891 The value should be a list of text properties to discard or t,
892 which means to discard all text properties."
893 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
897 (defun occur-accumulate-lines (count &optional keep-props
)
899 (let ((forwardp (> count
0))
901 (while (not (or (zerop count
)
905 (setq count
(+ count
(if forwardp -
1 1)))
906 (setq beg
(line-beginning-position)
907 end
(line-end-position))
908 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
909 (text-property-not-all beg end
'fontified t
))
910 (if (fboundp 'jit-lock-fontify-now
)
911 (jit-lock-fontify-now beg end
)))
913 (if (and keep-props
(not (eq occur-excluded-properties t
)))
914 (let ((str (buffer-substring beg end
)))
915 (remove-list-of-text-properties
916 0 (length str
) occur-excluded-properties str
)
918 (buffer-substring-no-properties beg end
))
920 (forward-line (if forwardp
1 -
1)))
923 (defun occur-read-primary-args ()
924 (list (let* ((default (car regexp-history
))
926 (read-from-minibuffer
928 (format "List lines matching regexp (default %s): "
929 (query-replace-descr default
))
930 "List lines matching regexp: ")
939 (when current-prefix-arg
940 (prefix-numeric-value current-prefix-arg
))))
942 (defun occur-rename-buffer (&optional unique-p interactive-p
)
943 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
944 Here `original-buffer-name' is the buffer name were Occur was originally run.
945 When given the prefix argument, or called non-interactively, the renaming
946 will not clobber the existing buffer(s) of that name, but use
947 `generate-new-buffer-name' instead. You can add this to `occur-hook'
948 if you always want a separate *Occur* buffer for each buffer where you
952 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
953 (rename-buffer (concat "*Occur: "
954 (mapconcat #'buffer-name
955 (car (cddr occur-revert-arguments
)) "/")
957 (or unique-p
(not interactive-p
)))))
959 (defun occur (regexp &optional nlines
)
960 "Show all lines in the current buffer containing a match for REGEXP.
961 This function can not handle matches that span more than one line.
963 Each line is displayed with NLINES lines before and after, or -NLINES
964 before if NLINES is negative.
965 NLINES defaults to `list-matching-lines-default-context-lines'.
966 Interactively it is the prefix arg.
968 The lines are shown in a buffer named `*Occur*'.
969 It serves as a menu to find any of the occurrences in this buffer.
970 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
972 If REGEXP contains upper case characters (excluding those preceded by `\\'),
973 the matching is case-sensitive."
974 (interactive (occur-read-primary-args))
975 (occur-1 regexp nlines
(list (current-buffer))))
977 (defun multi-occur (bufs regexp
&optional nlines
)
978 "Show all lines in buffers BUFS containing a match for REGEXP.
979 This function acts on multiple buffers; otherwise, it is exactly like
980 `occur'. When you invoke this command interactively, you must specify
981 the buffer names that you want, one by one."
984 (let* ((bufs (list (read-buffer "First buffer to search: "
985 (current-buffer) t
)))
987 (ido-ignore-item-temp-list bufs
))
988 (while (not (string-equal
989 (setq buf
(read-buffer
990 (if (eq read-buffer-function
'ido-read-buffer
)
991 "Next buffer to search (C-j to end): "
992 "Next buffer to search (RET to end): ")
995 (add-to-list 'bufs buf
)
996 (setq ido-ignore-item-temp-list bufs
))
997 (nreverse (mapcar #'get-buffer bufs
)))
998 (occur-read-primary-args)))
999 (occur-1 regexp nlines bufs
))
1001 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1002 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1003 Normally BUFREGEXP matches against each buffer's visited file name,
1004 but if you specify a prefix argument, it matches against the buffer name.
1005 See also `multi-occur'."
1008 (let* ((default (car regexp-history
))
1010 (read-from-minibuffer
1011 (if current-prefix-arg
1012 "List lines in buffers whose names match regexp: "
1013 "List lines in buffers whose filenames match regexp: ")
1018 (if (equal input
"")
1021 (occur-read-primary-args)))
1025 (mapcar (lambda (buf)
1027 (string-match bufregexp
1029 (and (buffer-file-name buf
)
1030 (string-match bufregexp
1031 (buffer-file-name buf
))))
1035 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1037 (setq buf-name
"*Occur*"))
1039 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1040 (when (buffer-live-p buf
) buf
))
1042 ;; Handle the case where one of the buffers we're searching is the
1043 ;; output buffer. Just rename it.
1044 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1045 (with-current-buffer (get-buffer buf-name
)
1048 ;; Now find or create the output buffer.
1049 ;; If we just renamed that buffer, we will make a new one here.
1050 (setq occur-buf
(get-buffer-create buf-name
))
1052 (with-current-buffer occur-buf
1054 (let ((inhibit-read-only t
)
1055 ;; Don't generate undo entries for creation of the initial contents.
1056 (buffer-undo-list t
))
1058 (let ((count (occur-engine
1059 regexp active-bufs occur-buf
1060 (or nlines list-matching-lines-default-context-lines
)
1061 (and case-fold-search
1062 (isearch-no-upper-case-p regexp t
))
1063 list-matching-lines-buffer-name-face
1064 nil list-matching-lines-face
1065 (not (eq occur-excluded-properties t
)))))
1066 (let* ((bufcount (length active-bufs
))
1067 (diff (- (length bufs
) bufcount
)))
1068 (message "Searched %d buffer%s%s; %s match%s for `%s'"
1069 bufcount
(if (= bufcount
1) "" "s")
1070 (if (zerop diff
) "" (format " (%d killed)" diff
))
1071 (if (zerop count
) "no" (format "%d" count
))
1072 (if (= count
1) "" "es")
1074 (setq occur-revert-arguments
(list regexp nlines bufs
))
1076 (kill-buffer occur-buf
)
1077 (display-buffer occur-buf
)
1078 (setq next-error-last-buffer occur-buf
)
1079 (setq buffer-read-only t
)
1080 (set-buffer-modified-p nil
)
1081 (run-hooks 'occur-hook
)))))))
1083 (defun occur-engine-add-prefix (lines)
1086 (concat " :" line
"\n"))
1089 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
1090 title-face prefix-face match-face keep-props
)
1091 (with-current-buffer out-buf
1092 (let ((globalcount 0)
1094 ;; Map over all the buffers
1095 (dolist (buf buffers
)
1096 (when (buffer-live-p buf
)
1097 (let ((matches 0) ;; count of matched lines
1098 (lines 1) ;; line count
1105 (inhibit-field-text-motion t
)
1106 (headerpt (with-current-buffer out-buf
(point))))
1107 (with-current-buffer buf
1109 ;; Set CODING only if the current buffer locally
1110 ;; binds buffer-file-coding-system.
1111 (not (local-variable-p 'buffer-file-coding-system
))
1112 (setq coding buffer-file-coding-system
))
1114 (goto-char (point-min)) ;; begin searching in the buffer
1116 (setq origpt
(point))
1117 (when (setq endpt
(re-search-forward regexp nil t
))
1118 (setq matches
(1+ matches
)) ;; increment match count
1119 (setq matchbeg
(match-beginning 0))
1120 (setq lines
(+ lines
(1- (count-lines origpt endpt
))))
1122 (goto-char matchbeg
)
1123 (setq begpt
(line-beginning-position)
1124 endpt
(line-end-position)))
1125 (setq marker
(make-marker))
1126 (set-marker marker matchbeg
)
1128 (if (boundp 'jit-lock-mode
) jit-lock-mode
)
1129 (text-property-not-all begpt endpt
'fontified t
))
1130 (if (fboundp 'jit-lock-fontify-now
)
1131 (jit-lock-fontify-now begpt endpt
)))
1132 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1134 (setq curstring
(buffer-substring begpt endpt
))
1135 (remove-list-of-text-properties
1136 0 (length curstring
) occur-excluded-properties curstring
))
1137 (setq curstring
(buffer-substring-no-properties begpt endpt
)))
1138 ;; Highlight the matches
1139 (let ((len (length curstring
))
1141 (while (and (< start len
)
1142 (string-match regexp curstring start
))
1143 (add-text-properties
1144 (match-beginning 0) (match-end 0)
1148 ;; Use `face' rather than `font-lock-face' here
1149 ;; so as to override faces copied from the buffer.
1150 `(face ,match-face
)))
1152 (setq start
(match-end 0))))
1153 ;; Generate the string to insert for this match
1156 ;; Using 7 digits aligns tabs properly.
1157 (apply #'propertize
(format "%7d:" lines
)
1160 `(font-lock-face prefix-face
))
1161 `(occur-prefix t mouse-face
(highlight)
1162 occur-target
,marker follow-link t
1163 help-echo
"mouse-2: go to this occurrence")))
1164 ;; We don't put `mouse-face' on the newline,
1165 ;; because that loses. And don't put it
1166 ;; on context lines to reduce flicker.
1167 (propertize curstring
'mouse-face
(list 'highlight
)
1168 'occur-target marker
1171 "mouse-2: go to this occurrence")
1172 ;; Add marker at eol, but no mouse props.
1173 (propertize "\n" 'occur-target marker
)))
1176 ;; The simple display style
1178 ;; The complex multi-line display
1179 ;; style. Generate a list of lines,
1180 ;; concatenate them all together.
1183 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ (abs nlines
))) keep-props
))))
1186 (occur-engine-add-prefix
1187 (cdr (occur-accumulate-lines (1+ nlines
) keep-props
)))))))))
1188 ;; Actually insert the match display data
1189 (with-current-buffer out-buf
1191 (end (progn (insert data
) (point))))
1192 (unless (= nlines
0)
1193 (insert "-------\n")))))
1197 (setq lines
(1+ lines
))
1198 ;; On to the next match...
1200 (goto-char (point-max))))))
1201 (when (not (zerop matches
)) ;; is the count zero?
1202 (setq globalcount
(+ globalcount matches
))
1203 (with-current-buffer out-buf
1204 (goto-char headerpt
)
1207 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1208 matches
(if (= matches
1) "" "es")
1209 regexp
(buffer-name buf
)))
1211 (add-text-properties beg end
1214 `(font-lock-face ,title-face
))
1215 `(occur-title ,buf
))))
1216 (goto-char (point-min)))))))
1218 ;; CODING is buffer-file-coding-system of the first buffer
1219 ;; that locally binds it. Let's use it also for the output
1221 (set-buffer-file-coding-system coding
))
1222 ;; Return the number of matches
1226 ;; It would be nice to use \\[...], but there is no reasonable way
1227 ;; to make that display both SPC and Y.
1228 (defconst query-replace-help
1229 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1230 RET or `q' to exit, Period to replace one match and exit,
1231 Comma to replace but not move point immediately,
1232 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1233 C-w to delete match and recursive edit,
1234 C-l to clear the screen, redisplay, and offer same replacement again,
1235 ! to replace all remaining matches with no more questions,
1236 ^ to move point back to previous match,
1237 E to edit the replacement string"
1238 "Help message while in `query-replace'.")
1240 (defvar query-replace-map
1241 (let ((map (make-sparse-keymap)))
1242 (define-key map
" " 'act
)
1243 (define-key map
"\d" 'skip
)
1244 (define-key map
[delete] 'skip)
1245 (define-key map [backspace] 'skip)
1246 (define-key map "y" 'act)
1247 (define-key map "n" 'skip)
1248 (define-key map "Y" 'act)
1249 (define-key map "N" 'skip)
1250 (define-key map "e" 'edit-replacement)
1251 (define-key map "E" 'edit-replacement)
1252 (define-key map "," 'act-and-show)
1253 (define-key map "q" 'exit)
1254 (define-key map "\r" 'exit)
1255 (define-key map [return] 'exit)
1256 (define-key map "." 'act-and-exit)
1257 (define-key map "\C-r" 'edit)
1258 (define-key map "\C-w" 'delete-and-edit)
1259 (define-key map "\C-l" 'recenter)
1260 (define-key map "!" 'automatic)
1261 (define-key map "^" 'backup)
1262 (define-key map "\C-h" 'help)
1263 (define-key map [f1] 'help)
1264 (define-key map [help] 'help)
1265 (define-key map "?" 'help)
1266 (define-key map "\C-g" 'quit)
1267 (define-key map "\C-]" 'quit)
1268 (define-key map "\e" 'exit-prefix)
1269 (define-key map [escape] 'exit-prefix)
1271 "Keymap that defines the responses to questions in `query-replace'.
1272 The \"bindings\" in this map are not commands; they are answers.
1273 The valid answers include `act', `skip', `act-and-show',
1274 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1275 `automatic', `backup', `exit-prefix', and `help'.")
1277 (defun replace-match-string-symbols (n)
1278 "Process a list (and any sub-lists), expanding certain symbols.
1280 N (match-string N) (where N is a string of digits)
1281 #N (string-to-number (match-string N))
1283 #& (string-to-number (match-string 0))
1286 Note that these symbols must be preceeded by a backslash in order to
1287 type them using Lisp syntax."
1291 (replace-match-string-symbols (car n))) ;Process sub-list
1293 (let ((name (symbol-name (car n))))
1295 ((string-match "^[0-9]+$" name)
1296 (setcar n (list 'match-string (string-to-number name))))
1297 ((string-match "^#[0-9]+$" name)
1298 (setcar n (list 'string-to-number
1300 (string-to-number (substring name 1))))))
1302 (setcar n '(match-string 0)))
1303 ((string= "#&" name)
1304 (setcar n '(string-to-number (match-string 0))))
1306 (setcar n 'replace-count))))))
1309 (defun replace-eval-replacement (expression replace-count)
1310 (let ((replacement (eval expression)))
1311 (if (stringp replacement)
1313 (prin1-to-string replacement t))))
1315 (defun replace-quote (replacement)
1316 "Quote a replacement string.
1317 This just doubles all backslashes in REPLACEMENT and
1318 returns the resulting string. If REPLACEMENT is not
1319 a string, it is first passed through `prin1-to-string'
1320 with the `noescape' argument set.
1322 `match-data' is preserved across the call."
1324 (replace-regexp-in-string "\\\\" "\\\\"
1325 (if (stringp replacement)
1327 (prin1-to-string replacement t))
1330 (defun replace-loop-through-replacements (data replace-count)
1331 ;; DATA is a vector contaning the following values:
1332 ;; 0 next-rotate-count
1334 ;; 2 next-replacement
1336 (if (= (aref data 0) replace-count)
1338 (aset data 0 (+ replace-count (aref data 1)))
1339 (let ((next (cdr (aref data 2))))
1340 (aset data 2 (if (consp next) next (aref data 3))))))
1341 (car (aref data 2)))
1343 (defun replace-match-data (integers reuse &optional new)
1344 "Like `match-data', but markers in REUSE get invalidated.
1345 If NEW is non-nil, it is set and returned instead of fresh data,
1346 but coerced to the correct value of INTEGERS."
1349 (set-match-data new)
1351 (eq (null integers) (markerp (car reuse)))
1353 (match-data integers reuse t)))
1355 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1356 "Make a replacement with `replace-match', editing `\\?'.
1357 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1358 check for `\\?' is made to save time. MATCH-DATA is used for the
1359 replacement. In case editing is done, it is changed to use markers.
1361 The return value is non-nil if there has been no `\\?' or NOEDIT was
1362 passed in. If LITERAL is set, no checking is done, anyway."
1363 (unless (or literal noedit)
1365 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1368 (read-string "Edit replacement string: "
1371 (replace-match "" t t newtext 3)
1372 (1+ (match-beginning 3)))
1375 nil match-data match-data))))
1377 (set-match-data match-data)
1378 (replace-match newtext fixedcase literal)
1381 (defun perform-replace (from-string replacements
1382 query-flag regexp-flag delimited-flag
1383 &optional repeat-count map start end)
1384 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1385 Don't use this in your own program unless you want to query and set the mark
1386 just as `query-replace' does. Instead, write a simple loop like this:
1388 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1389 (replace-match \"foobar\" nil nil))
1391 which will run faster and probably do exactly what you want. Please
1392 see the documentation of `replace-match' to find out how to simulate
1395 This function returns nil if and only if there were no matches to
1396 make, or the user didn't cancel the call."
1397 (or map (setq map query-replace-map))
1398 (and query-flag minibuffer-auto-raise
1399 (raise-frame (window-frame (minibuffer-window))))
1400 (let ((nocasify (not (and case-fold-search case-replace
1401 (string-equal from-string
1402 (downcase from-string)))))
1403 (case-fold-search (and case-fold-search
1404 (string-equal from-string
1405 (downcase from-string))))
1406 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1407 (search-function (if regexp-flag 're-search-forward 'search-forward))
1408 (search-string from-string)
1409 (real-match-data nil) ; the match data for the current match
1410 (next-replacement nil)
1411 ;; This is non-nil if we know there is nothing for the user
1412 ;; to edit in the replacement.
1417 (nonempty-match nil)
1419 ;; If non-nil, it is marker saying where in the buffer to stop.
1422 ;; Data for the next match. If a cons, it has the same format as
1423 ;; (match-data); otherwise it is t if a match is possible at point.
1429 (substitute-command-keys
1430 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1431 minibuffer-prompt-properties))))
1433 ;; If region is active, in Transient Mark mode, operate on region.
1435 (setq limit (copy-marker (max start end)))
1436 (goto-char (min start end))
1439 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1440 ;; containing a function and its first argument. The function is
1441 ;; called to generate each replacement like this:
1442 ;; (funcall (car replacements) (cdr replacements) replace-count)
1443 ;; It must return a string.
1445 ((stringp replacements)
1446 (setq next-replacement replacements
1448 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1449 (or repeat-count (setq repeat-count 1))
1450 (setq replacements (cons 'replace-loop-through-replacements
1451 (vector repeat-count repeat-count
1452 replacements replacements)))))
1455 (setq search-function 're-search-forward
1456 search-string (concat "\\b"
1457 (if regexp-flag from-string
1458 (regexp-quote from-string))
1460 (when query-replace-lazy-highlight
1461 (setq isearch-lazy-highlight-last-string nil))
1466 ;; Loop finding occurrences that perhaps should be replaced.
1467 (while (and keep-going
1468 (not (or (eobp) (and limit (>= (point) limit))))
1469 ;; Use the next match if it is already known;
1470 ;; otherwise, search for a match after moving forward
1471 ;; one char if progress is required.
1472 (setq real-match-data
1473 (cond ((consp match-again)
1474 (goto-char (nth 1 match-again))
1476 t real-match-data match-again))
1477 ;; MATCH-AGAIN non-nil means accept an
1481 (funcall search-function search-string
1483 ;; For speed, use only integers and
1484 ;; reuse the list used last time.
1485 (replace-match-data t real-match-data)))
1486 ((and (< (1+ (point)) (point-max))
1488 (< (1+ (point)) limit)))
1489 ;; If not accepting adjacent matches,
1490 ;; move one char to the right before
1491 ;; searching again. Undo the motion
1492 ;; if the search fails.
1493 (let ((opoint (point)))
1496 search-function search-string
1503 ;; Record whether the match is nonempty, to avoid an infinite loop
1504 ;; repeatedly matching the same empty string.
1505 (setq nonempty-match
1506 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1508 ;; If the match is empty, record that the next one can't be
1511 ;; Otherwise, if matching a regular expression, do the next
1512 ;; match now, since the replacement for this match may
1513 ;; affect whether the next match is adjacent to this one.
1514 ;; If that match is empty, don't use it.
1517 (or (not regexp-flag)
1518 (and (looking-at search-string)
1519 (let ((match (match-data)))
1520 (and (/= (nth 0 match) (nth 1 match))
1523 ;; Optionally ignore matches that have a read-only property.
1524 (unless (and query-replace-skip-read-only
1525 (text-property-not-all
1526 (nth 0 real-match-data) (nth 1 real-match-data)
1529 ;; Calculate the replacement string, if necessary.
1531 (set-match-data real-match-data)
1532 (setq next-replacement
1533 (funcall (car replacements) (cdr replacements)
1535 (if (not query-flag)
1536 (let ((inhibit-read-only
1537 query-replace-skip-read-only))
1538 (unless (or literal noedit)
1540 (nth 0 real-match-data) (nth 1 real-match-data)
1541 start end search-string
1542 (or delimited-flag regexp-flag) case-fold-search))
1544 (replace-match-maybe-edit
1545 next-replacement nocasify literal
1546 noedit real-match-data)
1547 replace-count (1+ replace-count)))
1549 (let (done replaced key def)
1550 ;; Loop reading commands until one of them sets done,
1551 ;; which means it has finished handling this
1552 ;; occurrence. Any command that sets `done' should
1553 ;; leave behind proper match data for the stack.
1554 ;; Commands not setting `done' need to adjust
1555 ;; `real-match-data'.
1557 (set-match-data real-match-data)
1559 (match-beginning 0) (match-end 0)
1560 start end search-string
1561 (or delimited-flag regexp-flag) case-fold-search)
1562 ;; Bind message-log-max so we don't fill up the message log
1563 ;; with a bunch of identical messages.
1564 (let ((message-log-max nil))
1566 (query-replace-descr from-string)
1567 (query-replace-descr next-replacement)))
1568 (setq key (read-event))
1569 ;; Necessary in case something happens during read-event
1570 ;; that clobbers the match data.
1571 (set-match-data real-match-data)
1572 (setq key (vector key))
1573 (setq def (lookup-key map key))
1574 ;; Restore the match data while we process the command.
1575 (cond ((eq def 'help)
1576 (with-output-to-temp-buffer "*Help*"
1578 (concat "Query replacing "
1579 (if regexp-flag "regexp " "")
1580 from-string " with "
1581 next-replacement ".\n\n"
1582 (substitute-command-keys
1583 query-replace-help)))
1584 (with-current-buffer standard-output
1587 (setq keep-going nil)
1591 (let ((elt (pop stack)))
1592 (goto-char (nth 0 elt))
1593 (setq replaced (nth 1 elt)
1598 (message "No previous match")
1599 (ding 'no-terminate)
1604 (replace-match-maybe-edit
1605 next-replacement nocasify literal
1606 noedit real-match-data)
1607 replace-count (1+ replace-count)))
1608 (setq done t replaced t))
1609 ((eq def 'act-and-exit)
1612 (replace-match-maybe-edit
1613 next-replacement nocasify literal
1614 noedit real-match-data)
1615 replace-count (1+ replace-count)))
1616 (setq keep-going nil)
1617 (setq done t replaced t))
1618 ((eq def 'act-and-show)
1621 (replace-match-maybe-edit
1622 next-replacement nocasify literal
1623 noedit real-match-data)
1624 replace-count (1+ replace-count)
1625 real-match-data (replace-match-data
1628 ((eq def 'automatic)
1631 (replace-match-maybe-edit
1632 next-replacement nocasify literal
1633 noedit real-match-data)
1634 replace-count (1+ replace-count)))
1635 (setq done t query-flag nil replaced t))
1641 (let ((opos (point-marker)))
1642 (setq real-match-data (replace-match-data
1645 (goto-char (match-beginning 0))
1647 (save-window-excursion
1650 (set-marker opos nil))
1651 ;; Before we make the replacement,
1652 ;; decide whether the search string
1653 ;; can match again just after this match.
1654 (if (and regexp-flag nonempty-match)
1655 (setq match-again (and (looking-at search-string)
1657 ;; Edit replacement.
1658 ((eq def 'edit-replacement)
1659 (setq real-match-data (replace-match-data
1663 (read-string "Edit replacement string: "
1667 (set-match-data real-match-data)
1669 (replace-match-maybe-edit
1670 next-replacement nocasify literal noedit
1675 ((eq def 'delete-and-edit)
1676 (replace-match "" t t)
1677 (setq real-match-data (replace-match-data
1678 nil real-match-data))
1679 (replace-dehighlight)
1680 (save-excursion (recursive-edit))
1682 ;; Note: we do not need to treat `exit-prefix'
1683 ;; specially here, since we reread
1684 ;; any unrecognized character.
1686 (setq this-command 'mode-exited)
1687 (setq keep-going nil)
1688 (setq unread-command-events
1689 (append (listify-key-sequence key)
1690 unread-command-events))
1692 (when query-replace-lazy-highlight
1693 ;; Force lazy rehighlighting only after replacements
1694 (if (not (memq def '(skip backup)))
1695 (setq isearch-lazy-highlight-last-string nil))))
1696 ;; Record previous position for ^ when we move on.
1697 ;; Change markers to numbers in the match data
1698 ;; since lots of markers slow down editing.
1699 (push (list (point) replaced
1700 ;;; If the replacement has already happened, all we need is the
1701 ;;; current match start and end. We could get this with a trivial
1703 ;;; (save-excursion (goto-char (match-beginning 0))
1704 ;;; (search-forward (match-string 0))
1706 ;;; if we really wanted to avoid manually constructing match data.
1707 ;;; Adding current-buffer is necessary so that match-data calls can
1708 ;;; return markers which are appropriate for editing.
1717 (replace-dehighlight))
1718 (or unread-command-events
1719 (message "Replaced %d occurrence%s"
1721 (if (= replace-count 1) "" "s")))
1722 (and keep-going stack)))
1724 (defvar replace-overlay nil)
1726 (defun replace-highlight (match-beg match-end range-beg range-end
1727 string regexp case-fold)
1728 (if query-replace-highlight
1730 (move-overlay replace-overlay match-beg match-end (current-buffer))
1731 (setq replace-overlay (make-overlay match-beg match-end))
1732 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
1733 (overlay-put replace-overlay 'face 'query-replace)))
1734 (if query-replace-lazy-highlight
1735 (let ((isearch-string string)
1736 (isearch-regexp regexp)
1737 (search-whitespace-regexp nil)
1738 (isearch-case-fold-search case-fold))
1739 (isearch-lazy-highlight-new-loop range-beg range-end))))
1741 (defun replace-dehighlight ()
1742 (when replace-overlay
1743 (delete-overlay replace-overlay))
1744 (when query-replace-lazy-highlight
1745 (lazy-highlight-cleanup lazy-highlight-cleanup)
1746 (setq isearch-lazy-highlight-last-string nil)))
1748 ;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1749 ;;; replace.el ends here