1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1992, 1994, 1996, 1997, 2000, 2001, 2002,
4 ;; 2003, 2004 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., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, 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-interactive nil
40 "Non-nil means `query-replace' uses the last search string.
41 That becomes the \"string to replace\".")
43 (defcustom query-replace-from-history-variable 'query-replace-history
44 "History list to use for the FROM argument of `query-replace' commands.
45 The value of this variable should be a symbol; that symbol
46 is used as a variable to hold a history list for the strings
47 or patterns to be replaced."
52 (defcustom query-replace-to-history-variable 'query-replace-history
53 "History list to use for the TO argument of `query-replace' commands.
54 The value of this variable should be a symbol; that symbol
55 is used as a variable to hold a history list for replacement
61 (defcustom query-replace-skip-read-only nil
62 "*Non-nil means `query-replace' and friends ignore read-only matches."
67 (defun query-replace-descr (string)
68 (mapconcat 'isearch-text-char-description string ""))
70 (defun query-replace-read-from (string regexp-flag)
71 "Query and return the `from' argument of a query-replace operation.
72 The return value can also be a pair (FROM . TO) indicating that the user
73 wants to replace FROM with TO."
74 (if query-replace-interactive
75 (car (if regexp-flag regexp-search-ring search-ring))
76 (let* ((lastfrom (car (symbol-value query-replace-from-history-variable)))
77 (lastto (car (symbol-value query-replace-to-history-variable)))
79 ;; The save-excursion here is in case the user marks and copies
80 ;; a region in order to specify the minibuffer input.
81 ;; That should not clobber the region for the query-replace itself.
83 (when (equal lastfrom lastto)
84 ;; Typically, this is because the two histlists are shared.
85 (setq lastfrom (cadr (symbol-value
86 query-replace-from-history-variable))))
88 (if (and lastto lastfrom)
89 (format "%s (default %s -> %s): " string
90 (query-replace-descr lastfrom)
91 (query-replace-descr lastto))
92 (format "%s: " string))
94 query-replace-from-history-variable
96 (if (and (zerop (length from)) lastto lastfrom)
98 (query-replace-compile-replacement lastto regexp-flag))
99 ;; Warn if user types \n or \t, but don't reject the input.
101 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
102 (let ((match (match-string 3 from)))
104 ((string= match "\\n")
105 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
106 ((string= match "\\t")
107 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
111 (defun query-replace-compile-replacement (to regexp-flag)
112 "Maybe convert a regexp replacement TO to Lisp.
113 Returns a list suitable for `perform-replace' if necessary,
114 the original string if not."
116 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
120 (setq pos (match-end 0))
121 (push (substring to 0 (- pos 2)) list)
122 (setq char (aref to (1- pos))
123 to (substring to pos))
125 (push '(number-to-string replace-count) list))
127 (setq pos (read-from-string to))
128 (push `(replace-quote ,(car pos)) list)
130 ;; Swallow a space after a symbol
131 ;; if there is a space.
132 (if (and (or (symbolp (car pos))
133 ;; Swallow a space after 'foo
134 ;; but not after (quote foo).
135 (and (eq (car-safe (car pos)) 'quote)
136 (not (= ?\( (aref to 0)))))
137 (eq (string-match " " to (cdr pos))
141 (setq to (substring to end)))))
142 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
143 (setq to (nreverse (delete "" (cons to list))))
144 (replace-match-string-symbols to)
145 (cons 'replace-eval-replacement
152 (defun query-replace-read-to (from string regexp-flag)
153 "Query and return the `to' argument of a query-replace operation."
154 (query-replace-compile-replacement
156 (read-from-minibuffer
157 (format "%s %s with: " string (query-replace-descr from))
159 query-replace-to-history-variable from t))
162 (defun query-replace-read-args (string regexp-flag &optional noerror)
164 (barf-if-buffer-read-only))
165 (let* ((from (query-replace-read-from string regexp-flag))
166 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
167 (query-replace-read-to from string regexp-flag))))
168 (list from to current-prefix-arg)))
170 (defun query-replace (from-string to-string &optional delimited start end)
171 "Replace some occurrences of FROM-STRING with TO-STRING.
172 As each match is found, the user must type a character saying
173 what to do with it. For directions, type \\[help-command] at that time.
175 In Transient Mark mode, if the mark is active, operate on the contents
176 of the region. Otherwise, operate from point to the end of the buffer.
178 If `query-replace-interactive' is non-nil, the last incremental search
179 string is used as FROM-STRING--you don't have to specify it with the
182 Matching is independent of case if `case-fold-search' is non-nil and
183 FROM-STRING has no uppercase letters. Replacement transfers the case
184 pattern of the old text to the new text, if `case-replace' and
185 `case-fold-search' are non-nil and FROM-STRING has no uppercase
186 letters. \(Transferring the case pattern means that if the old text
187 matched is all caps, or capitalized, then its replacement is upcased
190 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
191 only matches surrounded by word boundaries.
192 Fourth and fifth arg START and END specify the region to operate on.
194 To customize possible responses, change the \"bindings\" in `query-replace-map'."
195 (interactive (let ((common
196 (query-replace-read-args "Query replace" nil)))
197 (list (nth 0 common) (nth 1 common) (nth 2 common)
198 ;; These are done separately here
199 ;; so that command-history will record these expressions
200 ;; rather than the values they had this time.
201 (if (and transient-mark-mode mark-active)
203 (if (and transient-mark-mode mark-active)
205 (perform-replace from-string to-string t nil delimited nil nil start end))
207 (define-key esc-map "%" 'query-replace)
209 (defun query-replace-regexp (regexp to-string &optional delimited start end)
210 "Replace some things after point matching REGEXP with TO-STRING.
211 As each match is found, the user must type a character saying
212 what to do with it. For directions, type \\[help-command] at that time.
214 In Transient Mark mode, if the mark is active, operate on the contents
215 of the region. Otherwise, operate from point to the end of the buffer.
217 If `query-replace-interactive' is non-nil, the last incremental search
218 regexp is used as REGEXP--you don't have to specify it with the
221 Matching is independent of case if `case-fold-search' is non-nil and
222 REGEXP has no uppercase letters. Replacement transfers the case
223 pattern of the old text to the new text, if `case-replace' and
224 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
225 \(Transferring the case pattern means that if the old text matched is
226 all caps, or capitalized, then its replacement is upcased or
229 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
230 only matches surrounded by word boundaries.
231 Fourth and fifth arg START and END specify the region to operate on.
233 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
234 and `\\=\\N' (where N is a digit) stands for
235 whatever what matched the Nth `\\(...\\)' in REGEXP.
236 `\\?' lets you edit the replacement text in the minibuffer
237 at the given position for each replacement.
239 In interactive calls, the replacement text can contain `\\,'
240 followed by a Lisp expression. Each
241 replacement evaluates that expression to compute the replacement
242 string. Inside of that expression, `\\&' is a string denoting the
243 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
244 for the whole or a partial match converted to a number with
245 `string-to-number', and `\\#' itself for the number of replacements
246 done so far (starting with zero).
248 If the replacement expression is a symbol, write a space after it
249 to terminate it. One space there, if any, will be discarded.
251 When using those Lisp features interactively in the replacement
252 text, TO-STRING is actually made a list instead of a string.
253 Use \\[repeat-complex-command] after this command for details."
256 (query-replace-read-args "Query replace regexp" t)))
257 (list (nth 0 common) (nth 1 common) (nth 2 common)
258 ;; These are done separately here
259 ;; so that command-history will record these expressions
260 ;; rather than the values they had this time.
261 (if (and transient-mark-mode mark-active)
263 (if (and transient-mark-mode mark-active)
265 (perform-replace regexp to-string t t delimited nil nil start end))
267 (define-key esc-map [?\C-%] 'query-replace-regexp)
269 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
270 "Replace some things after point matching REGEXP with the result of TO-EXPR.
271 As each match is found, the user must type a character saying
272 what to do with it. For directions, type \\[help-command] at that time.
274 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
275 reference `replace-count' to get the number of replacements already made.
276 If the result of TO-EXPR is not a string, it is converted to one using
277 `prin1-to-string' with the NOESCAPE argument (which see).
279 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
280 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
281 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
282 Use `\\#&' or `\\#N' if you want a number instead of a string.
283 In interactive use, `\\#' in itself stands for `replace-count'.
285 In Transient Mark mode, if the mark is active, operate on the contents
286 of the region. Otherwise, operate from point to the end of the buffer.
288 If `query-replace-interactive' is non-nil, the last incremental search
289 regexp is used as REGEXP--you don't have to specify it with the
292 Preserves case in each replacement if `case-replace' and `case-fold-search'
293 are non-nil and REGEXP has no uppercase letters.
295 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
296 only matches that are surrounded by word boundaries.
297 Fourth and fifth arg START and END specify the region to operate on."
300 (barf-if-buffer-read-only)
302 ;; Let-bind the history var to disable the "foo -> bar" default.
303 ;; Maybe we shouldn't disable this default, but for now I'll
304 ;; leave it off. --Stef
305 (let ((query-replace-to-history-variable nil))
306 (query-replace-read-from "Query replace regexp" t)))
307 (to (list (read-from-minibuffer
308 (format "Query replace regexp %s with eval: "
309 (query-replace-descr from))
310 nil nil t query-replace-to-history-variable from t))))
311 ;; We make TO a list because replace-match-string-symbols requires one,
312 ;; and the user might enter a single token.
313 (replace-match-string-symbols to)
314 (list from (car to) current-prefix-arg
315 (if (and transient-mark-mode mark-active)
317 (if (and transient-mark-mode mark-active)
319 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
320 t 'literal delimited nil nil start end))
322 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
323 "Replace some matches for REGEXP with various strings, in rotation.
324 The second argument TO-STRINGS contains the replacement strings,
325 separated by spaces. Third arg DELIMITED (prefix arg if interactive),
326 if non-nil, means replace only matches surrounded by word boundaries.
327 This command works like `query-replace-regexp' except that each
328 successive replacement uses the next successive replacement string,
329 wrapping around from the last such string to the first.
331 In Transient Mark mode, if the mark is active, operate on the contents
332 of the region. Otherwise, operate from point to the end of the buffer.
334 Non-interactively, TO-STRINGS may be a list of replacement strings.
336 If `query-replace-interactive' is non-nil, the last incremental search
337 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
339 A prefix argument N says to use each replacement string N times
340 before rotating to the next.
341 Fourth and fifth arg START and END specify the region to operate on."
343 (let* ((from (if query-replace-interactive
344 (car regexp-search-ring)
345 (read-from-minibuffer "Map query replace (regexp): "
347 'query-replace-history nil t)))
348 (to (read-from-minibuffer
349 (format "Query replace %s with (space-separated strings): "
350 (query-replace-descr from))
352 'query-replace-history from t)))
354 (and current-prefix-arg
355 (prefix-numeric-value current-prefix-arg))
356 (if (and transient-mark-mode mark-active)
358 (if (and transient-mark-mode mark-active)
361 (if (listp to-strings)
362 (setq replacements to-strings)
363 (while (/= (length to-strings) 0)
364 (if (string-match " " to-strings)
367 (list (substring to-strings 0
368 (string-match " " to-strings))))
369 to-strings (substring to-strings
370 (1+ (string-match " " to-strings))))
371 (setq replacements (append replacements (list to-strings))
373 (perform-replace regexp replacements t t nil n nil start end)))
375 (defun replace-string (from-string to-string &optional delimited start end)
376 "Replace occurrences of FROM-STRING with TO-STRING.
377 Preserve case in each match if `case-replace' and `case-fold-search'
378 are non-nil and FROM-STRING has no uppercase letters.
379 \(Preserving case means that if the string matched is all caps, or capitalized,
380 then its replacement is upcased or capitalized.)
382 In Transient Mark mode, if the mark is active, operate on the contents
383 of the region. Otherwise, operate from point to the end of the buffer.
385 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
386 only matches surrounded by word boundaries.
387 Fourth and fifth arg START and END specify the region to operate on.
389 If `query-replace-interactive' is non-nil, the last incremental search
390 string is used as FROM-STRING--you don't have to specify it with the
393 This function is usually the wrong thing to use in a Lisp program.
394 What you probably want is a loop like this:
395 (while (search-forward FROM-STRING nil t)
396 (replace-match TO-STRING nil t))
397 which will run faster and will not set the mark or print anything.
398 \(You may need a more complex loop if FROM-STRING can match the null string
399 and TO-STRING is also null.)"
402 (query-replace-read-args "Replace string" nil)))
403 (list (nth 0 common) (nth 1 common) (nth 2 common)
404 (if (and transient-mark-mode mark-active)
406 (if (and transient-mark-mode mark-active)
408 (perform-replace from-string to-string nil nil delimited nil nil start end))
410 (defun replace-regexp (regexp to-string &optional delimited start end)
411 "Replace things after point matching REGEXP with TO-STRING.
412 Preserve case in each match if `case-replace' and `case-fold-search'
413 are non-nil and REGEXP has no uppercase letters.
415 In Transient Mark mode, if the mark is active, operate on the contents
416 of the region. Otherwise, operate from point to the end of the buffer.
418 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
419 only matches surrounded by word boundaries.
420 Fourth and fifth arg START and END specify the region to operate on.
422 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
423 and `\\=\\N' (where N is a digit) stands for
424 whatever what matched the Nth `\\(...\\)' in REGEXP.
425 `\\?' lets you edit the replacement text in the minibuffer
426 at the given position for each replacement.
428 In interactive calls, the replacement text may contain `\\,'
429 followed by a Lisp expression used as part of the replacement
430 text. Inside of that expression, `\\&' is a string denoting the
431 whole match, `\\N' a partial matches, `\\#&' and `\\#N' the
432 respective numeric values from `string-to-number', and `\\#'
433 itself for `replace-count', the number of replacements occured so
436 If your Lisp expression is an identifier and the next letter in
437 the replacement string would be interpreted as part of it, you
438 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
439 for this particular case you may also enter `\\#' in the
440 replacement text directly.
442 When using those Lisp features interactively in the replacement
443 text, TO-STRING is actually made a list instead of a string.
444 Use \\[repeat-complex-command] after this command for details.
446 If `query-replace-interactive' is non-nil, the last incremental search
447 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
449 This function is usually the wrong thing to use in a Lisp program.
450 What you probably want is a loop like this:
451 (while (re-search-forward REGEXP nil t)
452 (replace-match TO-STRING nil nil))
453 which will run faster and will not set the mark or print anything."
456 (query-replace-read-args "Replace regexp" t)))
457 (list (nth 0 common) (nth 1 common) (nth 2 common)
458 (if (and transient-mark-mode mark-active)
460 (if (and transient-mark-mode mark-active)
462 (perform-replace regexp to-string nil t delimited nil nil start end))
465 (defvar regexp-history nil
466 "History list for some commands that read regular expressions.")
469 (defalias 'delete-non-matching-lines 'keep-lines)
470 (defalias 'delete-matching-lines 'flush-lines)
471 (defalias 'count-matches 'how-many)
474 (defun keep-lines-read-args (prompt)
475 "Read arguments for `keep-lines' and friends.
476 Prompt for a regexp with PROMPT.
477 Value is a list, (REGEXP)."
478 (list (read-from-minibuffer prompt nil nil nil
479 'regexp-history nil t)))
481 (defun keep-lines (regexp &optional rstart rend)
482 "Delete all lines except those containing matches for REGEXP.
483 A match split across lines preserves all the lines it lies in.
484 Applies to all lines after point.
486 If REGEXP contains upper case characters (excluding those preceded by `\\'),
487 the matching is case-sensitive.
489 Second and third arg RSTART and REND specify the region to operate on.
491 Interactively, in Transient Mark mode when the mark is active, operate
492 on the contents of the region. Otherwise, operate from point to the
497 (barf-if-buffer-read-only)
498 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
501 (goto-char (min rstart rend))
502 (setq rend (copy-marker (max rstart rend))))
503 (if (and transient-mark-mode mark-active)
504 (setq rstart (region-beginning)
505 rend (copy-marker (region-end)))
507 rend (point-max-marker)))
510 (or (bolp) (forward-line 1))
511 (let ((start (point))
512 (case-fold-search (and case-fold-search
513 (isearch-no-upper-case-p regexp t))))
514 (while (< (point) rend)
515 ;; Start is first char not preserved by previous match.
516 (if (not (re-search-forward regexp rend 'move))
517 (delete-region start rend)
518 (let ((end (save-excursion (goto-char (match-beginning 0))
521 ;; Now end is first char preserved by the new match.
523 (delete-region start end))))
525 (setq start (save-excursion (forward-line 1) (point)))
526 ;; If the match was empty, avoid matching again at same place.
527 (and (< (point) rend)
528 (= (match-beginning 0) (match-end 0))
529 (forward-char 1))))))
532 (defun flush-lines (regexp &optional rstart rend)
533 "Delete lines containing matches for REGEXP.
534 If a match is split across lines, all the lines it lies in are deleted.
535 Applies to lines after point.
537 If REGEXP contains upper case characters (excluding those preceded by `\\'),
538 the matching is case-sensitive.
540 Second and third arg RSTART and REND specify the region to operate on.
542 Interactively, in Transient Mark mode when the mark is active, operate
543 on the contents of the region. Otherwise, operate from point to the
548 (barf-if-buffer-read-only)
549 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
552 (goto-char (min rstart rend))
553 (setq rend (copy-marker (max rstart rend))))
554 (if (and transient-mark-mode mark-active)
555 (setq rstart (region-beginning)
556 rend (copy-marker (region-end)))
558 rend (point-max-marker)))
560 (let ((case-fold-search (and case-fold-search
561 (isearch-no-upper-case-p regexp t))))
563 (while (and (< (point) rend)
564 (re-search-forward regexp rend t))
565 (delete-region (save-excursion (goto-char (match-beginning 0))
568 (progn (forward-line 1) (point)))))))
571 (defun how-many (regexp &optional rstart rend)
572 "Print number of matches for REGEXP following point.
574 If REGEXP contains upper case characters (excluding those preceded by `\\'),
575 the matching is case-sensitive.
577 Second and third arg RSTART and REND specify the region to operate on.
579 Interactively, in Transient Mark mode when the mark is active, operate
580 on the contents of the region. Otherwise, operate from point to the
584 (keep-lines-read-args "How many matches for (regexp): "))
587 (goto-char (min rstart rend))
588 (if (and transient-mark-mode mark-active)
589 (setq rstart (region-beginning)
590 rend (copy-marker (region-end)))
592 rend (point-max-marker)))
596 (case-fold-search (and case-fold-search
597 (isearch-no-upper-case-p regexp t))))
598 (while (and (< (point) rend)
599 (progn (setq opoint (point))
600 (re-search-forward regexp rend t)))
601 (if (= opoint (point))
603 (setq count (1+ count))))
604 (message "%d occurrences" count))))
607 (defvar occur-mode-map
608 (let ((map (make-sparse-keymap)))
609 (define-key map [mouse-2] 'occur-mode-mouse-goto)
610 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
611 (define-key map "\C-m" 'occur-mode-goto-occurrence)
612 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
613 (define-key map "\C-o" 'occur-mode-display-occurrence)
614 (define-key map "\M-n" 'occur-next)
615 (define-key map "\M-p" 'occur-prev)
616 (define-key map "r" 'occur-rename-buffer)
617 (define-key map "c" 'clone-buffer)
618 (define-key map "g" 'revert-buffer)
619 (define-key map "q" 'quit-window)
620 (define-key map "z" 'kill-this-buffer)
622 "Keymap for `occur-mode'.")
624 (defvar occur-revert-arguments nil
625 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
626 See `occur-revert-function'.")
628 (defcustom occur-mode-hook '(turn-on-font-lock)
629 "Hook run when entering Occur mode."
633 (defcustom occur-hook nil
634 "Hook run when `occur' is called."
638 (put 'occur-mode 'mode-class 'special)
640 "Major mode for output from \\[occur].
641 \\<occur-mode-map>Move point to one of the items in this buffer, then use
642 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
643 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
647 (kill-all-local-variables)
648 (use-local-map occur-mode-map)
649 (setq major-mode 'occur-mode)
650 (setq mode-name "Occur")
651 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
652 (make-local-variable 'occur-revert-arguments)
653 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
654 (setq next-error-function 'occur-next-error)
655 (run-hooks 'occur-mode-hook))
657 (defun occur-revert-function (ignore1 ignore2)
658 "Handle `revert-buffer' for Occur mode buffers."
659 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
661 (defun occur-mode-mouse-goto (event)
662 "In Occur mode, go to the occurrence whose line you click on."
666 (set-buffer (window-buffer (posn-window (event-end event))))
668 (goto-char (posn-point (event-end event)))
669 (setq pos (occur-mode-find-occurrence))))
670 (pop-to-buffer (marker-buffer pos))
673 (defun occur-mode-find-occurrence ()
674 (let ((pos (get-text-property (point) 'occur-target)))
676 (error "No occurrence on this line"))
677 (unless (buffer-live-p (marker-buffer pos))
678 (error "Buffer for this occurrence was killed"))
681 (defun occur-mode-goto-occurrence ()
682 "Go to the occurrence the current line describes."
684 (let ((pos (occur-mode-find-occurrence)))
685 (pop-to-buffer (marker-buffer pos))
688 (defun occur-mode-goto-occurrence-other-window ()
689 "Go to the occurrence the current line describes, in another window."
691 (let ((pos (occur-mode-find-occurrence)))
692 (switch-to-buffer-other-window (marker-buffer pos))
695 (defun occur-mode-display-occurrence ()
696 "Display in another window the occurrence the current line describes."
698 (let ((pos (occur-mode-find-occurrence))
700 ;; Bind these to ensure `display-buffer' puts it in another window.
701 same-window-buffer-names
703 (setq window (display-buffer (marker-buffer pos)))
704 ;; This is the way to set point in the proper window.
705 (save-selected-window
706 (select-window window)
709 (defun occur-find-match (n search message)
710 (if (not n) (setq n 1))
713 (setq r (funcall search (point) 'occur-match))
715 (get-text-property r 'occur-match)
716 (setq r (funcall search r 'occur-match)))
722 (defun occur-next (&optional n)
723 "Move to the Nth (default 1) next match in an Occur mode buffer."
725 (occur-find-match n #'next-single-property-change "No more matches"))
727 (defun occur-prev (&optional n)
728 "Move to the Nth (default 1) previous match in an Occur mode buffer."
730 (occur-find-match n #'previous-single-property-change "No earlier matches"))
732 (defun occur-next-error (&optional argp reset)
733 "Move to the Nth (default 1) next match in an Occur mode buffer.
734 Compatibility function for \\[next-error] invocations."
737 (occur-find-match 0 #'next-single-property-change "No first match"))
739 (prefix-numeric-value argp)
740 (if (> 0 (prefix-numeric-value argp))
741 #'previous-single-property-change
742 #'next-single-property-change)
744 ;; In case the *Occur* buffer is visible in a nonselected window.
745 (set-window-point (get-buffer-window (current-buffer)) (point))
746 (occur-mode-goto-occurrence))
749 (defcustom list-matching-lines-default-context-lines 0
750 "*Default number of context lines included around `list-matching-lines' matches.
751 A negative number means to include that many lines before the match.
752 A positive number means to include that many lines both before and after."
756 (defalias 'list-matching-lines 'occur)
758 (defcustom list-matching-lines-face 'bold
759 "*Face used by \\[list-matching-lines] to show the text that matches.
760 If the value is nil, don't highlight the matching portions specially."
764 (defcustom list-matching-lines-buffer-name-face 'underline
765 "*Face used by \\[list-matching-lines] to show the names of buffers.
766 If the value is nil, don't highlight the buffer names specially."
770 (defun occur-accumulate-lines (count &optional no-props)
772 (let ((forwardp (> count 0))
774 (while (not (or (zerop count)
778 (setq count (+ count (if forwardp -1 1)))
780 (funcall (if no-props
781 #'buffer-substring-no-properties
783 (line-beginning-position)
786 (forward-line (if forwardp 1 -1)))
789 (defun occur-read-primary-args ()
790 (list (let* ((default (car regexp-history))
792 (read-from-minibuffer
794 (format "List lines matching regexp (default `%s'): "
795 (query-replace-descr default))
796 "List lines matching regexp: ")
805 (when current-prefix-arg
806 (prefix-numeric-value current-prefix-arg))))
808 (defun occur-rename-buffer (&optional unique-p)
809 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
810 Here `original-buffer-name' is the buffer name were occur was originally run.
811 When given the prefix argument, the renaming will not clobber the existing
812 buffer(s) of that name, but use `generate-new-buffer-name' instead.
813 You can add this to `occur-hook' if you always want a separate *Occur*
814 buffer for each buffer where you invoke `occur'."
817 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
818 (rename-buffer (concat "*Occur: "
819 (mapconcat #'buffer-name
820 (car (cddr occur-revert-arguments)) "/")
824 (defun occur (regexp &optional nlines)
825 "Show all lines in the current buffer containing a match for REGEXP.
827 If a match spreads across multiple lines, all those lines are shown.
829 Each line is displayed with NLINES lines before and after, or -NLINES
830 before if NLINES is negative.
831 NLINES defaults to `list-matching-lines-default-context-lines'.
832 Interactively it is the prefix arg.
834 The lines are shown in a buffer named `*Occur*'.
835 It serves as a menu to find any of the occurrences in this buffer.
836 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
838 If REGEXP contains upper case characters (excluding those preceded by `\\'),
839 the matching is case-sensitive."
840 (interactive (occur-read-primary-args))
841 (occur-1 regexp nlines (list (current-buffer))))
843 (defun multi-occur (bufs regexp &optional nlines)
844 "Show all lines in buffers BUFS containing a match for REGEXP.
845 This function acts on multiple buffers; otherwise, it is exactly like
849 (let* ((bufs (list (read-buffer "First buffer to search: "
850 (current-buffer) t)))
852 (ido-ignore-item-temp-list bufs))
853 (while (not (string-equal
854 (setq buf (read-buffer
855 (if (eq read-buffer-function 'ido-read-buffer)
856 "Next buffer to search (C-j to end): "
857 "Next buffer to search (RET to end): ")
860 (add-to-list 'bufs buf)
861 (setq ido-ignore-item-temp-list bufs))
862 (nreverse (mapcar #'get-buffer bufs)))
863 (occur-read-primary-args)))
864 (occur-1 regexp nlines bufs))
866 (defun multi-occur-by-filename-regexp (bufregexp regexp &optional nlines)
867 "Show all lines matching REGEXP in buffers named by BUFREGEXP.
868 See also `multi-occur'."
871 (let* ((default (car regexp-history))
873 (read-from-minibuffer
874 "List lines in buffers whose filename matches regexp: "
882 (occur-read-primary-args)))
884 (occur-1 regexp nlines
886 (mapcar (lambda (buf)
887 (when (and (buffer-file-name buf)
888 (string-match bufregexp
889 (buffer-file-name buf)))
893 (defun occur-1 (regexp nlines bufs &optional buf-name)
895 (setq buf-name "*Occur*"))
896 (let ((occur-buf (get-buffer-create buf-name))
898 (active-bufs (delq nil (mapcar #'(lambda (buf)
899 (when (buffer-live-p buf) buf))
901 ;; Handle the case where one of the buffers we're searching is the
902 ;; *Occur* buffer itself.
903 (when (memq occur-buf bufs)
904 (setq occur-buf (with-current-buffer occur-buf
905 (clone-buffer "*Occur-temp*"))
907 (with-current-buffer occur-buf
908 (setq buffer-read-only nil)
911 (let ((count (occur-engine
912 regexp active-bufs occur-buf
913 (or nlines list-matching-lines-default-context-lines)
914 (and case-fold-search
915 (isearch-no-upper-case-p regexp t))
916 list-matching-lines-buffer-name-face
917 nil list-matching-lines-face nil)))
918 (let* ((bufcount (length active-bufs))
919 (diff (- (length bufs) bufcount)))
920 (message "Searched %d buffer%s%s; %s match%s for `%s'"
921 bufcount (if (= bufcount 1) "" "s")
922 (if (zerop diff) "" (format " (%d killed)" diff))
923 (if (zerop count) "no" (format "%d" count))
924 (if (= count 1) "" "es")
926 ;; If we had to make a temporary buffer, make it the *Occur*
929 (with-current-buffer (get-buffer buf-name)
930 (kill-buffer (current-buffer)))
931 (rename-buffer buf-name))
932 (setq occur-revert-arguments (list regexp nlines bufs)
936 (display-buffer occur-buf)
937 (setq next-error-last-buffer occur-buf))
938 (kill-buffer occur-buf)))
939 (run-hooks 'occur-hook))))
941 (defun occur-engine-add-prefix (lines)
944 (concat " :" line "\n"))
947 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
948 title-face prefix-face match-face keep-props)
949 (with-current-buffer out-buf
950 (setq buffer-read-only nil)
951 (let ((globalcount 0)
953 ;; Map over all the buffers
954 (dolist (buf buffers)
955 (when (buffer-live-p buf)
956 (let ((matches 0) ;; count of matched lines
957 (lines 1) ;; line count
964 (headerpt (with-current-buffer out-buf (point))))
968 ;; Set CODING only if the current buffer locally
969 ;; binds buffer-file-coding-system.
970 (not (local-variable-p 'buffer-file-coding-system))
971 (setq coding buffer-file-coding-system))
973 (goto-char (point-min)) ;; begin searching in the buffer
975 (setq origpt (point))
976 (when (setq endpt (re-search-forward regexp nil t))
977 (setq matches (1+ matches)) ;; increment match count
978 (setq matchbeg (match-beginning 0))
979 (setq begpt (save-excursion
981 (line-beginning-position)))
982 (setq lines (+ lines (1- (count-lines origpt endpt))))
983 (setq marker (make-marker))
984 (set-marker marker matchbeg)
985 (setq curstring (buffer-substring begpt
986 (line-end-position)))
987 ;; Depropertize the string, and maybe
988 ;; highlight the matches
989 (let ((len (length curstring))
992 (set-text-properties 0 len nil curstring))
993 (while (and (< start len)
994 (string-match regexp curstring start))
995 (add-text-properties (match-beginning 0)
1000 `(font-lock-face ,match-face)))
1002 (setq start (match-end 0))))
1003 ;; Generate the string to insert for this match
1006 ;; Using 7 digits aligns tabs properly.
1007 (apply #'propertize (format "%7d:" lines)
1010 `(font-lock-face prefix-face))
1016 ;; The simple display style
1018 ;; The complex multi-line display
1019 ;; style. Generate a list of lines,
1020 ;; concatenate them all together.
1023 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ (abs nlines))) keep-props))))
1026 (occur-engine-add-prefix
1027 (cdr (occur-accumulate-lines (1+ nlines) keep-props)))))))))
1028 ;; Actually insert the match display data
1029 (with-current-buffer out-buf
1031 (end (progn (insert data) (point))))
1032 (unless (= nlines 0)
1033 (insert "-------\n"))
1034 (add-text-properties
1036 `(occur-target ,marker help-echo "mouse-2: go to this occurrence"))
1037 ;; We don't put `mouse-face' on the newline,
1038 ;; because that loses.
1039 (add-text-properties beg (1- end) '(mouse-face highlight)))))
1043 (setq lines (1+ lines))
1044 ;; On to the next match...
1046 (goto-char (point-max))))))
1047 (when (not (zerop matches)) ;; is the count zero?
1048 (setq globalcount (+ globalcount matches))
1049 (with-current-buffer out-buf
1050 (goto-char headerpt)
1053 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1054 matches (if (= matches 1) "" "es")
1055 regexp (buffer-name buf)))
1057 (add-text-properties beg end
1060 `(font-lock-face ,title-face))
1061 `(occur-title ,buf))))
1062 (goto-char (point-min)))))))
1064 ;; CODING is buffer-file-coding-system of the first buffer
1065 ;; that locally binds it. Let's use it also for the output
1067 (set-buffer-file-coding-system coding))
1068 ;; Return the number of matches
1072 ;; It would be nice to use \\[...], but there is no reasonable way
1073 ;; to make that display both SPC and Y.
1074 (defconst query-replace-help
1075 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1076 RET or `q' to exit, Period to replace one match and exit,
1077 Comma to replace but not move point immediately,
1078 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1079 C-w to delete match and recursive edit,
1080 C-l to clear the screen, redisplay, and offer same replacement again,
1081 ! to replace all remaining matches with no more questions,
1082 ^ to move point back to previous match,
1083 E to edit the replacement string"
1084 "Help message while in `query-replace'.")
1086 (defvar query-replace-map (make-sparse-keymap)
1087 "Keymap that defines the responses to questions in `query-replace'.
1088 The \"bindings\" in this map are not commands; they are answers.
1089 The valid answers include `act', `skip', `act-and-show',
1090 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1091 `automatic', `backup', `exit-prefix', and `help'.")
1093 (define-key query-replace-map " " 'act)
1094 (define-key query-replace-map "\d" 'skip)
1095 (define-key query-replace-map [delete] 'skip)
1096 (define-key query-replace-map [backspace] 'skip)
1097 (define-key query-replace-map "y" 'act)
1098 (define-key query-replace-map "n" 'skip)
1099 (define-key query-replace-map "Y" 'act)
1100 (define-key query-replace-map "N" 'skip)
1101 (define-key query-replace-map "e" 'edit-replacement)
1102 (define-key query-replace-map "E" 'edit-replacement)
1103 (define-key query-replace-map "," 'act-and-show)
1104 (define-key query-replace-map "q" 'exit)
1105 (define-key query-replace-map "\r" 'exit)
1106 (define-key query-replace-map [return] 'exit)
1107 (define-key query-replace-map "." 'act-and-exit)
1108 (define-key query-replace-map "\C-r" 'edit)
1109 (define-key query-replace-map "\C-w" 'delete-and-edit)
1110 (define-key query-replace-map "\C-l" 'recenter)
1111 (define-key query-replace-map "!" 'automatic)
1112 (define-key query-replace-map "^" 'backup)
1113 (define-key query-replace-map "\C-h" 'help)
1114 (define-key query-replace-map [f1] 'help)
1115 (define-key query-replace-map [help] 'help)
1116 (define-key query-replace-map "?" 'help)
1117 (define-key query-replace-map "\C-g" 'quit)
1118 (define-key query-replace-map "\C-]" 'quit)
1119 (define-key query-replace-map "\e" 'exit-prefix)
1120 (define-key query-replace-map [escape] 'exit-prefix)
1122 (defun replace-match-string-symbols (n)
1123 "Process a list (and any sub-lists), expanding certain symbols.
1125 N (match-string N) (where N is a string of digits)
1126 #N (string-to-number (match-string N))
1128 #& (string-to-number (match-string 0))
1131 Note that these symbols must be preceeded by a backslash in order to
1136 (replace-match-string-symbols (car n))) ;Process sub-list
1138 (let ((name (symbol-name (car n))))
1140 ((string-match "^[0-9]+$" name)
1141 (setcar n (list 'match-string (string-to-number name))))
1142 ((string-match "^#[0-9]+$" name)
1143 (setcar n (list 'string-to-number
1145 (string-to-number (substring name 1))))))
1147 (setcar n '(match-string 0)))
1148 ((string= "#&" name)
1149 (setcar n '(string-to-number (match-string 0))))
1151 (setcar n 'replace-count))))))
1154 (defun replace-eval-replacement (expression replace-count)
1155 (let ((replacement (eval expression)))
1156 (if (stringp replacement)
1158 (prin1-to-string replacement t))))
1160 (defun replace-quote (replacement)
1161 "Quote a replacement string.
1162 This just doubles all backslashes in REPLACEMENT and
1163 returns the resulting string. If REPLACEMENT is not
1164 a string, it is first passed through `prin1-to-string'
1165 with the `noescape' argument set.
1167 `match-data' is preserved across the call."
1169 (replace-regexp-in-string "\\\\" "\\\\"
1170 (if (stringp replacement)
1172 (prin1-to-string replacement t))
1175 (defun replace-loop-through-replacements (data replace-count)
1176 ;; DATA is a vector contaning the following values:
1177 ;; 0 next-rotate-count
1179 ;; 2 next-replacement
1181 (if (= (aref data 0) replace-count)
1183 (aset data 0 (+ replace-count (aref data 1)))
1184 (let ((next (cdr (aref data 2))))
1185 (aset data 2 (if (consp next) next (aref data 3))))))
1186 (car (aref data 2)))
1188 (defun replace-match-data (integers reuse &optional new)
1189 "Like `match-data', but markers in REUSE get invalidated.
1190 If NEW is non-NIL, it is set and returned instead of fresh data,
1191 but coerced to the correct value of INTEGERS."
1194 (set-match-data new)
1196 (eq (null integers) (markerp (car reuse)))
1198 (match-data integers
1201 (if (markerp (car reuse))
1202 (set-marker (car reuse) nil))
1203 (setq reuse (cdr reuse)))))))
1205 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1206 "Make a replacement with `replace-match', editing `\\?'.
1207 NEXTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1208 check for `\\?' is made to save time. MATCH-DATA is used for the
1209 replacement. In case editing is done, it is changed to use markers.
1211 The return value is non-NIL if there has been no `\\?' or NOEDIT was
1212 passed in. If LITERAL is set, no checking is done, anyway."
1213 (unless (or literal noedit)
1215 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1218 (read-input "Edit replacement string: "
1221 (replace-match "" t t newtext 3)
1222 (1+ (match-beginning 3)))
1225 nil match-data match-data))))
1227 (set-match-data match-data)
1228 (replace-match newtext fixedcase literal)
1231 (defun perform-replace (from-string replacements
1232 query-flag regexp-flag delimited-flag
1233 &optional repeat-count map start end)
1234 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1235 Don't use this in your own program unless you want to query and set the mark
1236 just as `query-replace' does. Instead, write a simple loop like this:
1238 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1239 (replace-match \"foobar\" nil nil))
1241 which will run faster and probably do exactly what you want. Please
1242 see the documentation of `replace-match' to find out how to simulate
1245 This function returns nil if and only if there were no matches to
1246 make, or the user didn't cancel the call."
1247 (or map (setq map query-replace-map))
1248 (and query-flag minibuffer-auto-raise
1249 (raise-frame (window-frame (minibuffer-window))))
1250 (let ((nocasify (not (and case-fold-search case-replace
1251 (string-equal from-string
1252 (downcase from-string)))))
1253 (case-fold-search (and case-fold-search
1254 (string-equal from-string
1255 (downcase from-string))))
1256 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1257 (search-function (if regexp-flag 're-search-forward 'search-forward))
1258 (search-string from-string)
1259 (real-match-data nil) ; the match data for the current match
1260 (next-replacement nil)
1265 (nonempty-match nil)
1267 ;; If non-nil, it is marker saying where in the buffer to stop.
1270 ;; Data for the next match. If a cons, it has the same format as
1271 ;; (match-data); otherwise it is t if a match is possible at point.
1276 (substitute-command-keys
1277 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
1279 ;; If region is active, in Transient Mark mode, operate on region.
1281 (setq limit (copy-marker (max start end)))
1282 (goto-char (min start end))
1285 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1286 ;; containing a function and its first argument. The function is
1287 ;; called to generate each replacement like this:
1288 ;; (funcall (car replacements) (cdr replacements) replace-count)
1289 ;; It must return a string.
1291 ((stringp replacements)
1292 (setq next-replacement replacements
1294 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1295 (or repeat-count (setq repeat-count 1))
1296 (setq replacements (cons 'replace-loop-through-replacements
1297 (vector repeat-count repeat-count
1298 replacements replacements)))))
1301 (setq search-function 're-search-forward
1302 search-string (concat "\\b"
1303 (if regexp-flag from-string
1304 (regexp-quote from-string))
1309 ;; Loop finding occurrences that perhaps should be replaced.
1310 (while (and keep-going
1311 (not (or (eobp) (and limit (>= (point) limit))))
1312 ;; Use the next match if it is already known;
1313 ;; otherwise, search for a match after moving forward
1314 ;; one char if progress is required.
1315 (setq real-match-data
1316 (if (consp match-again)
1317 (progn (goto-char (nth 1 match-again))
1318 (replace-match-data t
1321 (and (or match-again
1322 ;; MATCH-AGAIN non-nil means we
1323 ;; accept an adjacent match. If
1324 ;; we don't, move one char to the
1325 ;; right. This takes us a
1326 ;; character too far at the end,
1327 ;; but this is undone after the
1332 (and limit (>= (point) limit))))))
1333 (funcall search-function search-string limit t)
1334 ;; For speed, use only integers and
1335 ;; reuse the list used last time.
1336 (replace-match-data t real-match-data)))))
1337 ;; Optionally ignore matches that have a read-only property.
1338 (unless (and query-replace-skip-read-only
1339 (text-property-not-all
1340 (match-beginning 0) (match-end 0)
1343 ;; Record whether the match is nonempty, to avoid an infinite loop
1344 ;; repeatedly matching the same empty string.
1345 (setq nonempty-match
1346 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1348 ;; If the match is empty, record that the next one can't be
1351 ;; Otherwise, if matching a regular expression, do the next
1352 ;; match now, since the replacement for this match may
1353 ;; affect whether the next match is adjacent to this one.
1354 ;; If that match is empty, don't use it.
1357 (or (not regexp-flag)
1358 (and (looking-at search-string)
1359 (let ((match (match-data)))
1360 (and (/= (nth 0 match) (nth 1 match))
1363 ;; Calculate the replacement string, if necessary.
1365 (set-match-data real-match-data)
1366 (setq next-replacement
1367 (funcall (car replacements) (cdr replacements)
1370 (if (not query-flag)
1371 (let ((inhibit-read-only
1372 query-replace-skip-read-only))
1374 (replace-highlight (nth 0 real-match-data)
1375 (nth 1 real-match-data)))
1377 (replace-match-maybe-edit
1378 next-replacement nocasify literal
1379 noedit real-match-data)
1380 replace-count (1+ replace-count)))
1382 (let (done replaced key def)
1383 ;; Loop reading commands until one of them sets done,
1384 ;; which means it has finished handling this
1385 ;; occurrence. Any command that sets `done' should
1386 ;; leave behind proper match data for the stack.
1387 ;; Commands not setting `done' need to adjust
1388 ;; `real-match-data'.
1390 (set-match-data real-match-data)
1391 (replace-highlight (match-beginning 0) (match-end 0))
1392 ;; Bind message-log-max so we don't fill up the message log
1393 ;; with a bunch of identical messages.
1394 (let ((message-log-max nil))
1395 (message message from-string next-replacement))
1396 (setq key (read-event))
1397 ;; Necessary in case something happens during read-event
1398 ;; that clobbers the match data.
1399 (set-match-data real-match-data)
1400 (setq key (vector key))
1401 (setq def (lookup-key map key))
1402 ;; Restore the match data while we process the command.
1403 (cond ((eq def 'help)
1404 (with-output-to-temp-buffer "*Help*"
1406 (concat "Query replacing "
1407 (if regexp-flag "regexp " "")
1408 from-string " with "
1409 next-replacement ".\n\n"
1410 (substitute-command-keys
1411 query-replace-help)))
1412 (with-current-buffer standard-output
1415 (setq keep-going nil)
1419 (let ((elt (pop stack)))
1420 (goto-char (nth 0 elt))
1421 (setq replaced (nth 1 elt)
1426 (message "No previous match")
1427 (ding 'no-terminate)
1432 (replace-match-maybe-edit
1433 next-replacement nocasify literal
1434 noedit real-match-data)
1435 replace-count (1+ replace-count)))
1436 (setq done t replaced t))
1437 ((eq def 'act-and-exit)
1440 (replace-match-maybe-edit
1441 next-replacement nocasify literal
1442 noedit real-match-data)
1443 replace-count (1+ replace-count)))
1444 (setq keep-going nil)
1445 (setq done t replaced t))
1446 ((eq def 'act-and-show)
1449 (replace-match-maybe-edit
1450 next-replacement nocasify literal
1451 noedit real-match-data)
1452 replace-count (1+ replace-count)
1453 real-match-data (replace-match-data
1456 ((eq def 'automatic)
1459 (replace-match-maybe-edit
1460 next-replacement nocasify literal
1461 noedit real-match-data)
1462 replace-count (1+ replace-count)))
1463 (setq done t query-flag nil replaced t))
1469 (let ((opos (point-marker)))
1470 (setq real-match-data (replace-match-data
1473 (goto-char (match-beginning 0))
1475 (save-window-excursion
1478 (set-marker opos nil))
1479 ;; Before we make the replacement,
1480 ;; decide whether the search string
1481 ;; can match again just after this match.
1482 (if (and regexp-flag nonempty-match)
1483 (setq match-again (and (looking-at search-string)
1485 ;; Edit replacement.
1486 ((eq def 'edit-replacement)
1487 (setq real-match-data (replace-match-data
1491 (read-input "Edit replacement string: "
1495 (set-match-data real-match-data)
1497 (replace-match-maybe-edit
1498 next-replacement nocasify literal noedit
1503 ((eq def 'delete-and-edit)
1504 (replace-match "" t t)
1505 (setq real-match-data (replace-match-data
1506 nil real-match-data))
1507 (replace-dehighlight)
1508 (save-excursion (recursive-edit))
1510 ;; Note: we do not need to treat `exit-prefix'
1511 ;; specially here, since we reread
1512 ;; any unrecognized character.
1514 (setq this-command 'mode-exited)
1515 (setq keep-going nil)
1516 (setq unread-command-events
1517 (append (listify-key-sequence key)
1518 unread-command-events))
1520 ;; Record previous position for ^ when we move on.
1521 ;; Change markers to numbers in the match data
1522 ;; since lots of markers slow down editing.
1523 (push (list (point) replaced
1524 ;;; If the replacement has already happened, all we need is the
1525 ;;; current match start and end. We could get this with a trivial
1527 ;;; (save-excursion (goto-char (match-beginning 0))
1528 ;;; (search-forward (match-string 0))
1530 ;;; if we really wanted to avoid manually constructing match data.
1531 ;;; Adding current-buffer is necessary so that match-data calls can
1532 ;;; return markers which are appropriate for editing.
1541 ;; The code preventing adjacent regexp matches in the condition
1542 ;; of the while-loop above will haven taken us one character
1543 ;; beyond the last replacement. Undo that.
1544 (when (and regexp-flag (not match-again) (> replace-count 0))
1547 (replace-dehighlight))
1548 (or unread-command-events
1549 (message "Replaced %d occurrence%s"
1551 (if (= replace-count 1) "" "s")))
1552 (and keep-going stack)))
1554 (defcustom query-replace-highlight t
1555 "*Non-nil means to highlight words during query replacement."
1559 (defvar replace-overlay nil)
1561 (defun replace-dehighlight ()
1562 (and replace-overlay
1564 (delete-overlay replace-overlay)
1565 (setq replace-overlay nil))))
1567 (defun replace-highlight (start end)
1568 (and query-replace-highlight
1570 (move-overlay replace-overlay start end (current-buffer))
1571 (setq replace-overlay (make-overlay start end))
1572 (overlay-put replace-overlay 'face
1573 (if (facep 'query-replace)
1574 'query-replace 'region)))))
1576 ;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1577 ;;; replace.el ends here