1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1992, 1994, 1996, 1997, 2000, 2001,
4 ;; 2002, 2003, 2004, 2005, 2006, 2007 Free Software Foundation, Inc.
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 3, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
27 ;; This package supplies the string and regular-expression replace functions
28 ;; documented in the Emacs user's manual.
32 (defcustom case-replace t
33 "*Non-nil means `query-replace' should preserve case in replacements."
37 (defvar query-replace-history nil
)
39 (defvar query-replace-defaults nil
40 "Default values of FROM-STRING and TO-STRING for `query-replace'.
41 This is a cons cell (FROM-STRING . TO-STRING), or nil if there is
44 (defvar query-replace-interactive nil
45 "Non-nil means `query-replace' uses the last search string.
46 That becomes the \"string to replace\".")
48 (defcustom query-replace-from-history-variable
'query-replace-history
49 "History list to use for the FROM argument of `query-replace' commands.
50 The value of this variable should be a symbol; that symbol
51 is used as a variable to hold a history list for the strings
52 or patterns to be replaced."
57 (defcustom query-replace-to-history-variable
'query-replace-history
58 "History list to use for the TO argument of `query-replace' commands.
59 The value of this variable should be a symbol; that symbol
60 is used as a variable to hold a history list for replacement
66 (defcustom query-replace-skip-read-only nil
67 "*Non-nil means `query-replace' and friends ignore read-only matches."
72 (defcustom query-replace-highlight t
73 "*Non-nil means to highlight matches during query replacement."
77 (defcustom query-replace-lazy-highlight t
78 "*Controls the lazy-highlighting during query replacements.
79 When non-nil, all text in the buffer matching the current match
80 is highlighted lazily using isearch lazy highlighting (see
81 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
83 :group
'lazy-highlight
87 (defface query-replace
88 '((t (:inherit isearch
)))
89 "Face for highlighting query replacement matches."
93 (defun query-replace-descr (string)
94 (mapconcat 'isearch-text-char-description string
""))
96 (defun query-replace-read-from (prompt regexp-flag
)
97 "Query and return the `from' argument of a query-replace operation.
98 The return value can also be a pair (FROM . TO) indicating that the user
99 wants to replace FROM with TO."
100 (if query-replace-interactive
101 (car (if regexp-flag regexp-search-ring search-ring
))
102 (let* ((history-add-new-input nil
)
104 ;; The save-excursion here is in case the user marks and copies
105 ;; a region in order to specify the minibuffer input.
106 ;; That should not clobber the region for the query-replace itself.
108 (read-from-minibuffer
109 (if query-replace-defaults
110 (format "%s (default %s -> %s): " prompt
111 (query-replace-descr (car query-replace-defaults
))
112 (query-replace-descr (cdr query-replace-defaults
)))
113 (format "%s: " prompt
))
115 query-replace-from-history-variable
117 (if (and (zerop (length from
)) query-replace-defaults
)
118 (cons (car query-replace-defaults
)
119 (query-replace-compile-replacement
120 (cdr query-replace-defaults
) regexp-flag
))
121 (add-to-history query-replace-from-history-variable from nil t
)
122 ;; Warn if user types \n or \t, but don't reject the input.
124 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
125 (let ((match (match-string 3 from
)))
127 ((string= match
"\\n")
128 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
129 ((string= match
"\\t")
130 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
134 (defun query-replace-compile-replacement (to regexp-flag
)
135 "Maybe convert a regexp replacement TO to Lisp.
136 Returns a list suitable for `perform-replace' if necessary,
137 the original string if not."
139 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
))
143 (setq pos
(match-end 0))
144 (push (substring to
0 (- pos
2)) list
)
145 (setq char
(aref to
(1- pos
))
146 to
(substring to pos
))
148 (push '(number-to-string replace-count
) list
))
150 (setq pos
(read-from-string to
))
151 (push `(replace-quote ,(car pos
)) list
)
153 ;; Swallow a space after a symbol
154 ;; if there is a space.
155 (if (and (or (symbolp (car pos
))
156 ;; Swallow a space after 'foo
157 ;; but not after (quote foo).
158 (and (eq (car-safe (car pos
)) 'quote
)
159 (not (= ?\
( (aref to
0)))))
160 (eq (string-match " " to
(cdr pos
))
164 (setq to
(substring to end
)))))
165 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
)))
166 (setq to
(nreverse (delete "" (cons to list
))))
167 (replace-match-string-symbols to
)
168 (cons 'replace-eval-replacement
175 (defun query-replace-read-to (from prompt regexp-flag
)
176 "Query and return the `to' argument of a query-replace operation."
177 (query-replace-compile-replacement
179 (let* ((history-add-new-input nil
)
180 (to (read-from-minibuffer
181 (format "%s %s with: " prompt
(query-replace-descr from
))
183 query-replace-to-history-variable from t
)))
184 (add-to-history query-replace-to-history-variable to nil t
)
185 (setq query-replace-defaults
(cons from to
))
189 (defun query-replace-read-args (prompt regexp-flag
&optional noerror
)
191 (barf-if-buffer-read-only))
192 (let* ((from (query-replace-read-from prompt regexp-flag
))
193 (to (if (consp from
) (prog1 (cdr from
) (setq from
(car from
)))
194 (query-replace-read-to from prompt regexp-flag
))))
195 (list from to current-prefix-arg
)))
197 (defun query-replace (from-string to-string
&optional delimited start end
)
198 "Replace some occurrences of FROM-STRING with TO-STRING.
199 As each match is found, the user must type a character saying
200 what to do with it. For directions, type \\[help-command] at that time.
202 In Transient Mark mode, if the mark is active, operate on the contents
203 of the region. Otherwise, operate from point to the end of the buffer.
205 If `query-replace-interactive' is non-nil, the last incremental search
206 string is used as FROM-STRING--you don't have to specify it with the
209 Matching is independent of case if `case-fold-search' is non-nil and
210 FROM-STRING has no uppercase letters. Replacement transfers the case
211 pattern of the old text to the new text, if `case-replace' and
212 `case-fold-search' are non-nil and FROM-STRING has no uppercase
213 letters. \(Transferring the case pattern means that if the old text
214 matched is all caps, or capitalized, then its replacement is upcased
217 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
218 only matches surrounded by word boundaries.
219 Fourth and fifth arg START and END specify the region to operate on.
221 To customize possible responses, change the \"bindings\" in `query-replace-map'."
222 (interactive (let ((common
223 (query-replace-read-args
224 (if (and transient-mark-mode mark-active
)
225 "Query replace in region"
228 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
229 ;; These are done separately here
230 ;; so that command-history will record these expressions
231 ;; rather than the values they had this time.
232 (if (and transient-mark-mode mark-active
)
234 (if (and transient-mark-mode mark-active
)
236 (perform-replace from-string to-string t nil delimited nil nil start end
))
238 (define-key esc-map
"%" 'query-replace
)
240 (defun query-replace-regexp (regexp to-string
&optional delimited start end
)
241 "Replace some things after point matching REGEXP with TO-STRING.
242 As each match is found, the user must type a character saying
243 what to do with it. For directions, type \\[help-command] at that time.
245 In Transient Mark mode, if the mark is active, operate on the contents
246 of the region. Otherwise, operate from point to the end of the buffer.
248 If `query-replace-interactive' is non-nil, the last incremental search
249 regexp is used as REGEXP--you don't have to specify it with the
252 Matching is independent of case if `case-fold-search' is non-nil and
253 REGEXP has no uppercase letters. Replacement transfers the case
254 pattern of the old text to the new text, if `case-replace' and
255 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
256 \(Transferring the case pattern means that if the old text matched is
257 all caps, or capitalized, then its replacement is upcased or
260 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
261 only matches surrounded by word boundaries.
262 Fourth and fifth arg START and END specify the region to operate on.
264 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
265 and `\\=\\N' (where N is a digit) stands for
266 whatever what matched the Nth `\\(...\\)' in REGEXP.
267 `\\?' lets you edit the replacement text in the minibuffer
268 at the given position for each replacement.
270 In interactive calls, the replacement text can contain `\\,'
271 followed by a Lisp expression. Each
272 replacement evaluates that expression to compute the replacement
273 string. Inside of that expression, `\\&' is a string denoting the
274 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
275 for the whole or a partial match converted to a number with
276 `string-to-number', and `\\#' itself for the number of replacements
277 done so far (starting with zero).
279 If the replacement expression is a symbol, write a space after it
280 to terminate it. One space there, if any, will be discarded.
282 When using those Lisp features interactively in the replacement
283 text, TO-STRING is actually made a list instead of a string.
284 Use \\[repeat-complex-command] after this command for details."
287 (query-replace-read-args
288 (if (and transient-mark-mode mark-active
)
289 "Query replace regexp in region"
290 "Query replace regexp")
292 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
293 ;; These are done separately here
294 ;; so that command-history will record these expressions
295 ;; rather than the values they had this time.
296 (if (and transient-mark-mode mark-active
)
298 (if (and transient-mark-mode mark-active
)
300 (perform-replace regexp to-string t t delimited nil nil start end
))
302 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
304 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
305 "Replace some things after point matching REGEXP with the result of TO-EXPR.
307 Interactive use of this function is deprecated in favor of the
308 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
309 using `search-forward-regexp' and `replace-match' is preferred.
311 As each match is found, the user must type a character saying
312 what to do with it. For directions, type \\[help-command] at that time.
314 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
315 reference `replace-count' to get the number of replacements already made.
316 If the result of TO-EXPR is not a string, it is converted to one using
317 `prin1-to-string' with the NOESCAPE argument (which see).
319 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
320 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
321 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
322 Use `\\#&' or `\\#N' if you want a number instead of a string.
323 In interactive use, `\\#' in itself stands for `replace-count'.
325 In Transient Mark mode, if the mark is active, operate on the contents
326 of the region. Otherwise, operate from point to the end of the buffer.
328 If `query-replace-interactive' is non-nil, the last incremental search
329 regexp is used as REGEXP--you don't have to specify it with the
332 Preserves case in each replacement if `case-replace' and `case-fold-search'
333 are non-nil and REGEXP has no uppercase letters.
335 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
336 only matches that are surrounded by word boundaries.
337 Fourth and fifth arg START and END specify the region to operate on."
340 (barf-if-buffer-read-only)
342 ;; Let-bind the history var to disable the "foo -> bar" default.
343 ;; Maybe we shouldn't disable this default, but for now I'll
344 ;; leave it off. --Stef
345 (let ((query-replace-to-history-variable nil
))
346 (query-replace-read-from "Query replace regexp" t
)))
347 (to (list (read-from-minibuffer
348 (format "Query replace regexp %s with eval: "
349 (query-replace-descr from
))
350 nil nil t query-replace-to-history-variable from t
))))
351 ;; We make TO a list because replace-match-string-symbols requires one,
352 ;; and the user might enter a single token.
353 (replace-match-string-symbols to
)
354 (list from
(car to
) current-prefix-arg
355 (if (and transient-mark-mode mark-active
)
357 (if (and transient-mark-mode mark-active
)
359 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
360 t
'literal delimited nil nil start end
))
362 (make-obsolete 'query-replace-regexp-eval
363 "for interactive use, use the special `\\,' feature of
364 `query-replace-regexp' instead. Non-interactively, a loop
365 using `search-forward-regexp' and `replace-match' is preferred." "22.1")
367 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
368 "Replace some matches for REGEXP with various strings, in rotation.
369 The second argument TO-STRINGS contains the replacement strings,
370 separated by spaces. Third arg DELIMITED (prefix arg if interactive),
371 if non-nil, means replace only matches surrounded by word boundaries.
372 This command works like `query-replace-regexp' except that each
373 successive replacement uses the next successive replacement string,
374 wrapping around from the last such string to the first.
376 In Transient Mark mode, if the mark is active, operate on the contents
377 of the region. Otherwise, operate from point to the end of the buffer.
379 Non-interactively, TO-STRINGS may be a list of replacement strings.
381 If `query-replace-interactive' is non-nil, the last incremental search
382 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
384 A prefix argument N says to use each replacement string N times
385 before rotating to the next.
386 Fourth and fifth arg START and END specify the region to operate on."
388 (let* ((from (if query-replace-interactive
389 (car regexp-search-ring
)
390 (read-from-minibuffer "Map query replace (regexp): "
392 'query-replace-history nil t
)))
393 (to (read-from-minibuffer
394 (format "Query replace %s with (space-separated strings): "
395 (query-replace-descr from
))
397 'query-replace-history from t
)))
399 (and current-prefix-arg
400 (prefix-numeric-value current-prefix-arg
))
401 (if (and transient-mark-mode mark-active
)
403 (if (and transient-mark-mode mark-active
)
406 (if (listp to-strings
)
407 (setq replacements to-strings
)
408 (while (/= (length to-strings
) 0)
409 (if (string-match " " to-strings
)
412 (list (substring to-strings
0
413 (string-match " " to-strings
))))
414 to-strings
(substring to-strings
415 (1+ (string-match " " to-strings
))))
416 (setq replacements
(append replacements
(list to-strings
))
418 (perform-replace regexp replacements t t nil n nil start end
)))
420 (defun replace-string (from-string to-string
&optional delimited start end
)
421 "Replace occurrences of FROM-STRING with TO-STRING.
422 Preserve case in each match if `case-replace' and `case-fold-search'
423 are non-nil and FROM-STRING has no uppercase letters.
424 \(Preserving case means that if the string matched is all caps, or capitalized,
425 then its replacement is upcased or capitalized.)
427 In Transient Mark mode, if the mark is active, operate on the contents
428 of the region. Otherwise, operate from point to the end of the buffer.
430 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
431 only matches surrounded by word boundaries.
432 Fourth and fifth arg START and END specify the region to operate on.
434 If `query-replace-interactive' is non-nil, the last incremental search
435 string is used as FROM-STRING--you don't have to specify it with the
438 This function is usually the wrong thing to use in a Lisp program.
439 What you probably want is a loop like this:
440 (while (search-forward FROM-STRING nil t)
441 (replace-match TO-STRING nil t))
442 which will run faster and will not set the mark or print anything.
443 \(You may need a more complex loop if FROM-STRING can match the null string
444 and TO-STRING is also null.)"
447 (query-replace-read-args
448 (if (and transient-mark-mode mark-active
)
449 "Replace string in region"
452 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
453 (if (and transient-mark-mode mark-active
)
455 (if (and transient-mark-mode mark-active
)
457 (perform-replace from-string to-string nil nil delimited nil nil start end
))
459 (defun replace-regexp (regexp to-string
&optional delimited start end
)
460 "Replace things after point matching REGEXP with TO-STRING.
461 Preserve case in each match if `case-replace' and `case-fold-search'
462 are non-nil and REGEXP has no uppercase letters.
464 In Transient Mark mode, if the mark is active, operate on the contents
465 of the region. Otherwise, operate from point to the end of the buffer.
467 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
468 only matches surrounded by word boundaries.
469 Fourth and fifth arg START and END specify the region to operate on.
471 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
472 and `\\=\\N' (where N is a digit) stands for
473 whatever what matched the Nth `\\(...\\)' in REGEXP.
474 `\\?' lets you edit the replacement text in the minibuffer
475 at the given position for each replacement.
477 In interactive calls, the replacement text may contain `\\,'
478 followed by a Lisp expression used as part of the replacement
479 text. Inside of that expression, `\\&' is a string denoting the
480 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
481 numeric values from `string-to-number', and `\\#' itself for
482 `replace-count', the number of replacements occurred so far.
484 If your Lisp expression is an identifier and the next letter in
485 the replacement string would be interpreted as part of it, you
486 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
487 for this particular case you may also enter `\\#' in the
488 replacement text directly.
490 When using those Lisp features interactively in the replacement
491 text, TO-STRING is actually made a list instead of a string.
492 Use \\[repeat-complex-command] after this command for details.
494 If `query-replace-interactive' is non-nil, the last incremental search
495 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
497 This function is usually the wrong thing to use in a Lisp program.
498 What you probably want is a loop like this:
499 (while (re-search-forward REGEXP nil t)
500 (replace-match TO-STRING nil nil))
501 which will run faster and will not set the mark or print anything."
504 (query-replace-read-args
505 (if (and transient-mark-mode mark-active
)
506 "Replace regexp in region"
509 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
510 (if (and transient-mark-mode mark-active
)
512 (if (and transient-mark-mode mark-active
)
514 (perform-replace regexp to-string nil t delimited nil nil start end
))
517 (defvar regexp-history nil
518 "History list for some commands that read regular expressions.")
521 (defalias 'delete-non-matching-lines
'keep-lines
)
522 (defalias 'delete-matching-lines
'flush-lines
)
523 (defalias 'count-matches
'how-many
)
526 (defun keep-lines-read-args (prompt)
527 "Read arguments for `keep-lines' and friends.
528 Prompt for a regexp with PROMPT.
529 Value is a list, (REGEXP)."
530 (list (read-from-minibuffer prompt nil nil nil
531 'regexp-history nil t
)
534 (defun keep-lines (regexp &optional rstart rend interactive
)
535 "Delete all lines except those containing matches for REGEXP.
536 A match split across lines preserves all the lines it lies in.
537 When called from Lisp (and usually interactively as well, see below)
538 applies to all lines starting after point.
540 If REGEXP contains upper case characters (excluding those preceded by `\\'),
541 the matching is case-sensitive.
543 Second and third arg RSTART and REND specify the region to operate on.
544 This command operates on (the accessible part of) all lines whose
545 accessible part is entirely contained in the region determined by RSTART
546 and REND. (A newline ending a line counts as part of that line.)
548 Interactively, in Transient Mark mode when the mark is active, operate
549 on all lines whose accessible part is entirely contained in the region.
550 Otherwise, the command applies to all lines starting after point.
551 When calling this function from Lisp, you can pretend that it was
552 called interactively by passing a non-nil INTERACTIVE argument.
554 This function starts looking for the next match from the end of
555 the previous match. Hence, it ignores matches that overlap
556 a previously found match."
560 (barf-if-buffer-read-only)
561 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
564 (goto-char (min rstart rend
))
568 (goto-char (max rstart rend
))
569 (unless (or (bolp) (eobp))
572 (if (and interactive transient-mark-mode mark-active
)
573 (setq rstart
(region-beginning)
575 (goto-char (region-end))
576 (unless (or (bolp) (eobp))
580 rend
(point-max-marker)))
583 (or (bolp) (forward-line 1))
584 (let ((start (point))
585 (case-fold-search (and case-fold-search
586 (isearch-no-upper-case-p regexp t
))))
587 (while (< (point) rend
)
588 ;; Start is first char not preserved by previous match.
589 (if (not (re-search-forward regexp rend
'move
))
590 (delete-region start rend
)
591 (let ((end (save-excursion (goto-char (match-beginning 0))
594 ;; Now end is first char preserved by the new match.
596 (delete-region start end
))))
598 (setq start
(save-excursion (forward-line 1) (point)))
599 ;; If the match was empty, avoid matching again at same place.
600 (and (< (point) rend
)
601 (= (match-beginning 0) (match-end 0))
603 (set-marker rend nil
)
607 (defun flush-lines (regexp &optional rstart rend interactive
)
608 "Delete lines containing matches for REGEXP.
609 When called from Lisp (and usually when called interactively as
610 well, see below), applies to the part of the buffer after point.
611 The line point is in is deleted if and only if it contains a
612 match for regexp starting after point.
614 If REGEXP contains upper case characters (excluding those preceded by `\\'),
615 the matching is case-sensitive.
617 Second and third arg RSTART and REND specify the region to operate on.
618 Lines partially contained in this region are deleted if and only if
619 they contain a match entirely contained in it.
621 Interactively, in Transient Mark mode when the mark is active, operate
622 on the contents of the region. Otherwise, operate from point to the
623 end of (the accessible portion of) the buffer. When calling this function
624 from Lisp, you can pretend that it was called interactively by passing
625 a non-nil INTERACTIVE argument.
627 If a match is split across lines, all the lines it lies in are deleted.
628 They are deleted _before_ looking for the next match. Hence, a match
629 starting on the same line at which another match ended is ignored."
633 (barf-if-buffer-read-only)
634 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
637 (goto-char (min rstart rend
))
638 (setq rend
(copy-marker (max rstart rend
))))
639 (if (and interactive transient-mark-mode mark-active
)
640 (setq rstart
(region-beginning)
641 rend
(copy-marker (region-end)))
643 rend
(point-max-marker)))
645 (let ((case-fold-search (and case-fold-search
646 (isearch-no-upper-case-p regexp t
))))
648 (while (and (< (point) rend
)
649 (re-search-forward regexp rend t
))
650 (delete-region (save-excursion (goto-char (match-beginning 0))
653 (progn (forward-line 1) (point))))))
654 (set-marker rend nil
)
658 (defun how-many (regexp &optional rstart rend interactive
)
659 "Print and return number of matches for REGEXP following point.
660 When called from Lisp and INTERACTIVE is omitted or nil, just return
661 the number, do not print it; if INTERACTIVE is t, the function behaves
662 in all respects has if it had been called interactively.
664 If REGEXP contains upper case characters (excluding those preceded by `\\'),
665 the matching is case-sensitive.
667 Second and third arg RSTART and REND specify the region to operate on.
669 Interactively, in Transient Mark mode when the mark is active, operate
670 on the contents of the region. Otherwise, operate from point to the
671 end of (the accessible portion of) the buffer.
673 This function starts looking for the next match from the end of
674 the previous match. Hence, it ignores matches that overlap
675 a previously found match."
678 (keep-lines-read-args "How many matches for (regexp): "))
682 (goto-char (min rstart rend
))
683 (setq rend
(max rstart rend
)))
684 (if (and interactive transient-mark-mode mark-active
)
685 (setq rstart
(region-beginning)
692 (case-fold-search (and case-fold-search
693 (isearch-no-upper-case-p regexp t
))))
694 (while (and (< (point) rend
)
695 (progn (setq opoint
(point))
696 (re-search-forward regexp rend t
)))
697 (if (= opoint
(point))
699 (setq count
(1+ count
))))
700 (when interactive
(message "%d occurrence%s"
702 (if (= count
1) "" "s")))
706 (defvar occur-mode-map
707 (let ((map (make-sparse-keymap)))
708 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
709 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
710 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
711 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
712 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
713 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
714 (define-key map
"\M-n" 'occur-next
)
715 (define-key map
"\M-p" 'occur-prev
)
716 (define-key map
"r" 'occur-rename-buffer
)
717 (define-key map
"c" 'clone-buffer
)
718 (define-key map
"g" 'revert-buffer
)
719 (define-key map
"q" 'quit-window
)
720 (define-key map
"z" 'kill-this-buffer
)
721 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
723 "Keymap for `occur-mode'.")
725 (defvar occur-revert-arguments nil
726 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
727 See `occur-revert-function'.")
729 (defcustom occur-mode-hook
'(turn-on-font-lock)
730 "Hook run when entering Occur mode."
734 (defcustom occur-hook nil
735 "Hook run by Occur when there are any matches."
739 (put 'occur-mode
'mode-class
'special
)
741 "Major mode for output from \\[occur].
742 \\<occur-mode-map>Move point to one of the items in this buffer, then use
743 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
744 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
748 (kill-all-local-variables)
749 (use-local-map occur-mode-map
)
750 (setq major-mode
'occur-mode
)
751 (setq mode-name
"Occur")
752 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
753 (make-local-variable 'occur-revert-arguments
)
754 (add-hook 'change-major-mode-hook
'font-lock-defontify nil t
)
755 (setq next-error-function
'occur-next-error
)
756 (run-mode-hooks 'occur-mode-hook
))
758 (defun occur-revert-function (ignore1 ignore2
)
759 "Handle `revert-buffer' for Occur mode buffers."
760 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
762 (defun occur-mode-find-occurrence ()
763 (let ((pos (get-text-property (point) 'occur-target
)))
765 (error "No occurrence on this line"))
766 (unless (buffer-live-p (marker-buffer pos
))
767 (error "Buffer for this occurrence was killed"))
770 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
771 (defun occur-mode-goto-occurrence (&optional event
)
772 "Go to the occurrence the current line describes."
773 (interactive (list last-nonmenu-event
))
776 ;; Actually `event-end' works correctly with a nil argument as
777 ;; well, so we could dispense with this test, but let's not
778 ;; rely on this undocumented behavior.
779 (occur-mode-find-occurrence)
780 (with-current-buffer (window-buffer (posn-window (event-end event
)))
782 (goto-char (posn-point (event-end event
)))
783 (occur-mode-find-occurrence)))))
784 same-window-buffer-names
786 (pop-to-buffer (marker-buffer pos
))
789 (defun occur-mode-goto-occurrence-other-window ()
790 "Go to the occurrence the current line describes, in another window."
792 (let ((pos (occur-mode-find-occurrence)))
793 (switch-to-buffer-other-window (marker-buffer pos
))
796 (defun occur-mode-display-occurrence ()
797 "Display in another window the occurrence the current line describes."
799 (let ((pos (occur-mode-find-occurrence))
801 ;; Bind these to ensure `display-buffer' puts it in another window.
802 same-window-buffer-names
804 (setq window
(display-buffer (marker-buffer pos
)))
805 ;; This is the way to set point in the proper window.
806 (save-selected-window
807 (select-window window
)
810 (defun occur-find-match (n search message
)
811 (if (not n
) (setq n
1))
814 (setq r
(funcall search
(point) 'occur-match
))
816 (get-text-property r
'occur-match
)
817 (setq r
(funcall search r
'occur-match
)))
823 (defun occur-next (&optional n
)
824 "Move to the Nth (default 1) next match in an Occur mode buffer."
826 (occur-find-match n
#'next-single-property-change
"No more matches"))
828 (defun occur-prev (&optional n
)
829 "Move to the Nth (default 1) previous match in an Occur mode buffer."
831 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
833 (defun occur-next-error (&optional argp reset
)
834 "Move to the Nth (default 1) next match in an Occur mode buffer.
835 Compatibility function for \\[next-error] invocations."
837 ;; we need to run occur-find-match from within the Occur buffer
839 ;; Choose the buffer and make it current.
840 (if (next-error-buffer-p (current-buffer))
842 (next-error-find-buffer nil nil
844 (eq major-mode
'occur-mode
))))
846 (goto-char (cond (reset (point-min))
847 ((< argp
0) (line-beginning-position))
848 ((> argp
0) (line-end-position))
853 #'previous-single-property-change
854 #'next-single-property-change
)
856 ;; In case the *Occur* buffer is visible in a nonselected window.
857 (let ((win (get-buffer-window (current-buffer) t
)))
858 (if win
(set-window-point win
(point))))
859 (occur-mode-goto-occurrence)))
862 '((((class color
) (min-colors 88) (background light
))
863 :background
"yellow1")
864 (((class color
) (min-colors 88) (background dark
))
865 :background
"RoyalBlue3")
866 (((class color
) (min-colors 8) (background light
))
867 :background
"yellow" :foreground
"black")
868 (((class color
) (min-colors 8) (background dark
))
869 :background
"blue" :foreground
"white")
870 (((type tty
) (class mono
))
872 (t :background
"gray"))
873 "Face used to highlight matches permanently."
877 (defcustom list-matching-lines-default-context-lines
0
878 "*Default number of context lines included around `list-matching-lines' matches.
879 A negative number means to include that many lines before the match.
880 A positive number means to include that many lines both before and after."
884 (defalias 'list-matching-lines
'occur
)
886 (defcustom list-matching-lines-face
'match
887 "*Face used by \\[list-matching-lines] to show the text that matches.
888 If the value is nil, don't highlight the matching portions specially."
892 (defcustom list-matching-lines-buffer-name-face
'underline
893 "*Face used by \\[list-matching-lines] to show the names of buffers.
894 If the value is nil, don't highlight the buffer names specially."
898 (defcustom occur-excluded-properties
899 '(read-only invisible intangible field mouse-face help-echo local-map keymap
900 yank-handler follow-link
)
901 "*Text properties to discard when copying lines to the *Occur* buffer.
902 The value should be a list of text properties to discard or t,
903 which means to discard all text properties."
904 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
908 (defun occur-accumulate-lines (count &optional keep-props
)
910 (let ((forwardp (> count
0))
912 (while (not (or (zerop count
)
916 (setq count
(+ count
(if forwardp -
1 1)))
917 (setq beg
(line-beginning-position)
918 end
(line-end-position))
919 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
920 (text-property-not-all beg end
'fontified t
))
921 (if (fboundp 'jit-lock-fontify-now
)
922 (jit-lock-fontify-now beg end
)))
924 (if (and keep-props
(not (eq occur-excluded-properties t
)))
925 (let ((str (buffer-substring beg end
)))
926 (remove-list-of-text-properties
927 0 (length str
) occur-excluded-properties str
)
929 (buffer-substring-no-properties beg end
))
931 (forward-line (if forwardp
1 -
1)))
934 (defun occur-read-primary-args ()
935 (list (let* ((default (car regexp-history
))
937 (read-from-minibuffer
939 (format "List lines matching regexp (default %s): "
940 (query-replace-descr default
))
941 "List lines matching regexp: ")
950 (when current-prefix-arg
951 (prefix-numeric-value current-prefix-arg
))))
953 (defun occur-rename-buffer (&optional unique-p interactive-p
)
954 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
955 Here `original-buffer-name' is the buffer name were Occur was originally run.
956 When given the prefix argument, or called non-interactively, the renaming
957 will not clobber the existing buffer(s) of that name, but use
958 `generate-new-buffer-name' instead. You can add this to `occur-hook'
959 if you always want a separate *Occur* buffer for each buffer where you
963 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
964 (rename-buffer (concat "*Occur: "
965 (mapconcat #'buffer-name
966 (car (cddr occur-revert-arguments
)) "/")
968 (or unique-p
(not interactive-p
)))))
970 (defun occur (regexp &optional nlines
)
971 "Show all lines in the current buffer containing a match for REGEXP.
972 This function can not handle matches that span more than one line.
974 Each line is displayed with NLINES lines before and after, or -NLINES
975 before if NLINES is negative.
976 NLINES defaults to `list-matching-lines-default-context-lines'.
977 Interactively it is the prefix arg.
979 The lines are shown in a buffer named `*Occur*'.
980 It serves as a menu to find any of the occurrences in this buffer.
981 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
983 If REGEXP contains upper case characters (excluding those preceded by `\\'),
984 the matching is case-sensitive."
985 (interactive (occur-read-primary-args))
986 (occur-1 regexp nlines
(list (current-buffer))))
988 (defun multi-occur (bufs regexp
&optional nlines
)
989 "Show all lines in buffers BUFS containing a match for REGEXP.
990 This function acts on multiple buffers; otherwise, it is exactly like
991 `occur'. When you invoke this command interactively, you must specify
992 the buffer names that you want, one by one."
995 (let* ((bufs (list (read-buffer "First buffer to search: "
996 (current-buffer) t
)))
998 (ido-ignore-item-temp-list bufs
))
999 (while (not (string-equal
1000 (setq buf
(read-buffer
1001 (if (eq read-buffer-function
'ido-read-buffer
)
1002 "Next buffer to search (C-j to end): "
1003 "Next buffer to search (RET to end): ")
1006 (add-to-list 'bufs buf
)
1007 (setq ido-ignore-item-temp-list bufs
))
1008 (nreverse (mapcar #'get-buffer bufs
)))
1009 (occur-read-primary-args)))
1010 (occur-1 regexp nlines bufs
))
1012 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1013 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1014 Normally BUFREGEXP matches against each buffer's visited file name,
1015 but if you specify a prefix argument, it matches against the buffer name.
1016 See also `multi-occur'."
1019 (let* ((default (car regexp-history
))
1021 (read-from-minibuffer
1022 (if current-prefix-arg
1023 "List lines in buffers whose names match regexp: "
1024 "List lines in buffers whose filenames match regexp: ")
1029 (if (equal input
"")
1032 (occur-read-primary-args)))
1036 (mapcar (lambda (buf)
1038 (string-match bufregexp
1040 (and (buffer-file-name buf
)
1041 (string-match bufregexp
1042 (buffer-file-name buf
))))
1046 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1048 (setq buf-name
"*Occur*"))
1050 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1051 (when (buffer-live-p buf
) buf
))
1053 ;; Handle the case where one of the buffers we're searching is the
1054 ;; output buffer. Just rename it.
1055 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1056 (with-current-buffer (get-buffer buf-name
)
1059 ;; Now find or create the output buffer.
1060 ;; If we just renamed that buffer, we will make a new one here.
1061 (setq occur-buf
(get-buffer-create buf-name
))
1063 (with-current-buffer occur-buf
1065 (let ((inhibit-read-only t
)
1066 ;; Don't generate undo entries for creation of the initial contents.
1067 (buffer-undo-list t
))
1069 (let ((count (occur-engine
1070 regexp active-bufs occur-buf
1071 (or nlines list-matching-lines-default-context-lines
)
1072 (and case-fold-search
1073 (isearch-no-upper-case-p regexp t
))
1074 list-matching-lines-buffer-name-face
1075 nil list-matching-lines-face
1076 (not (eq occur-excluded-properties t
)))))
1077 (let* ((bufcount (length active-bufs
))
1078 (diff (- (length bufs
) bufcount
)))
1079 (message "Searched %d buffer%s%s; %s match%s for `%s'"
1080 bufcount
(if (= bufcount
1) "" "s")
1081 (if (zerop diff
) "" (format " (%d killed)" diff
))
1082 (if (zerop count
) "no" (format "%d" count
))
1083 (if (= count
1) "" "es")
1085 (setq occur-revert-arguments
(list regexp nlines bufs
))
1087 (kill-buffer occur-buf
)
1088 (display-buffer occur-buf
)
1089 (setq next-error-last-buffer occur-buf
)
1090 (setq buffer-read-only t
)
1091 (set-buffer-modified-p nil
)
1092 (run-hooks 'occur-hook
)))))))
1094 (defun occur-engine-add-prefix (lines)
1097 (concat " :" line
"\n"))
1100 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
1101 title-face prefix-face match-face keep-props
)
1102 (with-current-buffer out-buf
1103 (let ((globalcount 0)
1105 ;; Map over all the buffers
1106 (dolist (buf buffers
)
1107 (when (buffer-live-p buf
)
1108 (let ((matches 0) ;; count of matched lines
1109 (lines 1) ;; line count
1116 (inhibit-field-text-motion t
)
1117 (headerpt (with-current-buffer out-buf
(point))))
1118 (with-current-buffer buf
1120 ;; Set CODING only if the current buffer locally
1121 ;; binds buffer-file-coding-system.
1122 (not (local-variable-p 'buffer-file-coding-system
))
1123 (setq coding buffer-file-coding-system
))
1125 (goto-char (point-min)) ;; begin searching in the buffer
1127 (setq origpt
(point))
1128 (when (setq endpt
(re-search-forward regexp nil t
))
1129 (setq matches
(1+ matches
)) ;; increment match count
1130 (setq matchbeg
(match-beginning 0))
1131 (setq lines
(+ lines
(1- (count-lines origpt endpt
))))
1133 (goto-char matchbeg
)
1134 (setq begpt
(line-beginning-position)
1135 endpt
(line-end-position)))
1136 (setq marker
(make-marker))
1137 (set-marker marker matchbeg
)
1139 (if (boundp 'jit-lock-mode
) jit-lock-mode
)
1140 (text-property-not-all begpt endpt
'fontified t
))
1141 (if (fboundp 'jit-lock-fontify-now
)
1142 (jit-lock-fontify-now begpt endpt
)))
1143 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1145 (setq curstring
(buffer-substring begpt endpt
))
1146 (remove-list-of-text-properties
1147 0 (length curstring
) occur-excluded-properties curstring
))
1148 (setq curstring
(buffer-substring-no-properties begpt endpt
)))
1149 ;; Highlight the matches
1150 (let ((len (length curstring
))
1152 (while (and (< start len
)
1153 (string-match regexp curstring start
))
1154 (add-text-properties
1155 (match-beginning 0) (match-end 0)
1159 ;; Use `face' rather than `font-lock-face' here
1160 ;; so as to override faces copied from the buffer.
1161 `(face ,match-face
)))
1163 (setq start
(match-end 0))))
1164 ;; Generate the string to insert for this match
1167 ;; Using 7 digits aligns tabs properly.
1168 (apply #'propertize
(format "%7d:" lines
)
1171 `(font-lock-face prefix-face
))
1172 `(occur-prefix t mouse-face
(highlight)
1173 occur-target
,marker follow-link t
1174 help-echo
"mouse-2: go to this occurrence")))
1175 ;; We don't put `mouse-face' on the newline,
1176 ;; because that loses. And don't put it
1177 ;; on context lines to reduce flicker.
1178 (propertize curstring
'mouse-face
(list 'highlight
)
1179 'occur-target marker
1182 "mouse-2: go to this occurrence")
1183 ;; Add marker at eol, but no mouse props.
1184 (propertize "\n" 'occur-target marker
)))
1187 ;; The simple display style
1189 ;; The complex multi-line display
1190 ;; style. Generate a list of lines,
1191 ;; concatenate them all together.
1194 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ (abs nlines
))) keep-props
))))
1197 (occur-engine-add-prefix
1198 (cdr (occur-accumulate-lines (1+ nlines
) keep-props
)))))))))
1199 ;; Actually insert the match display data
1200 (with-current-buffer out-buf
1202 (end (progn (insert data
) (point))))
1203 (unless (= nlines
0)
1204 (insert "-------\n")))))
1208 (setq lines
(1+ lines
))
1209 ;; On to the next match...
1211 (goto-char (point-max))))))
1212 (when (not (zerop matches
)) ;; is the count zero?
1213 (setq globalcount
(+ globalcount matches
))
1214 (with-current-buffer out-buf
1215 (goto-char headerpt
)
1218 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1219 matches
(if (= matches
1) "" "es")
1220 regexp
(buffer-name buf
)))
1222 (add-text-properties beg end
1225 `(font-lock-face ,title-face
))
1226 `(occur-title ,buf
))))
1227 (goto-char (point-min)))))))
1229 ;; CODING is buffer-file-coding-system of the first buffer
1230 ;; that locally binds it. Let's use it also for the output
1232 (set-buffer-file-coding-system coding
))
1233 ;; Return the number of matches
1237 ;; It would be nice to use \\[...], but there is no reasonable way
1238 ;; to make that display both SPC and Y.
1239 (defconst query-replace-help
1240 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1241 RET or `q' to exit, Period to replace one match and exit,
1242 Comma to replace but not move point immediately,
1243 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1244 C-w to delete match and recursive edit,
1245 C-l to clear the screen, redisplay, and offer same replacement again,
1246 ! to replace all remaining matches with no more questions,
1247 ^ to move point back to previous match,
1248 E to edit the replacement string"
1249 "Help message while in `query-replace'.")
1251 (defvar query-replace-map
1252 (let ((map (make-sparse-keymap)))
1253 (define-key map
" " 'act
)
1254 (define-key map
"\d" 'skip
)
1255 (define-key map
[delete] 'skip)
1256 (define-key map [backspace] 'skip)
1257 (define-key map "y" 'act)
1258 (define-key map "n" 'skip)
1259 (define-key map "Y" 'act)
1260 (define-key map "N" 'skip)
1261 (define-key map "e" 'edit-replacement)
1262 (define-key map "E" 'edit-replacement)
1263 (define-key map "," 'act-and-show)
1264 (define-key map "q" 'exit)
1265 (define-key map "\r" 'exit)
1266 (define-key map [return] 'exit)
1267 (define-key map "." 'act-and-exit)
1268 (define-key map "\C-r" 'edit)
1269 (define-key map "\C-w" 'delete-and-edit)
1270 (define-key map "\C-l" 'recenter)
1271 (define-key map "!" 'automatic)
1272 (define-key map "^" 'backup)
1273 (define-key map "\C-h" 'help)
1274 (define-key map [f1] 'help)
1275 (define-key map [help] 'help)
1276 (define-key map "?" 'help)
1277 (define-key map "\C-g" 'quit)
1278 (define-key map "\C-]" 'quit)
1279 (define-key map "\e" 'exit-prefix)
1280 (define-key map [escape] 'exit-prefix)
1282 "Keymap that defines the responses to questions in `query-replace'.
1283 The \"bindings\" in this map are not commands; they are answers.
1284 The valid answers include `act', `skip', `act-and-show',
1285 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1286 `automatic', `backup', `exit-prefix', and `help'.")
1288 (defun replace-match-string-symbols (n)
1289 "Process a list (and any sub-lists), expanding certain symbols.
1291 N (match-string N) (where N is a string of digits)
1292 #N (string-to-number (match-string N))
1294 #& (string-to-number (match-string 0))
1297 Note that these symbols must be preceeded by a backslash in order to
1298 type them using Lisp syntax."
1302 (replace-match-string-symbols (car n))) ;Process sub-list
1304 (let ((name (symbol-name (car n))))
1306 ((string-match "^[0-9]+$" name)
1307 (setcar n (list 'match-string (string-to-number name))))
1308 ((string-match "^#[0-9]+$" name)
1309 (setcar n (list 'string-to-number
1311 (string-to-number (substring name 1))))))
1313 (setcar n '(match-string 0)))
1314 ((string= "#&" name)
1315 (setcar n '(string-to-number (match-string 0))))
1317 (setcar n 'replace-count))))))
1320 (defun replace-eval-replacement (expression replace-count)
1321 (let ((replacement (eval expression)))
1322 (if (stringp replacement)
1324 (prin1-to-string replacement t))))
1326 (defun replace-quote (replacement)
1327 "Quote a replacement string.
1328 This just doubles all backslashes in REPLACEMENT and
1329 returns the resulting string. If REPLACEMENT is not
1330 a string, it is first passed through `prin1-to-string'
1331 with the `noescape' argument set.
1333 `match-data' is preserved across the call."
1335 (replace-regexp-in-string "\\\\" "\\\\"
1336 (if (stringp replacement)
1338 (prin1-to-string replacement t))
1341 (defun replace-loop-through-replacements (data replace-count)
1342 ;; DATA is a vector contaning the following values:
1343 ;; 0 next-rotate-count
1345 ;; 2 next-replacement
1347 (if (= (aref data 0) replace-count)
1349 (aset data 0 (+ replace-count (aref data 1)))
1350 (let ((next (cdr (aref data 2))))
1351 (aset data 2 (if (consp next) next (aref data 3))))))
1352 (car (aref data 2)))
1354 (defun replace-match-data (integers reuse &optional new)
1355 "Like `match-data', but markers in REUSE get invalidated.
1356 If NEW is non-nil, it is set and returned instead of fresh data,
1357 but coerced to the correct value of INTEGERS."
1360 (set-match-data new)
1362 (eq (null integers) (markerp (car reuse)))
1364 (match-data integers reuse t)))
1366 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1367 "Make a replacement with `replace-match', editing `\\?'.
1368 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1369 check for `\\?' is made to save time. MATCH-DATA is used for the
1370 replacement. In case editing is done, it is changed to use markers.
1372 The return value is non-nil if there has been no `\\?' or NOEDIT was
1373 passed in. If LITERAL is set, no checking is done, anyway."
1374 (unless (or literal noedit)
1376 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1379 (read-string "Edit replacement string: "
1382 (replace-match "" t t newtext 3)
1383 (1+ (match-beginning 3)))
1386 nil match-data match-data))))
1388 (set-match-data match-data)
1389 (replace-match newtext fixedcase literal)
1392 (defun perform-replace (from-string replacements
1393 query-flag regexp-flag delimited-flag
1394 &optional repeat-count map start end)
1395 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1396 Don't use this in your own program unless you want to query and set the mark
1397 just as `query-replace' does. Instead, write a simple loop like this:
1399 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1400 (replace-match \"foobar\" nil nil))
1402 which will run faster and probably do exactly what you want. Please
1403 see the documentation of `replace-match' to find out how to simulate
1406 This function returns nil if and only if there were no matches to
1407 make, or the user didn't cancel the call."
1408 (or map (setq map query-replace-map))
1409 (and query-flag minibuffer-auto-raise
1410 (raise-frame (window-frame (minibuffer-window))))
1411 (let ((nocasify (not (and case-fold-search case-replace
1412 (string-equal from-string
1413 (downcase from-string)))))
1414 (case-fold-search (and case-fold-search
1415 (string-equal from-string
1416 (downcase from-string))))
1417 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1418 (search-function (if regexp-flag 're-search-forward 'search-forward))
1419 (search-string from-string)
1420 (real-match-data nil) ; the match data for the current match
1421 (next-replacement nil)
1422 ;; This is non-nil if we know there is nothing for the user
1423 ;; to edit in the replacement.
1428 (nonempty-match nil)
1430 ;; If non-nil, it is marker saying where in the buffer to stop.
1433 ;; Data for the next match. If a cons, it has the same format as
1434 ;; (match-data); otherwise it is t if a match is possible at point.
1440 (substitute-command-keys
1441 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1442 minibuffer-prompt-properties))))
1444 ;; If region is active, in Transient Mark mode, operate on region.
1446 (setq limit (copy-marker (max start end)))
1447 (goto-char (min start end))
1450 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1451 ;; containing a function and its first argument. The function is
1452 ;; called to generate each replacement like this:
1453 ;; (funcall (car replacements) (cdr replacements) replace-count)
1454 ;; It must return a string.
1456 ((stringp replacements)
1457 (setq next-replacement replacements
1459 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1460 (or repeat-count (setq repeat-count 1))
1461 (setq replacements (cons 'replace-loop-through-replacements
1462 (vector repeat-count repeat-count
1463 replacements replacements)))))
1466 (setq search-function 're-search-forward
1467 search-string (concat "\\b"
1468 (if regexp-flag from-string
1469 (regexp-quote from-string))
1471 (when query-replace-lazy-highlight
1472 (setq isearch-lazy-highlight-last-string nil))
1477 ;; Loop finding occurrences that perhaps should be replaced.
1478 (while (and keep-going
1479 (not (or (eobp) (and limit (>= (point) limit))))
1480 ;; Use the next match if it is already known;
1481 ;; otherwise, search for a match after moving forward
1482 ;; one char if progress is required.
1483 (setq real-match-data
1484 (cond ((consp match-again)
1485 (goto-char (nth 1 match-again))
1487 t real-match-data match-again))
1488 ;; MATCH-AGAIN non-nil means accept an
1492 (funcall search-function search-string
1494 ;; For speed, use only integers and
1495 ;; reuse the list used last time.
1496 (replace-match-data t real-match-data)))
1497 ((and (< (1+ (point)) (point-max))
1499 (< (1+ (point)) limit)))
1500 ;; If not accepting adjacent matches,
1501 ;; move one char to the right before
1502 ;; searching again. Undo the motion
1503 ;; if the search fails.
1504 (let ((opoint (point)))
1507 search-function search-string
1514 ;; Record whether the match is nonempty, to avoid an infinite loop
1515 ;; repeatedly matching the same empty string.
1516 (setq nonempty-match
1517 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1519 ;; If the match is empty, record that the next one can't be
1522 ;; Otherwise, if matching a regular expression, do the next
1523 ;; match now, since the replacement for this match may
1524 ;; affect whether the next match is adjacent to this one.
1525 ;; If that match is empty, don't use it.
1528 (or (not regexp-flag)
1529 (and (looking-at search-string)
1530 (let ((match (match-data)))
1531 (and (/= (nth 0 match) (nth 1 match))
1534 ;; Optionally ignore matches that have a read-only property.
1535 (unless (and query-replace-skip-read-only
1536 (text-property-not-all
1537 (nth 0 real-match-data) (nth 1 real-match-data)
1540 ;; Calculate the replacement string, if necessary.
1542 (set-match-data real-match-data)
1543 (setq next-replacement
1544 (funcall (car replacements) (cdr replacements)
1546 (if (not query-flag)
1547 (let ((inhibit-read-only
1548 query-replace-skip-read-only))
1549 (unless (or literal noedit)
1551 (nth 0 real-match-data) (nth 1 real-match-data)
1552 start end search-string
1553 (or delimited-flag regexp-flag) case-fold-search))
1555 (replace-match-maybe-edit
1556 next-replacement nocasify literal
1557 noedit real-match-data)
1558 replace-count (1+ replace-count)))
1560 (let (done replaced key def)
1561 ;; Loop reading commands until one of them sets done,
1562 ;; which means it has finished handling this
1563 ;; occurrence. Any command that sets `done' should
1564 ;; leave behind proper match data for the stack.
1565 ;; Commands not setting `done' need to adjust
1566 ;; `real-match-data'.
1568 (set-match-data real-match-data)
1570 (match-beginning 0) (match-end 0)
1571 start end search-string
1572 (or delimited-flag regexp-flag) case-fold-search)
1573 ;; Bind message-log-max so we don't fill up the message log
1574 ;; with a bunch of identical messages.
1575 (let ((message-log-max nil))
1577 (query-replace-descr from-string)
1578 (query-replace-descr next-replacement)))
1579 (setq key (read-event))
1580 ;; Necessary in case something happens during read-event
1581 ;; that clobbers the match data.
1582 (set-match-data real-match-data)
1583 (setq key (vector key))
1584 (setq def (lookup-key map key))
1585 ;; Restore the match data while we process the command.
1586 (cond ((eq def 'help)
1587 (with-output-to-temp-buffer "*Help*"
1589 (concat "Query replacing "
1590 (if regexp-flag "regexp " "")
1591 from-string " with "
1592 next-replacement ".\n\n"
1593 (substitute-command-keys
1594 query-replace-help)))
1595 (with-current-buffer standard-output
1598 (setq keep-going nil)
1602 (let ((elt (pop stack)))
1603 (goto-char (nth 0 elt))
1604 (setq replaced (nth 1 elt)
1609 (message "No previous match")
1610 (ding 'no-terminate)
1615 (replace-match-maybe-edit
1616 next-replacement nocasify literal
1617 noedit real-match-data)
1618 replace-count (1+ replace-count)))
1619 (setq done t replaced t))
1620 ((eq def 'act-and-exit)
1623 (replace-match-maybe-edit
1624 next-replacement nocasify literal
1625 noedit real-match-data)
1626 replace-count (1+ replace-count)))
1627 (setq keep-going nil)
1628 (setq done t replaced t))
1629 ((eq def 'act-and-show)
1632 (replace-match-maybe-edit
1633 next-replacement nocasify literal
1634 noedit real-match-data)
1635 replace-count (1+ replace-count)
1636 real-match-data (replace-match-data
1639 ((eq def 'automatic)
1642 (replace-match-maybe-edit
1643 next-replacement nocasify literal
1644 noedit real-match-data)
1645 replace-count (1+ replace-count)))
1646 (setq done t query-flag nil replaced t))
1652 (let ((opos (point-marker)))
1653 (setq real-match-data (replace-match-data
1656 (goto-char (match-beginning 0))
1658 (save-window-excursion
1661 (set-marker opos nil))
1662 ;; Before we make the replacement,
1663 ;; decide whether the search string
1664 ;; can match again just after this match.
1665 (if (and regexp-flag nonempty-match)
1666 (setq match-again (and (looking-at search-string)
1668 ;; Edit replacement.
1669 ((eq def 'edit-replacement)
1670 (setq real-match-data (replace-match-data
1674 (read-string "Edit replacement string: "
1678 (set-match-data real-match-data)
1680 (replace-match-maybe-edit
1681 next-replacement nocasify literal noedit
1686 ((eq def 'delete-and-edit)
1687 (replace-match "" t t)
1688 (setq real-match-data (replace-match-data
1689 nil real-match-data))
1690 (replace-dehighlight)
1691 (save-excursion (recursive-edit))
1693 ;; Note: we do not need to treat `exit-prefix'
1694 ;; specially here, since we reread
1695 ;; any unrecognized character.
1697 (setq this-command 'mode-exited)
1698 (setq keep-going nil)
1699 (setq unread-command-events
1700 (append (listify-key-sequence key)
1701 unread-command-events))
1703 (when query-replace-lazy-highlight
1704 ;; Force lazy rehighlighting only after replacements
1705 (if (not (memq def '(skip backup)))
1706 (setq isearch-lazy-highlight-last-string nil))))
1707 ;; Record previous position for ^ when we move on.
1708 ;; Change markers to numbers in the match data
1709 ;; since lots of markers slow down editing.
1710 (push (list (point) replaced
1711 ;;; If the replacement has already happened, all we need is the
1712 ;;; current match start and end. We could get this with a trivial
1714 ;;; (save-excursion (goto-char (match-beginning 0))
1715 ;;; (search-forward (match-string 0))
1717 ;;; if we really wanted to avoid manually constructing match data.
1718 ;;; Adding current-buffer is necessary so that match-data calls can
1719 ;;; return markers which are appropriate for editing.
1728 (replace-dehighlight))
1729 (or unread-command-events
1730 (message "Replaced %d occurrence%s"
1732 (if (= replace-count 1) "" "s")))
1733 (and keep-going stack)))
1735 (defvar replace-overlay nil)
1737 (defun replace-highlight (match-beg match-end range-beg range-end
1738 string regexp case-fold)
1739 (if query-replace-highlight
1741 (move-overlay replace-overlay match-beg match-end (current-buffer))
1742 (setq replace-overlay (make-overlay match-beg match-end))
1743 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
1744 (overlay-put replace-overlay 'face 'query-replace)))
1745 (if query-replace-lazy-highlight
1746 (let ((isearch-string string)
1747 (isearch-regexp regexp)
1748 (search-whitespace-regexp nil)
1749 (isearch-case-fold-search case-fold))
1750 (isearch-lazy-highlight-new-loop range-beg range-end))))
1752 (defun replace-dehighlight ()
1753 (when replace-overlay
1754 (delete-overlay replace-overlay))
1755 (when query-replace-lazy-highlight
1756 (lazy-highlight-cleanup lazy-highlight-cleanup)
1757 (setq isearch-lazy-highlight-last-string nil)))
1759 ;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1760 ;;; replace.el ends here