1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1992, 1994, 1996, 1997, 2000, 2001,
4 ;; 2002, 2003, 2004, 2005 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-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 (defcustom query-replace-highlight t
68 "*Non-nil means to highlight matches during query replacement."
72 (defcustom query-replace-lazy-highlight t
73 "*Controls the lazy-highlighting during query replacements.
74 When non-nil, all text in the buffer matching the current match
75 is highlighted lazily using isearch lazy highlighting (see
76 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
78 :group
'lazy-highlight
82 (defface query-replace
83 '((t (:inherit isearch
)))
84 "Face for highlighting query replacement matches."
88 (defun query-replace-descr (string)
89 (mapconcat 'isearch-text-char-description string
""))
91 (defun query-replace-read-from (prompt regexp-flag
)
92 "Query and return the `from' argument of a query-replace operation.
93 The return value can also be a pair (FROM . TO) indicating that the user
94 wants to replace FROM with TO."
95 (if query-replace-interactive
96 (car (if regexp-flag regexp-search-ring search-ring
))
97 (let* ((lastfrom (car (symbol-value query-replace-from-history-variable
)))
98 (lastto (car (symbol-value query-replace-to-history-variable
)))
100 ;; The save-excursion here is in case the user marks and copies
101 ;; a region in order to specify the minibuffer input.
102 ;; That should not clobber the region for the query-replace itself.
104 (when (equal lastfrom lastto
)
105 ;; Typically, this is because the two histlists are shared.
106 (setq lastfrom
(cadr (symbol-value
107 query-replace-from-history-variable
))))
108 (read-from-minibuffer
109 (if (and lastto lastfrom
)
110 (format "%s (default %s -> %s): " prompt
111 (query-replace-descr lastfrom
)
112 (query-replace-descr lastto
))
113 (format "%s: " prompt
))
115 query-replace-from-history-variable
117 (if (and (zerop (length from
)) lastto lastfrom
)
119 (set query-replace-from-history-variable
120 (cdr (symbol-value query-replace-from-history-variable
)))
122 (query-replace-compile-replacement lastto regexp-flag
)))
123 ;; Warn if user types \n or \t, but don't reject the input.
125 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
126 (let ((match (match-string 3 from
)))
128 ((string= match
"\\n")
129 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
130 ((string= match
"\\t")
131 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
135 (defun query-replace-compile-replacement (to regexp-flag
)
136 "Maybe convert a regexp replacement TO to Lisp.
137 Returns a list suitable for `perform-replace' if necessary,
138 the original string if not."
140 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
))
144 (setq pos
(match-end 0))
145 (push (substring to
0 (- pos
2)) list
)
146 (setq char
(aref to
(1- pos
))
147 to
(substring to pos
))
149 (push '(number-to-string replace-count
) list
))
151 (setq pos
(read-from-string to
))
152 (push `(replace-quote ,(car pos
)) list
)
154 ;; Swallow a space after a symbol
155 ;; if there is a space.
156 (if (and (or (symbolp (car pos
))
157 ;; Swallow a space after 'foo
158 ;; but not after (quote foo).
159 (and (eq (car-safe (car pos
)) 'quote
)
160 (not (= ?\
( (aref to
0)))))
161 (eq (string-match " " to
(cdr pos
))
165 (setq to
(substring to end
)))))
166 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
)))
167 (setq to
(nreverse (delete "" (cons to list
))))
168 (replace-match-string-symbols to
)
169 (cons 'replace-eval-replacement
176 (defun query-replace-read-to (from prompt regexp-flag
)
177 "Query and return the `to' argument of a query-replace operation."
178 (query-replace-compile-replacement
180 (read-from-minibuffer
181 (format "%s %s with: " prompt
(query-replace-descr from
))
183 query-replace-to-history-variable from t t
))
186 (defun query-replace-read-args (prompt regexp-flag
&optional noerror
)
188 (barf-if-buffer-read-only))
189 (let* ((from (query-replace-read-from prompt regexp-flag
))
190 (to (if (consp from
) (prog1 (cdr from
) (setq from
(car from
)))
191 (query-replace-read-to from prompt regexp-flag
))))
192 (list from to current-prefix-arg
)))
194 (defun query-replace (from-string to-string
&optional delimited start end
)
195 "Replace some occurrences of FROM-STRING with TO-STRING.
196 As each match is found, the user must type a character saying
197 what to do with it. For directions, type \\[help-command] at that time.
199 In Transient Mark mode, if the mark is active, operate on the contents
200 of the region. Otherwise, operate from point to the end of the buffer.
202 If `query-replace-interactive' is non-nil, the last incremental search
203 string is used as FROM-STRING--you don't have to specify it with the
206 Matching is independent of case if `case-fold-search' is non-nil and
207 FROM-STRING has no uppercase letters. Replacement transfers the case
208 pattern of the old text to the new text, if `case-replace' and
209 `case-fold-search' are non-nil and FROM-STRING has no uppercase
210 letters. \(Transferring the case pattern means that if the old text
211 matched is all caps, or capitalized, then its replacement is upcased
214 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
215 only matches surrounded by word boundaries.
216 Fourth and fifth arg START and END specify the region to operate on.
218 To customize possible responses, change the \"bindings\" in `query-replace-map'."
219 (interactive (let ((common
220 (query-replace-read-args
221 (if (and transient-mark-mode mark-active
)
222 "Query replace in region"
225 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
226 ;; These are done separately here
227 ;; so that command-history will record these expressions
228 ;; rather than the values they had this time.
229 (if (and transient-mark-mode mark-active
)
231 (if (and transient-mark-mode mark-active
)
233 (perform-replace from-string to-string t nil delimited nil nil start end
))
235 (define-key esc-map
"%" 'query-replace
)
237 (defun query-replace-regexp (regexp to-string
&optional delimited start end
)
238 "Replace some things after point matching REGEXP with TO-STRING.
239 As each match is found, the user must type a character saying
240 what to do with it. For directions, type \\[help-command] at that time.
242 In Transient Mark mode, if the mark is active, operate on the contents
243 of the region. Otherwise, operate from point to the end of the buffer.
245 If `query-replace-interactive' is non-nil, the last incremental search
246 regexp is used as REGEXP--you don't have to specify it with the
249 Matching is independent of case if `case-fold-search' is non-nil and
250 REGEXP has no uppercase letters. Replacement transfers the case
251 pattern of the old text to the new text, if `case-replace' and
252 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
253 \(Transferring the case pattern means that if the old text matched is
254 all caps, or capitalized, then its replacement is upcased or
257 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
258 only matches surrounded by word boundaries.
259 Fourth and fifth arg START and END specify the region to operate on.
261 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
262 and `\\=\\N' (where N is a digit) stands for
263 whatever what matched the Nth `\\(...\\)' in REGEXP.
264 `\\?' lets you edit the replacement text in the minibuffer
265 at the given position for each replacement.
267 In interactive calls, the replacement text can contain `\\,'
268 followed by a Lisp expression. Each
269 replacement evaluates that expression to compute the replacement
270 string. Inside of that expression, `\\&' is a string denoting the
271 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
272 for the whole or a partial match converted to a number with
273 `string-to-number', and `\\#' itself for the number of replacements
274 done so far (starting with zero).
276 If the replacement expression is a symbol, write a space after it
277 to terminate it. One space there, if any, will be discarded.
279 When using those Lisp features interactively in the replacement
280 text, TO-STRING is actually made a list instead of a string.
281 Use \\[repeat-complex-command] after this command for details."
284 (query-replace-read-args
285 (if (and transient-mark-mode mark-active
)
286 "Query replace regexp in region"
287 "Query replace regexp")
289 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
290 ;; These are done separately here
291 ;; so that command-history will record these expressions
292 ;; rather than the values they had this time.
293 (if (and transient-mark-mode mark-active
)
295 (if (and transient-mark-mode mark-active
)
297 (perform-replace regexp to-string t t delimited nil nil start end
))
299 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
301 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
302 "Replace some things after point matching REGEXP with the result of TO-EXPR.
303 As each match is found, the user must type a character saying
304 what to do with it. For directions, type \\[help-command] at that time.
306 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
307 reference `replace-count' to get the number of replacements already made.
308 If the result of TO-EXPR is not a string, it is converted to one using
309 `prin1-to-string' with the NOESCAPE argument (which see).
311 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
312 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
313 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
314 Use `\\#&' or `\\#N' if you want a number instead of a string.
315 In interactive use, `\\#' in itself stands for `replace-count'.
317 In Transient Mark mode, if the mark is active, operate on the contents
318 of the region. Otherwise, operate from point to the end of the buffer.
320 If `query-replace-interactive' is non-nil, the last incremental search
321 regexp is used as REGEXP--you don't have to specify it with the
324 Preserves case in each replacement if `case-replace' and `case-fold-search'
325 are non-nil and REGEXP has no uppercase letters.
327 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
328 only matches that are surrounded by word boundaries.
329 Fourth and fifth arg START and END specify the region to operate on."
332 (barf-if-buffer-read-only)
334 ;; Let-bind the history var to disable the "foo -> bar" default.
335 ;; Maybe we shouldn't disable this default, but for now I'll
336 ;; leave it off. --Stef
337 (let ((query-replace-to-history-variable nil
))
338 (query-replace-read-from "Query replace regexp" t
)))
339 (to (list (read-from-minibuffer
340 (format "Query replace regexp %s with eval: "
341 (query-replace-descr from
))
342 nil nil t query-replace-to-history-variable from t
))))
343 ;; We make TO a list because replace-match-string-symbols requires one,
344 ;; and the user might enter a single token.
345 (replace-match-string-symbols to
)
346 (list from
(car to
) current-prefix-arg
347 (if (and transient-mark-mode mark-active
)
349 (if (and transient-mark-mode mark-active
)
351 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
352 t
'literal delimited nil nil start end
))
354 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
355 "Replace some matches for REGEXP with various strings, in rotation.
356 The second argument TO-STRINGS contains the replacement strings,
357 separated by spaces. Third arg DELIMITED (prefix arg if interactive),
358 if non-nil, means replace only matches surrounded by word boundaries.
359 This command works like `query-replace-regexp' except that each
360 successive replacement uses the next successive replacement string,
361 wrapping around from the last such string to the first.
363 In Transient Mark mode, if the mark is active, operate on the contents
364 of the region. Otherwise, operate from point to the end of the buffer.
366 Non-interactively, TO-STRINGS may be a list of replacement strings.
368 If `query-replace-interactive' is non-nil, the last incremental search
369 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
371 A prefix argument N says to use each replacement string N times
372 before rotating to the next.
373 Fourth and fifth arg START and END specify the region to operate on."
375 (let* ((from (if query-replace-interactive
376 (car regexp-search-ring
)
377 (read-from-minibuffer "Map query replace (regexp): "
379 'query-replace-history nil t
)))
380 (to (read-from-minibuffer
381 (format "Query replace %s with (space-separated strings): "
382 (query-replace-descr from
))
384 'query-replace-history from t
)))
386 (and current-prefix-arg
387 (prefix-numeric-value current-prefix-arg
))
388 (if (and transient-mark-mode mark-active
)
390 (if (and transient-mark-mode mark-active
)
393 (if (listp to-strings
)
394 (setq replacements to-strings
)
395 (while (/= (length to-strings
) 0)
396 (if (string-match " " to-strings
)
399 (list (substring to-strings
0
400 (string-match " " to-strings
))))
401 to-strings
(substring to-strings
402 (1+ (string-match " " to-strings
))))
403 (setq replacements
(append replacements
(list to-strings
))
405 (perform-replace regexp replacements t t nil n nil start end
)))
407 (defun replace-string (from-string to-string
&optional delimited start end
)
408 "Replace occurrences of FROM-STRING with TO-STRING.
409 Preserve case in each match if `case-replace' and `case-fold-search'
410 are non-nil and FROM-STRING has no uppercase letters.
411 \(Preserving case means that if the string matched is all caps, or capitalized,
412 then its replacement is upcased or capitalized.)
414 In Transient Mark mode, if the mark is active, operate on the contents
415 of the region. Otherwise, operate from point to the end of the buffer.
417 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
418 only matches surrounded by word boundaries.
419 Fourth and fifth arg START and END specify the region to operate on.
421 If `query-replace-interactive' is non-nil, the last incremental search
422 string is used as FROM-STRING--you don't have to specify it with the
425 This function is usually the wrong thing to use in a Lisp program.
426 What you probably want is a loop like this:
427 (while (search-forward FROM-STRING nil t)
428 (replace-match TO-STRING nil t))
429 which will run faster and will not set the mark or print anything.
430 \(You may need a more complex loop if FROM-STRING can match the null string
431 and TO-STRING is also null.)"
434 (query-replace-read-args
435 (if (and transient-mark-mode mark-active
)
436 "Replace string in region"
439 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
440 (if (and transient-mark-mode mark-active
)
442 (if (and transient-mark-mode mark-active
)
444 (perform-replace from-string to-string nil nil delimited nil nil start end
))
446 (defun replace-regexp (regexp to-string
&optional delimited start end
)
447 "Replace things after point matching REGEXP with TO-STRING.
448 Preserve case in each match if `case-replace' and `case-fold-search'
449 are non-nil and REGEXP has no uppercase letters.
451 In Transient Mark mode, if the mark is active, operate on the contents
452 of the region. Otherwise, operate from point to the end of the buffer.
454 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
455 only matches surrounded by word boundaries.
456 Fourth and fifth arg START and END specify the region to operate on.
458 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
459 and `\\=\\N' (where N is a digit) stands for
460 whatever what matched the Nth `\\(...\\)' in REGEXP.
461 `\\?' lets you edit the replacement text in the minibuffer
462 at the given position for each replacement.
464 In interactive calls, the replacement text may contain `\\,'
465 followed by a Lisp expression used as part of the replacement
466 text. Inside of that expression, `\\&' is a string denoting the
467 whole match, `\\N' a partial matches, `\\#&' and `\\#N' the
468 respective numeric values from `string-to-number', and `\\#'
469 itself for `replace-count', the number of replacements occured so
472 If your Lisp expression is an identifier and the next letter in
473 the replacement string would be interpreted as part of it, you
474 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
475 for this particular case you may also enter `\\#' in the
476 replacement text directly.
478 When using those Lisp features interactively in the replacement
479 text, TO-STRING is actually made a list instead of a string.
480 Use \\[repeat-complex-command] after this command for details.
482 If `query-replace-interactive' is non-nil, the last incremental search
483 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
485 This function is usually the wrong thing to use in a Lisp program.
486 What you probably want is a loop like this:
487 (while (re-search-forward REGEXP nil t)
488 (replace-match TO-STRING nil nil))
489 which will run faster and will not set the mark or print anything."
492 (query-replace-read-args
493 (if (and transient-mark-mode mark-active
)
494 "Replace regexp in region"
497 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
498 (if (and transient-mark-mode mark-active
)
500 (if (and transient-mark-mode mark-active
)
502 (perform-replace regexp to-string nil t delimited nil nil start end
))
505 (defvar regexp-history nil
506 "History list for some commands that read regular expressions.")
509 (defalias 'delete-non-matching-lines
'keep-lines
)
510 (defalias 'delete-matching-lines
'flush-lines
)
511 (defalias 'count-matches
'how-many
)
514 (defun keep-lines-read-args (prompt)
515 "Read arguments for `keep-lines' and friends.
516 Prompt for a regexp with PROMPT.
517 Value is a list, (REGEXP)."
518 (list (read-from-minibuffer prompt nil nil nil
519 'regexp-history nil t
)
522 (defun keep-lines (regexp &optional rstart rend interactive
)
523 "Delete all lines except those containing matches for REGEXP.
524 A match split across lines preserves all the lines it lies in.
525 When called from Lisp (and usually interactively as well, see below)
526 applies to all lines starting after point.
528 If REGEXP contains upper case characters (excluding those preceded by `\\'),
529 the matching is case-sensitive.
531 Second and third arg RSTART and REND specify the region to operate on.
532 This command operates on (the accessible part of) all lines whose
533 accessible part is entirely contained in the region determined by RSTART
534 and REND. (A newline ending a line counts as part of that line.)
536 Interactively, in Transient Mark mode when the mark is active, operate
537 on all lines whose accessible part is entirely contained in the region.
538 Otherwise, the command applies to all lines starting after point.
539 When calling this function from Lisp, you can pretend that it was
540 called interactively by passing a non-nil INTERACTIVE argument.
542 This function starts looking for the next match from the end of
543 the previous match. Hence, it ignores matches that overlap
544 a previously found match."
548 (barf-if-buffer-read-only)
549 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
552 (goto-char (min rstart rend
))
556 (goto-char (max rstart rend
))
557 (unless (or (bolp) (eobp))
560 (if (and interactive transient-mark-mode mark-active
)
561 (setq rstart
(region-beginning)
563 (goto-char (region-end))
564 (unless (or (bolp) (eobp))
568 rend
(point-max-marker)))
571 (or (bolp) (forward-line 1))
572 (let ((start (point))
573 (case-fold-search (and case-fold-search
574 (isearch-no-upper-case-p regexp t
))))
575 (while (< (point) rend
)
576 ;; Start is first char not preserved by previous match.
577 (if (not (re-search-forward regexp rend
'move
))
578 (delete-region start rend
)
579 (let ((end (save-excursion (goto-char (match-beginning 0))
582 ;; Now end is first char preserved by the new match.
584 (delete-region start end
))))
586 (setq start
(save-excursion (forward-line 1) (point)))
587 ;; If the match was empty, avoid matching again at same place.
588 (and (< (point) rend
)
589 (= (match-beginning 0) (match-end 0))
591 (set-marker rend nil
)
595 (defun flush-lines (regexp &optional rstart rend interactive
)
596 "Delete lines containing matches for REGEXP.
597 When called from Lisp (and usually when called interactively as
598 well, see below), applies to the part of the buffer after point.
599 The line point is in is deleted if and only if it contains a
600 match for regexp starting after point.
602 If REGEXP contains upper case characters (excluding those preceded by `\\'),
603 the matching is case-sensitive.
605 Second and third arg RSTART and REND specify the region to operate on.
606 Lines partially contained in this region are deleted if and only if
607 they contain a match entirely contained in it.
609 Interactively, in Transient Mark mode when the mark is active, operate
610 on the contents of the region. Otherwise, operate from point to the
611 end of (the accessible portion of) the buffer. When calling this function
612 from Lisp, you can pretend that it was called interactively by passing
613 a non-nil INTERACTIVE argument.
615 If a match is split across lines, all the lines it lies in are deleted.
616 They are deleted _before_ looking for the next match. Hence, a match
617 starting on the same line at which another match ended is ignored."
621 (barf-if-buffer-read-only)
622 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
625 (goto-char (min rstart rend
))
626 (setq rend
(copy-marker (max rstart rend
))))
627 (if (and interactive transient-mark-mode mark-active
)
628 (setq rstart
(region-beginning)
629 rend
(copy-marker (region-end)))
631 rend
(point-max-marker)))
633 (let ((case-fold-search (and case-fold-search
634 (isearch-no-upper-case-p regexp t
))))
636 (while (and (< (point) rend
)
637 (re-search-forward regexp rend t
))
638 (delete-region (save-excursion (goto-char (match-beginning 0))
641 (progn (forward-line 1) (point))))))
642 (set-marker rend nil
)
646 (defun how-many (regexp &optional rstart rend interactive
)
647 "Print and return number of matches for REGEXP following point.
648 When called from Lisp and INTERACTIVE is omitted or nil, just return
649 the number, do not print it; if INTERACTIVE is t, the function behaves
650 in all respects has if it had been called interactively.
652 If REGEXP contains upper case characters (excluding those preceded by `\\'),
653 the matching is case-sensitive.
655 Second and third arg RSTART and REND specify the region to operate on.
657 Interactively, in Transient Mark mode when the mark is active, operate
658 on the contents of the region. Otherwise, operate from point to the
659 end of (the accessible portion of) the buffer.
661 This function starts looking for the next match from the end of
662 the previous match. Hence, it ignores matches that overlap
663 a previously found match."
666 (keep-lines-read-args "How many matches for (regexp): "))
670 (goto-char (min rstart rend
))
671 (setq rend
(max rstart rend
)))
672 (if (and interactive transient-mark-mode mark-active
)
673 (setq rstart
(region-beginning)
680 (case-fold-search (and case-fold-search
681 (isearch-no-upper-case-p regexp t
))))
682 (while (and (< (point) rend
)
683 (progn (setq opoint
(point))
684 (re-search-forward regexp rend t
)))
685 (if (= opoint
(point))
687 (setq count
(1+ count
))))
688 (when interactive
(message "%d occurrence%s"
690 (if (= count
1) "" "s")))
694 (defvar occur-mode-map
695 (let ((map (make-sparse-keymap)))
696 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
697 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
698 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
699 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
700 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
701 (define-key map
"\M-n" 'occur-next
)
702 (define-key map
"\M-p" 'occur-prev
)
703 (define-key map
"r" 'occur-rename-buffer
)
704 (define-key map
"c" 'clone-buffer
)
705 (define-key map
"g" 'revert-buffer
)
706 (define-key map
"q" 'quit-window
)
707 (define-key map
"z" 'kill-this-buffer
)
708 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
710 "Keymap for `occur-mode'.")
712 (defvar occur-revert-arguments nil
713 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
714 See `occur-revert-function'.")
716 (defcustom occur-mode-hook
'(turn-on-font-lock)
717 "Hook run when entering Occur mode."
721 (defcustom occur-hook nil
722 "Hook run by Occur when there are any matches."
726 (put 'occur-mode
'mode-class
'special
)
728 "Major mode for output from \\[occur].
729 \\<occur-mode-map>Move point to one of the items in this buffer, then use
730 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
731 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
735 (kill-all-local-variables)
736 (use-local-map occur-mode-map
)
737 (setq major-mode
'occur-mode
)
738 (setq mode-name
"Occur")
739 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
740 (make-local-variable 'occur-revert-arguments
)
741 (add-hook 'change-major-mode-hook
'font-lock-defontify nil t
)
742 (setq next-error-function
'occur-next-error
)
743 (run-mode-hooks 'occur-mode-hook
))
745 (defun occur-revert-function (ignore1 ignore2
)
746 "Handle `revert-buffer' for Occur mode buffers."
747 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
749 (defun occur-mode-mouse-goto (event)
750 "In Occur mode, go to the occurrence whose line you click on."
754 (set-buffer (window-buffer (posn-window (event-end event
))))
756 (goto-char (posn-point (event-end event
)))
757 (setq pos
(occur-mode-find-occurrence))))
758 (let (same-window-buffer-names
760 (pop-to-buffer (marker-buffer pos
)))
763 (defun occur-mode-find-occurrence ()
764 (let ((pos (get-text-property (point) 'occur-target
)))
766 (error "No occurrence on this line"))
767 (unless (buffer-live-p (marker-buffer pos
))
768 (error "Buffer for this occurrence was killed"))
771 (defun occur-mode-goto-occurrence ()
772 "Go to the occurrence the current line describes."
774 (let ((pos (occur-mode-find-occurrence))
775 same-window-buffer-names
777 (pop-to-buffer (marker-buffer pos
))
780 (defun occur-mode-goto-occurrence-other-window ()
781 "Go to the occurrence the current line describes, in another window."
783 (let ((pos (occur-mode-find-occurrence)))
784 (switch-to-buffer-other-window (marker-buffer pos
))
787 (defun occur-mode-display-occurrence ()
788 "Display in another window the occurrence the current line describes."
790 (let ((pos (occur-mode-find-occurrence))
792 ;; Bind these to ensure `display-buffer' puts it in another window.
793 same-window-buffer-names
795 (setq window
(display-buffer (marker-buffer pos
)))
796 ;; This is the way to set point in the proper window.
797 (save-selected-window
798 (select-window window
)
801 (defun occur-find-match (n search message
)
802 (if (not n
) (setq n
1))
805 (setq r
(funcall search
(point) 'occur-match
))
807 (get-text-property r
'occur-match
)
808 (setq r
(funcall search r
'occur-match
)))
814 (defun occur-next (&optional n
)
815 "Move to the Nth (default 1) next match in an Occur mode buffer."
817 (occur-find-match n
#'next-single-property-change
"No more matches"))
819 (defun occur-prev (&optional n
)
820 "Move to the Nth (default 1) previous match in an Occur mode buffer."
822 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
824 (defun occur-next-error (&optional argp reset
)
825 "Move to the Nth (default 1) next match in an Occur mode buffer.
826 Compatibility function for \\[next-error] invocations."
828 ;; we need to run occur-find-match from within the Occur buffer
830 ;; Choose the buffer and make it current.
831 (if (next-error-buffer-p (current-buffer))
833 (next-error-find-buffer nil nil
835 (eq major-mode
'occur-mode
))))
837 (goto-char (cond (reset (point-min))
838 ((< argp
0) (line-beginning-position))
839 ((> argp
0) (line-end-position))
844 #'previous-single-property-change
845 #'next-single-property-change
)
847 ;; In case the *Occur* buffer is visible in a nonselected window.
848 (set-window-point (get-buffer-window (current-buffer)) (point))
849 (occur-mode-goto-occurrence)))
852 '((((class color
) (min-colors 88) (background light
))
854 (((class color
) (min-colors 88) (background dark
))
855 :background
"RoyalBlue3")
856 (((class color
) (min-colors 8))
857 :background
"blue" :foreground
"white")
858 (((type tty
) (class mono
))
860 (t :background
"gray"))
861 "Face used to highlight matches permanently."
865 (defcustom list-matching-lines-default-context-lines
0
866 "*Default number of context lines included around `list-matching-lines' matches.
867 A negative number means to include that many lines before the match.
868 A positive number means to include that many lines both before and after."
872 (defalias 'list-matching-lines
'occur
)
874 (defcustom list-matching-lines-face
'match
875 "*Face used by \\[list-matching-lines] to show the text that matches.
876 If the value is nil, don't highlight the matching portions specially."
880 (defcustom list-matching-lines-buffer-name-face
'underline
881 "*Face used by \\[list-matching-lines] to show the names of buffers.
882 If the value is nil, don't highlight the buffer names specially."
886 (defcustom occur-excluded-properties
887 '(read-only invisible intangible field mouse-face help-echo local-map keymap
888 yank-handler follow-link
)
889 "*Text properties to discard when copying lines to the *Occur* buffer.
890 The value should be a list of text properties to discard or t,
891 which means to discard all text properties."
892 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
896 (defun occur-accumulate-lines (count &optional keep-props
)
898 (let ((forwardp (> count
0))
900 (while (not (or (zerop count
)
904 (setq count
(+ count
(if forwardp -
1 1)))
905 (setq beg
(line-beginning-position)
906 end
(line-end-position))
907 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
908 (text-property-not-all beg end
'fontified t
))
909 (if (fboundp 'jit-lock-fontify-now
)
910 (jit-lock-fontify-now beg end
)))
912 (if (and keep-props
(not (eq occur-excluded-properties t
)))
913 (let ((str (buffer-substring beg end
)))
914 (remove-list-of-text-properties
915 0 (length str
) occur-excluded-properties str
)
917 (buffer-substring-no-properties beg end
))
919 (forward-line (if forwardp
1 -
1)))
922 (defun occur-read-primary-args ()
923 (list (let* ((default (car regexp-history
))
925 (read-from-minibuffer
927 (format "List lines matching regexp (default %s): "
928 (query-replace-descr default
))
929 "List lines matching regexp: ")
938 (when current-prefix-arg
939 (prefix-numeric-value current-prefix-arg
))))
941 (defun occur-rename-buffer (&optional unique-p interactive-p
)
942 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
943 Here `original-buffer-name' is the buffer name were Occur was originally run.
944 When given the prefix argument, or called non-interactively, the renaming
945 will not clobber the existing buffer(s) of that name, but use
946 `generate-new-buffer-name' instead. You can add this to `occur-hook'
947 if you always want a separate *Occur* buffer for each buffer where you
951 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
952 (rename-buffer (concat "*Occur: "
953 (mapconcat #'buffer-name
954 (car (cddr occur-revert-arguments
)) "/")
956 (or unique-p
(not interactive-p
)))))
958 (defun occur (regexp &optional nlines
)
959 "Show all lines in the current buffer containing a match for REGEXP.
960 This function can not handle matches that span more than one line.
962 Each line is displayed with NLINES lines before and after, or -NLINES
963 before if NLINES is negative.
964 NLINES defaults to `list-matching-lines-default-context-lines'.
965 Interactively it is the prefix arg.
967 The lines are shown in a buffer named `*Occur*'.
968 It serves as a menu to find any of the occurrences in this buffer.
969 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
971 If REGEXP contains upper case characters (excluding those preceded by `\\'),
972 the matching is case-sensitive."
973 (interactive (occur-read-primary-args))
974 (occur-1 regexp nlines
(list (current-buffer))))
976 (defun multi-occur (bufs regexp
&optional nlines
)
977 "Show all lines in buffers BUFS containing a match for REGEXP.
978 This function acts on multiple buffers; otherwise, it is exactly like
982 (let* ((bufs (list (read-buffer "First buffer to search: "
983 (current-buffer) t
)))
985 (ido-ignore-item-temp-list bufs
))
986 (while (not (string-equal
987 (setq buf
(read-buffer
988 (if (eq read-buffer-function
'ido-read-buffer
)
989 "Next buffer to search (C-j to end): "
990 "Next buffer to search (RET to end): ")
993 (add-to-list 'bufs buf
)
994 (setq ido-ignore-item-temp-list bufs
))
995 (nreverse (mapcar #'get-buffer bufs
)))
996 (occur-read-primary-args)))
997 (occur-1 regexp nlines bufs
))
999 (defun multi-occur-by-filename-regexp (bufregexp regexp
&optional nlines
)
1000 "Show all lines matching REGEXP in buffers named by BUFREGEXP.
1001 See also `multi-occur'."
1004 (let* ((default (car regexp-history
))
1006 (read-from-minibuffer
1007 "List lines in buffers whose filename matches regexp: "
1012 (if (equal input
"")
1015 (occur-read-primary-args)))
1017 (occur-1 regexp nlines
1019 (mapcar (lambda (buf)
1020 (when (and (buffer-file-name buf
)
1021 (string-match bufregexp
1022 (buffer-file-name buf
)))
1026 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1028 (setq buf-name
"*Occur*"))
1030 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1031 (when (buffer-live-p buf
) buf
))
1033 ;; Handle the case where one of the buffers we're searching is the
1034 ;; output buffer. Just rename it.
1035 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1036 (with-current-buffer (get-buffer buf-name
)
1039 ;; Now find or create the output buffer.
1040 ;; If we just renamed that buffer, we will make a new one here.
1041 (setq occur-buf
(get-buffer-create buf-name
))
1043 (with-current-buffer occur-buf
1045 (let ((inhibit-read-only t
))
1047 (let ((count (occur-engine
1048 regexp active-bufs occur-buf
1049 (or nlines list-matching-lines-default-context-lines
)
1050 (and case-fold-search
1051 (isearch-no-upper-case-p regexp t
))
1052 list-matching-lines-buffer-name-face
1053 nil list-matching-lines-face
1054 (not (eq occur-excluded-properties t
)))))
1055 (let* ((bufcount (length active-bufs
))
1056 (diff (- (length bufs
) bufcount
)))
1057 (message "Searched %d buffer%s%s; %s match%s for `%s'"
1058 bufcount
(if (= bufcount
1) "" "s")
1059 (if (zerop diff
) "" (format " (%d killed)" diff
))
1060 (if (zerop count
) "no" (format "%d" count
))
1061 (if (= count
1) "" "es")
1063 (setq occur-revert-arguments
(list regexp nlines bufs
))
1065 (kill-buffer occur-buf
)
1066 (display-buffer occur-buf
)
1067 (setq next-error-last-buffer occur-buf
)
1068 (setq buffer-read-only t
)
1069 (set-buffer-modified-p nil
)
1070 (run-hooks 'occur-hook
)))))))
1072 (defun occur-engine-add-prefix (lines)
1075 (concat " :" line
"\n"))
1078 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
1079 title-face prefix-face match-face keep-props
)
1080 (with-current-buffer out-buf
1081 (let ((globalcount 0)
1082 ;; Don't generate undo entries for creation of the initial contents.
1083 (buffer-undo-list t
)
1085 ;; Map over all the buffers
1086 (dolist (buf buffers
)
1087 (when (buffer-live-p buf
)
1088 (let ((matches 0) ;; count of matched lines
1089 (lines 1) ;; line count
1096 (headerpt (with-current-buffer out-buf
(point))))
1100 ;; Set CODING only if the current buffer locally
1101 ;; binds buffer-file-coding-system.
1102 (not (local-variable-p 'buffer-file-coding-system
))
1103 (setq coding buffer-file-coding-system
))
1105 (goto-char (point-min)) ;; begin searching in the buffer
1107 (setq origpt
(point))
1108 (when (setq endpt
(re-search-forward regexp nil t
))
1109 (setq matches
(1+ matches
)) ;; increment match count
1110 (setq matchbeg
(match-beginning 0))
1111 (setq lines
(+ lines
(1- (count-lines origpt endpt
))))
1113 (goto-char matchbeg
)
1114 (setq begpt
(line-beginning-position)
1115 endpt
(line-end-position)))
1116 (setq marker
(make-marker))
1117 (set-marker marker matchbeg
)
1119 (if (boundp 'jit-lock-mode
) jit-lock-mode
)
1120 (text-property-not-all begpt endpt
'fontified t
))
1121 (if (fboundp 'jit-lock-fontify-now
)
1122 (jit-lock-fontify-now begpt endpt
)))
1123 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1125 (setq curstring
(buffer-substring begpt endpt
))
1126 (remove-list-of-text-properties
1127 0 (length curstring
) occur-excluded-properties curstring
))
1128 (setq curstring
(buffer-substring-no-properties begpt endpt
)))
1129 ;; Highlight the matches
1130 (let ((len (length curstring
))
1132 (while (and (< start len
)
1133 (string-match regexp curstring start
))
1134 (add-text-properties
1135 (match-beginning 0) (match-end 0)
1139 ;; Use `face' rather than `font-lock-face' here
1140 ;; so as to override faces copied from the buffer.
1141 `(face ,match-face
)))
1143 (setq start
(match-end 0))))
1144 ;; Generate the string to insert for this match
1147 ;; Using 7 digits aligns tabs properly.
1148 (apply #'propertize
(format "%7d:" lines
)
1151 `(font-lock-face prefix-face
))
1152 `(occur-prefix t mouse-face
(highlight)
1153 occur-target
,marker follow-link t
1154 help-echo
"mouse-2: go to this occurrence")))
1155 ;; We don't put `mouse-face' on the newline,
1156 ;; because that loses. And don't put it
1157 ;; on context lines to reduce flicker.
1158 (propertize curstring
'mouse-face
(list 'highlight
)
1159 'occur-target marker
1162 "mouse-2: go to this occurrence")
1163 ;; Add marker at eol, but no mouse props.
1164 (propertize "\n" 'occur-target marker
)))
1167 ;; The simple display style
1169 ;; The complex multi-line display
1170 ;; style. Generate a list of lines,
1171 ;; concatenate them all together.
1174 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ (abs nlines
))) keep-props
))))
1177 (occur-engine-add-prefix
1178 (cdr (occur-accumulate-lines (1+ nlines
) keep-props
)))))))))
1179 ;; Actually insert the match display data
1180 (with-current-buffer out-buf
1182 (end (progn (insert data
) (point))))
1183 (unless (= nlines
0)
1184 (insert "-------\n")))))
1188 (setq lines
(1+ lines
))
1189 ;; On to the next match...
1191 (goto-char (point-max))))))
1192 (when (not (zerop matches
)) ;; is the count zero?
1193 (setq globalcount
(+ globalcount matches
))
1194 (with-current-buffer out-buf
1195 (goto-char headerpt
)
1198 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1199 matches
(if (= matches
1) "" "es")
1200 regexp
(buffer-name buf
)))
1202 (add-text-properties beg end
1205 `(font-lock-face ,title-face
))
1206 `(occur-title ,buf
))))
1207 (goto-char (point-min)))))))
1209 ;; CODING is buffer-file-coding-system of the first buffer
1210 ;; that locally binds it. Let's use it also for the output
1212 (set-buffer-file-coding-system coding
))
1213 ;; Return the number of matches
1217 ;; It would be nice to use \\[...], but there is no reasonable way
1218 ;; to make that display both SPC and Y.
1219 (defconst query-replace-help
1220 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1221 RET or `q' to exit, Period to replace one match and exit,
1222 Comma to replace but not move point immediately,
1223 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1224 C-w to delete match and recursive edit,
1225 C-l to clear the screen, redisplay, and offer same replacement again,
1226 ! to replace all remaining matches with no more questions,
1227 ^ to move point back to previous match,
1228 E to edit the replacement string"
1229 "Help message while in `query-replace'.")
1231 (defvar query-replace-map
(make-sparse-keymap)
1232 "Keymap that defines the responses to questions in `query-replace'.
1233 The \"bindings\" in this map are not commands; they are answers.
1234 The valid answers include `act', `skip', `act-and-show',
1235 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1236 `automatic', `backup', `exit-prefix', and `help'.")
1238 (define-key query-replace-map
" " 'act
)
1239 (define-key query-replace-map
"\d" 'skip
)
1240 (define-key query-replace-map
[delete] 'skip)
1241 (define-key query-replace-map [backspace] 'skip)
1242 (define-key query-replace-map "y" 'act)
1243 (define-key query-replace-map "n" 'skip)
1244 (define-key query-replace-map "Y" 'act)
1245 (define-key query-replace-map "N" 'skip)
1246 (define-key query-replace-map "e" 'edit-replacement)
1247 (define-key query-replace-map "E" 'edit-replacement)
1248 (define-key query-replace-map "," 'act-and-show)
1249 (define-key query-replace-map "q" 'exit)
1250 (define-key query-replace-map "\r" 'exit)
1251 (define-key query-replace-map [return] 'exit)
1252 (define-key query-replace-map "." 'act-and-exit)
1253 (define-key query-replace-map "\C-r" 'edit)
1254 (define-key query-replace-map "\C-w" 'delete-and-edit)
1255 (define-key query-replace-map "\C-l" 'recenter)
1256 (define-key query-replace-map "!" 'automatic)
1257 (define-key query-replace-map "^" 'backup)
1258 (define-key query-replace-map "\C-h" 'help)
1259 (define-key query-replace-map [f1] 'help)
1260 (define-key query-replace-map [help] 'help)
1261 (define-key query-replace-map "?" 'help)
1262 (define-key query-replace-map "\C-g" 'quit)
1263 (define-key query-replace-map "\C-]" 'quit)
1264 (define-key query-replace-map "\e" 'exit-prefix)
1265 (define-key query-replace-map [escape] 'exit-prefix)
1267 (defun replace-match-string-symbols (n)
1268 "Process a list (and any sub-lists), expanding certain symbols.
1270 N (match-string N) (where N is a string of digits)
1271 #N (string-to-number (match-string N))
1273 #& (string-to-number (match-string 0))
1276 Note that these symbols must be preceeded by a backslash in order to
1281 (replace-match-string-symbols (car n))) ;Process sub-list
1283 (let ((name (symbol-name (car n))))
1285 ((string-match "^[0-9]+$" name)
1286 (setcar n (list 'match-string (string-to-number name))))
1287 ((string-match "^#[0-9]+$" name)
1288 (setcar n (list 'string-to-number
1290 (string-to-number (substring name 1))))))
1292 (setcar n '(match-string 0)))
1293 ((string= "#&" name)
1294 (setcar n '(string-to-number (match-string 0))))
1296 (setcar n 'replace-count))))))
1299 (defun replace-eval-replacement (expression replace-count)
1300 (let ((replacement (eval expression)))
1301 (if (stringp replacement)
1303 (prin1-to-string replacement t))))
1305 (defun replace-quote (replacement)
1306 "Quote a replacement string.
1307 This just doubles all backslashes in REPLACEMENT and
1308 returns the resulting string. If REPLACEMENT is not
1309 a string, it is first passed through `prin1-to-string'
1310 with the `noescape' argument set.
1312 `match-data' is preserved across the call."
1314 (replace-regexp-in-string "\\\\" "\\\\"
1315 (if (stringp replacement)
1317 (prin1-to-string replacement t))
1320 (defun replace-loop-through-replacements (data replace-count)
1321 ;; DATA is a vector contaning the following values:
1322 ;; 0 next-rotate-count
1324 ;; 2 next-replacement
1326 (if (= (aref data 0) replace-count)
1328 (aset data 0 (+ replace-count (aref data 1)))
1329 (let ((next (cdr (aref data 2))))
1330 (aset data 2 (if (consp next) next (aref data 3))))))
1331 (car (aref data 2)))
1333 (defun replace-match-data (integers reuse &optional new)
1334 "Like `match-data', but markers in REUSE get invalidated.
1335 If NEW is non-NIL, it is set and returned instead of fresh data,
1336 but coerced to the correct value of INTEGERS."
1339 (set-match-data new)
1341 (eq (null integers) (markerp (car reuse)))
1343 (match-data integers reuse t)))
1345 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1346 "Make a replacement with `replace-match', editing `\\?'.
1347 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1348 check for `\\?' is made to save time. MATCH-DATA is used for the
1349 replacement. In case editing is done, it is changed to use markers.
1351 The return value is non-NIL if there has been no `\\?' or NOEDIT was
1352 passed in. If LITERAL is set, no checking is done, anyway."
1353 (unless (or literal noedit)
1355 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1358 (read-string "Edit replacement string: "
1361 (replace-match "" t t newtext 3)
1362 (1+ (match-beginning 3)))
1365 nil match-data match-data))))
1367 (set-match-data match-data)
1368 (replace-match newtext fixedcase literal)
1371 (defun perform-replace (from-string replacements
1372 query-flag regexp-flag delimited-flag
1373 &optional repeat-count map start end)
1374 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1375 Don't use this in your own program unless you want to query and set the mark
1376 just as `query-replace' does. Instead, write a simple loop like this:
1378 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1379 (replace-match \"foobar\" nil nil))
1381 which will run faster and probably do exactly what you want. Please
1382 see the documentation of `replace-match' to find out how to simulate
1385 This function returns nil if and only if there were no matches to
1386 make, or the user didn't cancel the call."
1387 (or map (setq map query-replace-map))
1388 (and query-flag minibuffer-auto-raise
1389 (raise-frame (window-frame (minibuffer-window))))
1390 (let ((nocasify (not (and case-fold-search case-replace
1391 (string-equal from-string
1392 (downcase from-string)))))
1393 (case-fold-search (and case-fold-search
1394 (string-equal from-string
1395 (downcase from-string))))
1396 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1397 (search-function (if regexp-flag 're-search-forward 'search-forward))
1398 (search-string from-string)
1399 (real-match-data nil) ; the match data for the current match
1400 (next-replacement nil)
1405 (nonempty-match nil)
1407 ;; If non-nil, it is marker saying where in the buffer to stop.
1410 ;; Data for the next match. If a cons, it has the same format as
1411 ;; (match-data); otherwise it is t if a match is possible at point.
1416 (substitute-command-keys
1417 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
1419 ;; If region is active, in Transient Mark mode, operate on region.
1421 (setq limit (copy-marker (max start end)))
1422 (goto-char (min start end))
1425 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1426 ;; containing a function and its first argument. The function is
1427 ;; called to generate each replacement like this:
1428 ;; (funcall (car replacements) (cdr replacements) replace-count)
1429 ;; It must return a string.
1431 ((stringp replacements)
1432 (setq next-replacement replacements
1434 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1435 (or repeat-count (setq repeat-count 1))
1436 (setq replacements (cons 'replace-loop-through-replacements
1437 (vector repeat-count repeat-count
1438 replacements replacements)))))
1441 (setq search-function 're-search-forward
1442 search-string (concat "\\b"
1443 (if regexp-flag from-string
1444 (regexp-quote from-string))
1446 (when query-replace-lazy-highlight
1447 (setq isearch-lazy-highlight-last-string nil))
1452 ;; Loop finding occurrences that perhaps should be replaced.
1453 (while (and keep-going
1454 (not (or (eobp) (and limit (>= (point) limit))))
1455 ;; Use the next match if it is already known;
1456 ;; otherwise, search for a match after moving forward
1457 ;; one char if progress is required.
1458 (setq real-match-data
1459 (if (consp match-again)
1460 (progn (goto-char (nth 1 match-again))
1461 (replace-match-data t
1464 (and (or match-again
1465 ;; MATCH-AGAIN non-nil means we
1466 ;; accept an adjacent match. If
1467 ;; we don't, move one char to the
1468 ;; right. This takes us a
1469 ;; character too far at the end,
1470 ;; but this is undone after the
1475 (and limit (>= (point) limit))))))
1476 (funcall search-function search-string limit t)
1477 ;; For speed, use only integers and
1478 ;; reuse the list used last time.
1479 (replace-match-data t real-match-data)))))
1480 ;; Optionally ignore matches that have a read-only property.
1481 (unless (and query-replace-skip-read-only
1482 (text-property-not-all
1483 (match-beginning 0) (match-end 0)
1486 ;; Record whether the match is nonempty, to avoid an infinite loop
1487 ;; repeatedly matching the same empty string.
1488 (setq nonempty-match
1489 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1491 ;; If the match is empty, record that the next one can't be
1494 ;; Otherwise, if matching a regular expression, do the next
1495 ;; match now, since the replacement for this match may
1496 ;; affect whether the next match is adjacent to this one.
1497 ;; If that match is empty, don't use it.
1500 (or (not regexp-flag)
1501 (and (looking-at search-string)
1502 (let ((match (match-data)))
1503 (and (/= (nth 0 match) (nth 1 match))
1506 ;; Calculate the replacement string, if necessary.
1508 (set-match-data real-match-data)
1509 (setq next-replacement
1510 (funcall (car replacements) (cdr replacements)
1513 (if (not query-flag)
1514 (let ((inhibit-read-only
1515 query-replace-skip-read-only))
1516 (unless (or literal noedit)
1518 (nth 0 real-match-data) (nth 1 real-match-data)
1519 start end search-string
1520 (or delimited-flag regexp-flag) case-fold-search))
1522 (replace-match-maybe-edit
1523 next-replacement nocasify literal
1524 noedit real-match-data)
1525 replace-count (1+ replace-count)))
1527 (let (done replaced key def)
1528 ;; Loop reading commands until one of them sets done,
1529 ;; which means it has finished handling this
1530 ;; occurrence. Any command that sets `done' should
1531 ;; leave behind proper match data for the stack.
1532 ;; Commands not setting `done' need to adjust
1533 ;; `real-match-data'.
1535 (set-match-data real-match-data)
1537 (match-beginning 0) (match-end 0)
1538 start end search-string
1539 (or delimited-flag regexp-flag) case-fold-search)
1540 ;; Bind message-log-max so we don't fill up the message log
1541 ;; with a bunch of identical messages.
1542 (let ((message-log-max nil))
1544 (query-replace-descr from-string)
1545 (query-replace-descr next-replacement)))
1546 (setq key (read-event))
1547 ;; Necessary in case something happens during read-event
1548 ;; that clobbers the match data.
1549 (set-match-data real-match-data)
1550 (setq key (vector key))
1551 (setq def (lookup-key map key))
1552 ;; Restore the match data while we process the command.
1553 (cond ((eq def 'help)
1554 (with-output-to-temp-buffer "*Help*"
1556 (concat "Query replacing "
1557 (if regexp-flag "regexp " "")
1558 from-string " with "
1559 next-replacement ".\n\n"
1560 (substitute-command-keys
1561 query-replace-help)))
1562 (with-current-buffer standard-output
1565 (setq keep-going nil)
1569 (let ((elt (pop stack)))
1570 (goto-char (nth 0 elt))
1571 (setq replaced (nth 1 elt)
1576 (message "No previous match")
1577 (ding 'no-terminate)
1582 (replace-match-maybe-edit
1583 next-replacement nocasify literal
1584 noedit real-match-data)
1585 replace-count (1+ replace-count)))
1586 (setq done t replaced t))
1587 ((eq def 'act-and-exit)
1590 (replace-match-maybe-edit
1591 next-replacement nocasify literal
1592 noedit real-match-data)
1593 replace-count (1+ replace-count)))
1594 (setq keep-going nil)
1595 (setq done t replaced t))
1596 ((eq def 'act-and-show)
1599 (replace-match-maybe-edit
1600 next-replacement nocasify literal
1601 noedit real-match-data)
1602 replace-count (1+ replace-count)
1603 real-match-data (replace-match-data
1606 ((eq def 'automatic)
1609 (replace-match-maybe-edit
1610 next-replacement nocasify literal
1611 noedit real-match-data)
1612 replace-count (1+ replace-count)))
1613 (setq done t query-flag nil replaced t))
1619 (let ((opos (point-marker)))
1620 (setq real-match-data (replace-match-data
1623 (goto-char (match-beginning 0))
1625 (save-window-excursion
1628 (set-marker opos nil))
1629 ;; Before we make the replacement,
1630 ;; decide whether the search string
1631 ;; can match again just after this match.
1632 (if (and regexp-flag nonempty-match)
1633 (setq match-again (and (looking-at search-string)
1635 ;; Edit replacement.
1636 ((eq def 'edit-replacement)
1637 (setq real-match-data (replace-match-data
1641 (read-string "Edit replacement string: "
1645 (set-match-data real-match-data)
1647 (replace-match-maybe-edit
1648 next-replacement nocasify literal noedit
1653 ((eq def 'delete-and-edit)
1654 (replace-match "" t t)
1655 (setq real-match-data (replace-match-data
1656 nil real-match-data))
1657 (replace-dehighlight)
1658 (save-excursion (recursive-edit))
1660 ;; Note: we do not need to treat `exit-prefix'
1661 ;; specially here, since we reread
1662 ;; any unrecognized character.
1664 (setq this-command 'mode-exited)
1665 (setq keep-going nil)
1666 (setq unread-command-events
1667 (append (listify-key-sequence key)
1668 unread-command-events))
1670 (when query-replace-lazy-highlight
1671 ;; Force lazy rehighlighting only after replacements
1672 (if (not (memq def '(skip backup)))
1673 (setq isearch-lazy-highlight-last-string nil))))
1674 ;; Record previous position for ^ when we move on.
1675 ;; Change markers to numbers in the match data
1676 ;; since lots of markers slow down editing.
1677 (push (list (point) replaced
1678 ;;; If the replacement has already happened, all we need is the
1679 ;;; current match start and end. We could get this with a trivial
1681 ;;; (save-excursion (goto-char (match-beginning 0))
1682 ;;; (search-forward (match-string 0))
1684 ;;; if we really wanted to avoid manually constructing match data.
1685 ;;; Adding current-buffer is necessary so that match-data calls can
1686 ;;; return markers which are appropriate for editing.
1695 ;; The code preventing adjacent regexp matches in the condition
1696 ;; of the while-loop above will haven taken us one character
1697 ;; beyond the last replacement. Undo that.
1698 (when (and regexp-flag (not match-again) (> replace-count 0))
1701 (replace-dehighlight))
1702 (or unread-command-events
1703 (message "Replaced %d occurrence%s"
1705 (if (= replace-count 1) "" "s")))
1706 (and keep-going stack)))
1708 (defvar replace-overlay nil)
1710 (defun replace-highlight (match-beg match-end range-beg range-end
1711 string regexp case-fold)
1712 (if query-replace-highlight
1714 (move-overlay replace-overlay match-beg match-end (current-buffer))
1715 (setq replace-overlay (make-overlay match-beg match-end))
1716 (overlay-put replace-overlay 'priority 1) ;higher than lazy overlays
1717 (overlay-put replace-overlay 'face 'query-replace)))
1718 (if query-replace-lazy-highlight
1719 (let ((isearch-string string)
1720 (isearch-regexp regexp)
1721 (isearch-case-fold-search case-fold))
1722 (isearch-lazy-highlight-new-loop range-beg range-end))))
1724 (defun replace-dehighlight ()
1725 (when replace-overlay
1726 (delete-overlay replace-overlay))
1727 (when query-replace-lazy-highlight
1728 (lazy-highlight-cleanup lazy-highlight-cleanup)
1729 (setq isearch-lazy-highlight-last-string nil)))
1731 ;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1732 ;;; replace.el ends here