1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1992, 1994, 1996, 1997, 2000, 2001,
4 ;; 2002, 2003, 2004, 2005, 2006, 2007, 2008 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, separated
370 by spaces. This command works like `query-replace-regexp' except that
371 each successive replacement uses the next successive replacement string,
372 wrapping around from the last such string to the first.
374 In Transient Mark mode, if the mark is active, operate on the contents
375 of the region. Otherwise, operate from point to the end of the buffer.
377 Non-interactively, TO-STRINGS may be a list of replacement strings.
379 If `query-replace-interactive' is non-nil, the last incremental search
380 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
382 A prefix argument N says to use each replacement string N times
383 before rotating to the next.
384 Fourth and fifth arg START and END specify the region to operate on."
386 (let* ((from (if query-replace-interactive
387 (car regexp-search-ring
)
388 (read-from-minibuffer "Map query replace (regexp): "
390 'query-replace-history nil t
)))
391 (to (read-from-minibuffer
392 (format "Query replace %s with (space-separated strings): "
393 (query-replace-descr from
))
395 'query-replace-history from t
)))
397 (and current-prefix-arg
398 (prefix-numeric-value current-prefix-arg
))
399 (if (and transient-mark-mode mark-active
)
401 (if (and transient-mark-mode mark-active
)
404 (if (listp to-strings
)
405 (setq replacements to-strings
)
406 (while (/= (length to-strings
) 0)
407 (if (string-match " " to-strings
)
410 (list (substring to-strings
0
411 (string-match " " to-strings
))))
412 to-strings
(substring to-strings
413 (1+ (string-match " " to-strings
))))
414 (setq replacements
(append replacements
(list to-strings
))
416 (perform-replace regexp replacements t t nil n nil start end
)))
418 (defun replace-string (from-string to-string
&optional delimited start end
)
419 "Replace occurrences of FROM-STRING with TO-STRING.
420 Preserve case in each match if `case-replace' and `case-fold-search'
421 are non-nil and FROM-STRING has no uppercase letters.
422 \(Preserving case means that if the string matched is all caps, or capitalized,
423 then its replacement is upcased or capitalized.)
425 In Transient Mark mode, if the mark is active, operate on the contents
426 of the region. Otherwise, operate from point to the end of the buffer.
428 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
429 only matches surrounded by word boundaries.
430 Fourth and fifth arg START and END specify the region to operate on.
432 If `query-replace-interactive' is non-nil, the last incremental search
433 string is used as FROM-STRING--you don't have to specify it with the
436 This function is usually the wrong thing to use in a Lisp program.
437 What you probably want is a loop like this:
438 (while (search-forward FROM-STRING nil t)
439 (replace-match TO-STRING nil t))
440 which will run faster and will not set the mark or print anything.
441 \(You may need a more complex loop if FROM-STRING can match the null string
442 and TO-STRING is also null.)"
445 (query-replace-read-args
446 (if (and transient-mark-mode mark-active
)
447 "Replace string in region"
450 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
451 (if (and transient-mark-mode mark-active
)
453 (if (and transient-mark-mode mark-active
)
455 (perform-replace from-string to-string nil nil delimited nil nil start end
))
457 (defun replace-regexp (regexp to-string
&optional delimited start end
)
458 "Replace things after point matching REGEXP with TO-STRING.
459 Preserve case in each match if `case-replace' and `case-fold-search'
460 are non-nil and REGEXP has no uppercase letters.
462 In Transient Mark mode, if the mark is active, operate on the contents
463 of the region. Otherwise, operate from point to the end of the buffer.
465 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
466 only matches surrounded by word boundaries.
467 Fourth and fifth arg START and END specify the region to operate on.
469 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
470 and `\\=\\N' (where N is a digit) stands for
471 whatever what matched the Nth `\\(...\\)' in REGEXP.
472 `\\?' lets you edit the replacement text in the minibuffer
473 at the given position for each replacement.
475 In interactive calls, the replacement text may contain `\\,'
476 followed by a Lisp expression used as part of the replacement
477 text. Inside of that expression, `\\&' is a string denoting the
478 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
479 numeric values from `string-to-number', and `\\#' itself for
480 `replace-count', the number of replacements occurred so far.
482 If your Lisp expression is an identifier and the next letter in
483 the replacement string would be interpreted as part of it, you
484 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
485 for this particular case you may also enter `\\#' in the
486 replacement text directly.
488 When using those Lisp features interactively in the replacement
489 text, TO-STRING is actually made a list instead of a string.
490 Use \\[repeat-complex-command] after this command for details.
492 If `query-replace-interactive' is non-nil, the last incremental search
493 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
495 This function is usually the wrong thing to use in a Lisp program.
496 What you probably want is a loop like this:
497 (while (re-search-forward REGEXP nil t)
498 (replace-match TO-STRING nil nil))
499 which will run faster and will not set the mark or print anything."
502 (query-replace-read-args
503 (if (and transient-mark-mode mark-active
)
504 "Replace regexp in region"
507 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
508 (if (and transient-mark-mode mark-active
)
510 (if (and transient-mark-mode mark-active
)
512 (perform-replace regexp to-string nil t delimited nil nil start end
))
515 (defvar regexp-history nil
516 "History list for some commands that read regular expressions.
518 Maximum length of the history list is determined by the value
519 of `history-length', which see.")
522 (defalias 'delete-non-matching-lines
'keep-lines
)
523 (defalias 'delete-matching-lines
'flush-lines
)
524 (defalias 'count-matches
'how-many
)
527 (defun keep-lines-read-args (prompt)
528 "Read arguments for `keep-lines' and friends.
529 Prompt for a regexp with PROMPT.
530 Value is a list, (REGEXP)."
531 (list (read-from-minibuffer prompt nil nil nil
532 'regexp-history nil t
)
535 (defun keep-lines (regexp &optional rstart rend interactive
)
536 "Delete all lines except those containing matches for REGEXP.
537 A match split across lines preserves all the lines it lies in.
538 When called from Lisp (and usually interactively as well, see below)
539 applies to all lines starting after point.
541 If REGEXP contains upper case characters (excluding those preceded by `\\'),
542 the matching is case-sensitive.
544 Second and third arg RSTART and REND specify the region to operate on.
545 This command operates on (the accessible part of) all lines whose
546 accessible part is entirely contained in the region determined by RSTART
547 and REND. (A newline ending a line counts as part of that line.)
549 Interactively, in Transient Mark mode when the mark is active, operate
550 on all lines whose accessible part is entirely contained in the region.
551 Otherwise, the command applies to all lines starting after point.
552 When calling this function from Lisp, you can pretend that it was
553 called interactively by passing a non-nil INTERACTIVE argument.
555 This function starts looking for the next match from the end of
556 the previous match. Hence, it ignores matches that overlap
557 a previously found match."
561 (barf-if-buffer-read-only)
562 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
565 (goto-char (min rstart rend
))
569 (goto-char (max rstart rend
))
570 (unless (or (bolp) (eobp))
573 (if (and interactive transient-mark-mode mark-active
)
574 (setq rstart
(region-beginning)
576 (goto-char (region-end))
577 (unless (or (bolp) (eobp))
581 rend
(point-max-marker)))
584 (or (bolp) (forward-line 1))
585 (let ((start (point))
586 (case-fold-search (and case-fold-search
587 (isearch-no-upper-case-p regexp t
))))
588 (while (< (point) rend
)
589 ;; Start is first char not preserved by previous match.
590 (if (not (re-search-forward regexp rend
'move
))
591 (delete-region start rend
)
592 (let ((end (save-excursion (goto-char (match-beginning 0))
595 ;; Now end is first char preserved by the new match.
597 (delete-region start end
))))
599 (setq start
(save-excursion (forward-line 1) (point)))
600 ;; If the match was empty, avoid matching again at same place.
601 (and (< (point) rend
)
602 (= (match-beginning 0) (match-end 0))
604 (set-marker rend nil
)
608 (defun flush-lines (regexp &optional rstart rend interactive
)
609 "Delete lines containing matches for REGEXP.
610 When called from Lisp (and usually when called interactively as
611 well, see below), applies to the part of the buffer after point.
612 The line point is in is deleted if and only if it contains a
613 match for regexp starting after point.
615 If REGEXP contains upper case characters (excluding those preceded by `\\'),
616 the matching is case-sensitive.
618 Second and third arg RSTART and REND specify the region to operate on.
619 Lines partially contained in this region are deleted if and only if
620 they contain a match entirely contained in it.
622 Interactively, in Transient Mark mode when the mark is active, operate
623 on the contents of the region. Otherwise, operate from point to the
624 end of (the accessible portion of) the buffer. When calling this function
625 from Lisp, you can pretend that it was called interactively by passing
626 a non-nil INTERACTIVE argument.
628 If a match is split across lines, all the lines it lies in are deleted.
629 They are deleted _before_ looking for the next match. Hence, a match
630 starting on the same line at which another match ended is ignored."
634 (barf-if-buffer-read-only)
635 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
638 (goto-char (min rstart rend
))
639 (setq rend
(copy-marker (max rstart rend
))))
640 (if (and interactive transient-mark-mode mark-active
)
641 (setq rstart
(region-beginning)
642 rend
(copy-marker (region-end)))
644 rend
(point-max-marker)))
646 (let ((case-fold-search (and case-fold-search
647 (isearch-no-upper-case-p regexp t
))))
649 (while (and (< (point) rend
)
650 (re-search-forward regexp rend t
))
651 (delete-region (save-excursion (goto-char (match-beginning 0))
654 (progn (forward-line 1) (point))))))
655 (set-marker rend nil
)
659 (defun how-many (regexp &optional rstart rend interactive
)
660 "Print and return number of matches for REGEXP following point.
661 When called from Lisp and INTERACTIVE is omitted or nil, just return
662 the number, do not print it; if INTERACTIVE is t, the function behaves
663 in all respects has if it had been called interactively.
665 If REGEXP contains upper case characters (excluding those preceded by `\\'),
666 the matching is case-sensitive.
668 Second and third arg RSTART and REND specify the region to operate on.
670 Interactively, in Transient Mark mode when the mark is active, operate
671 on the contents of the region. Otherwise, operate from point to the
672 end of (the accessible portion of) the buffer.
674 This function starts looking for the next match from the end of
675 the previous match. Hence, it ignores matches that overlap
676 a previously found match."
679 (keep-lines-read-args "How many matches for (regexp): "))
683 (goto-char (min rstart rend
))
684 (setq rend
(max rstart rend
)))
685 (if (and interactive transient-mark-mode mark-active
)
686 (setq rstart
(region-beginning)
693 (case-fold-search (and case-fold-search
694 (isearch-no-upper-case-p regexp t
))))
695 (while (and (< (point) rend
)
696 (progn (setq opoint
(point))
697 (re-search-forward regexp rend t
)))
698 (if (= opoint
(point))
700 (setq count
(1+ count
))))
701 (when interactive
(message "%d occurrence%s"
703 (if (= count
1) "" "s")))
707 (defvar occur-mode-map
708 (let ((map (make-sparse-keymap)))
709 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
710 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
711 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
712 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
713 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
714 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
715 (define-key map
"\M-n" 'occur-next
)
716 (define-key map
"\M-p" 'occur-prev
)
717 (define-key map
"r" 'occur-rename-buffer
)
718 (define-key map
"c" 'clone-buffer
)
719 (define-key map
"g" 'revert-buffer
)
720 (define-key map
"q" 'quit-window
)
721 (define-key map
"z" 'kill-this-buffer
)
722 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
724 "Keymap for `occur-mode'.")
726 (defvar occur-revert-arguments nil
727 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
728 See `occur-revert-function'.")
730 (defcustom occur-mode-hook
'(turn-on-font-lock)
731 "Hook run when entering Occur mode."
735 (defcustom occur-hook nil
736 "Hook run by Occur when there are any matches."
740 (put 'occur-mode
'mode-class
'special
)
742 "Major mode for output from \\[occur].
743 \\<occur-mode-map>Move point to one of the items in this buffer, then use
744 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
745 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
749 (kill-all-local-variables)
750 (use-local-map occur-mode-map
)
751 (setq major-mode
'occur-mode
)
752 (setq mode-name
"Occur")
753 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
754 (make-local-variable 'occur-revert-arguments
)
755 (add-hook 'change-major-mode-hook
'font-lock-defontify nil t
)
756 (setq next-error-function
'occur-next-error
)
757 (run-mode-hooks 'occur-mode-hook
))
759 (defun occur-revert-function (ignore1 ignore2
)
760 "Handle `revert-buffer' for Occur mode buffers."
761 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
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 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
772 (defun occur-mode-goto-occurrence (&optional event
)
773 "Go to the occurrence the current line describes."
774 (interactive (list last-nonmenu-event
))
777 ;; Actually `event-end' works correctly with a nil argument as
778 ;; well, so we could dispense with this test, but let's not
779 ;; rely on this undocumented behavior.
780 (occur-mode-find-occurrence)
781 (with-current-buffer (window-buffer (posn-window (event-end event
)))
783 (goto-char (posn-point (event-end event
)))
784 (occur-mode-find-occurrence)))))
785 same-window-buffer-names
787 (pop-to-buffer (marker-buffer pos
))
790 (defun occur-mode-goto-occurrence-other-window ()
791 "Go to the occurrence the current line describes, in another window."
793 (let ((pos (occur-mode-find-occurrence)))
794 (switch-to-buffer-other-window (marker-buffer pos
))
797 (defun occur-mode-display-occurrence ()
798 "Display in another window the occurrence the current line describes."
800 (let ((pos (occur-mode-find-occurrence))
802 ;; Bind these to ensure `display-buffer' puts it in another window.
803 same-window-buffer-names
805 (setq window
(display-buffer (marker-buffer pos
)))
806 ;; This is the way to set point in the proper window.
807 (save-selected-window
808 (select-window window
)
811 (defun occur-find-match (n search message
)
812 (if (not n
) (setq n
1))
815 (setq r
(funcall search
(point) 'occur-match
))
817 (get-text-property r
'occur-match
)
818 (setq r
(funcall search r
'occur-match
)))
824 (defun occur-next (&optional n
)
825 "Move to the Nth (default 1) next match in an Occur mode buffer."
827 (occur-find-match n
#'next-single-property-change
"No more matches"))
829 (defun occur-prev (&optional n
)
830 "Move to the Nth (default 1) previous match in an Occur mode buffer."
832 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
834 (defun occur-next-error (&optional argp reset
)
835 "Move to the Nth (default 1) next match in an Occur mode buffer.
836 Compatibility function for \\[next-error] invocations."
838 ;; we need to run occur-find-match from within the Occur buffer
840 ;; Choose the buffer and make it current.
841 (if (next-error-buffer-p (current-buffer))
843 (next-error-find-buffer nil nil
845 (eq major-mode
'occur-mode
))))
847 (goto-char (cond (reset (point-min))
848 ((< argp
0) (line-beginning-position))
849 ((> argp
0) (line-end-position))
854 #'previous-single-property-change
855 #'next-single-property-change
)
857 ;; In case the *Occur* buffer is visible in a nonselected window.
858 (let ((win (get-buffer-window (current-buffer) t
)))
859 (if win
(set-window-point win
(point))))
860 (occur-mode-goto-occurrence)))
863 '((((class color
) (min-colors 88) (background light
))
864 :background
"yellow1")
865 (((class color
) (min-colors 88) (background dark
))
866 :background
"RoyalBlue3")
867 (((class color
) (min-colors 8) (background light
))
868 :background
"yellow" :foreground
"black")
869 (((class color
) (min-colors 8) (background dark
))
870 :background
"blue" :foreground
"white")
871 (((type tty
) (class mono
))
873 (t :background
"gray"))
874 "Face used to highlight matches permanently."
878 (defcustom list-matching-lines-default-context-lines
0
879 "*Default number of context lines included around `list-matching-lines' matches.
880 A negative number means to include that many lines before the match.
881 A positive number means to include that many lines both before and after."
885 (defalias 'list-matching-lines
'occur
)
887 (defcustom list-matching-lines-face
'match
888 "*Face used by \\[list-matching-lines] to show the text that matches.
889 If the value is nil, don't highlight the matching portions specially."
893 (defcustom list-matching-lines-buffer-name-face
'underline
894 "*Face used by \\[list-matching-lines] to show the names of buffers.
895 If the value is nil, don't highlight the buffer names specially."
899 (defcustom occur-excluded-properties
900 '(read-only invisible intangible field mouse-face help-echo local-map keymap
901 yank-handler follow-link
)
902 "*Text properties to discard when copying lines to the *Occur* buffer.
903 The value should be a list of text properties to discard or t,
904 which means to discard all text properties."
905 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
909 (defun occur-accumulate-lines (count &optional keep-props
)
911 (let ((forwardp (> count
0))
913 (while (not (or (zerop count
)
917 (setq count
(+ count
(if forwardp -
1 1)))
918 (setq beg
(line-beginning-position)
919 end
(line-end-position))
920 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
921 (text-property-not-all beg end
'fontified t
))
922 (if (fboundp 'jit-lock-fontify-now
)
923 (jit-lock-fontify-now beg end
)))
925 (if (and keep-props
(not (eq occur-excluded-properties t
)))
926 (let ((str (buffer-substring beg end
)))
927 (remove-list-of-text-properties
928 0 (length str
) occur-excluded-properties str
)
930 (buffer-substring-no-properties beg end
))
932 (forward-line (if forwardp
1 -
1)))
935 (defun occur-read-primary-args ()
936 (list (let* ((default (car regexp-history
))
938 (read-from-minibuffer
940 (format "List lines matching regexp (default %s): "
941 (query-replace-descr default
))
942 "List lines matching regexp: ")
951 (when current-prefix-arg
952 (prefix-numeric-value current-prefix-arg
))))
954 (defun occur-rename-buffer (&optional unique-p interactive-p
)
955 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
956 Here `original-buffer-name' is the buffer name were Occur was originally run.
957 When given the prefix argument, or called non-interactively, the renaming
958 will not clobber the existing buffer(s) of that name, but use
959 `generate-new-buffer-name' instead. You can add this to `occur-hook'
960 if you always want a separate *Occur* buffer for each buffer where you
964 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
965 (rename-buffer (concat "*Occur: "
966 (mapconcat #'buffer-name
967 (car (cddr occur-revert-arguments
)) "/")
969 (or unique-p
(not interactive-p
)))))
971 (defun occur (regexp &optional nlines
)
972 "Show all lines in the current buffer containing a match for REGEXP.
973 This function can not handle matches that span more than one line.
975 Each line is displayed with NLINES lines before and after, or -NLINES
976 before if NLINES is negative.
977 NLINES defaults to `list-matching-lines-default-context-lines'.
978 Interactively it is the prefix arg.
980 The lines are shown in a buffer named `*Occur*'.
981 It serves as a menu to find any of the occurrences in this buffer.
982 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
984 If REGEXP contains upper case characters (excluding those preceded by `\\'),
985 the matching is case-sensitive."
986 (interactive (occur-read-primary-args))
987 (occur-1 regexp nlines
(list (current-buffer))))
989 (defun multi-occur (bufs regexp
&optional nlines
)
990 "Show all lines in buffers BUFS containing a match for REGEXP.
991 This function acts on multiple buffers; otherwise, it is exactly like
992 `occur'. When you invoke this command interactively, you must specify
993 the buffer names that you want, one by one."
996 (let* ((bufs (list (read-buffer "First buffer to search: "
997 (current-buffer) t
)))
999 (ido-ignore-item-temp-list bufs
))
1000 (while (not (string-equal
1001 (setq buf
(read-buffer
1002 (if (eq read-buffer-function
'ido-read-buffer
)
1003 "Next buffer to search (C-j to end): "
1004 "Next buffer to search (RET to end): ")
1007 (add-to-list 'bufs buf
)
1008 (setq ido-ignore-item-temp-list bufs
))
1009 (nreverse (mapcar #'get-buffer bufs
)))
1010 (occur-read-primary-args)))
1011 (occur-1 regexp nlines bufs
))
1013 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1014 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1015 Normally BUFREGEXP matches against each buffer's visited file name,
1016 but if you specify a prefix argument, it matches against the buffer name.
1017 See also `multi-occur'."
1020 (let* ((default (car regexp-history
))
1022 (read-from-minibuffer
1023 (if current-prefix-arg
1024 "List lines in buffers whose names match regexp: "
1025 "List lines in buffers whose filenames match regexp: ")
1030 (if (equal input
"")
1033 (occur-read-primary-args)))
1037 (mapcar (lambda (buf)
1039 (string-match bufregexp
1041 (and (buffer-file-name buf
)
1042 (string-match bufregexp
1043 (buffer-file-name buf
))))
1047 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1049 (setq buf-name
"*Occur*"))
1051 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1052 (when (buffer-live-p buf
) buf
))
1054 ;; Handle the case where one of the buffers we're searching is the
1055 ;; output buffer. Just rename it.
1056 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1057 (with-current-buffer (get-buffer buf-name
)
1060 ;; Now find or create the output buffer.
1061 ;; If we just renamed that buffer, we will make a new one here.
1062 (setq occur-buf
(get-buffer-create buf-name
))
1064 (with-current-buffer occur-buf
1066 (let ((inhibit-read-only t
)
1067 ;; Don't generate undo entries for creation of the initial contents.
1068 (buffer-undo-list t
))
1070 (let ((count (occur-engine
1071 regexp active-bufs occur-buf
1072 (or nlines list-matching-lines-default-context-lines
)
1073 (and case-fold-search
1074 (isearch-no-upper-case-p regexp t
))
1075 list-matching-lines-buffer-name-face
1076 nil list-matching-lines-face
1077 (not (eq occur-excluded-properties t
)))))
1078 (let* ((bufcount (length active-bufs
))
1079 (diff (- (length bufs
) bufcount
)))
1080 (message "Searched %d buffer%s%s; %s match%s for `%s'"
1081 bufcount
(if (= bufcount
1) "" "s")
1082 (if (zerop diff
) "" (format " (%d killed)" diff
))
1083 (if (zerop count
) "no" (format "%d" count
))
1084 (if (= count
1) "" "es")
1086 (setq occur-revert-arguments
(list regexp nlines bufs
))
1088 (kill-buffer occur-buf
)
1089 (display-buffer occur-buf
)
1090 (setq next-error-last-buffer occur-buf
)
1091 (setq buffer-read-only t
)
1092 (set-buffer-modified-p nil
)
1093 (run-hooks 'occur-hook
)))))))
1095 (defun occur-engine-add-prefix (lines)
1098 (concat " :" line
"\n"))
1101 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
1102 title-face prefix-face match-face keep-props
)
1103 (with-current-buffer out-buf
1104 (let ((globalcount 0)
1106 ;; Map over all the buffers
1107 (dolist (buf buffers
)
1108 (when (buffer-live-p buf
)
1109 (let ((matches 0) ;; count of matched lines
1110 (lines 1) ;; line count
1117 (inhibit-field-text-motion t
)
1118 (headerpt (with-current-buffer out-buf
(point))))
1119 (with-current-buffer buf
1121 ;; Set CODING only if the current buffer locally
1122 ;; binds buffer-file-coding-system.
1123 (not (local-variable-p 'buffer-file-coding-system
))
1124 (setq coding buffer-file-coding-system
))
1126 (goto-char (point-min)) ;; begin searching in the buffer
1128 (setq origpt
(point))
1129 (when (setq endpt
(re-search-forward regexp nil t
))
1130 (setq matches
(1+ matches
)) ;; increment match count
1131 (setq matchbeg
(match-beginning 0))
1132 (setq lines
(+ lines
(1- (count-lines origpt endpt
))))
1134 (goto-char matchbeg
)
1135 (setq begpt
(line-beginning-position)
1136 endpt
(line-end-position)))
1137 (setq marker
(make-marker))
1138 (set-marker marker matchbeg
)
1140 (if (boundp 'jit-lock-mode
) jit-lock-mode
)
1141 (text-property-not-all begpt endpt
'fontified t
))
1142 (if (fboundp 'jit-lock-fontify-now
)
1143 (jit-lock-fontify-now begpt endpt
)))
1144 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1146 (setq curstring
(buffer-substring begpt endpt
))
1147 (remove-list-of-text-properties
1148 0 (length curstring
) occur-excluded-properties curstring
))
1149 (setq curstring
(buffer-substring-no-properties begpt endpt
)))
1150 ;; Highlight the matches
1151 (let ((len (length curstring
))
1153 (while (and (< start len
)
1154 (string-match regexp curstring start
))
1155 (add-text-properties
1156 (match-beginning 0) (match-end 0)
1160 ;; Use `face' rather than `font-lock-face' here
1161 ;; so as to override faces copied from the buffer.
1162 `(face ,match-face
)))
1164 (setq start
(match-end 0))))
1165 ;; Generate the string to insert for this match
1168 ;; Using 7 digits aligns tabs properly.
1169 (apply #'propertize
(format "%7d:" lines
)
1172 `(font-lock-face prefix-face
))
1173 `(occur-prefix t mouse-face
(highlight)
1174 occur-target
,marker follow-link t
1175 help-echo
"mouse-2: go to this occurrence")))
1176 ;; We don't put `mouse-face' on the newline,
1177 ;; because that loses. And don't put it
1178 ;; on context lines to reduce flicker.
1179 (propertize curstring
'mouse-face
(list 'highlight
)
1180 'occur-target marker
1183 "mouse-2: go to this occurrence")
1184 ;; Add marker at eol, but no mouse props.
1185 (propertize "\n" 'occur-target marker
)))
1188 ;; The simple display style
1190 ;; The complex multi-line display
1191 ;; style. Generate a list of lines,
1192 ;; concatenate them all together.
1195 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ (abs nlines
))) keep-props
))))
1198 (occur-engine-add-prefix
1199 (cdr (occur-accumulate-lines (1+ nlines
) keep-props
)))))))))
1200 ;; Actually insert the match display data
1201 (with-current-buffer out-buf
1203 (end (progn (insert data
) (point))))
1204 (unless (= nlines
0)
1205 (insert "-------\n")))))
1209 (setq lines
(1+ lines
))
1210 ;; On to the next match...
1212 (goto-char (point-max))))))
1213 (when (not (zerop matches
)) ;; is the count zero?
1214 (setq globalcount
(+ globalcount matches
))
1215 (with-current-buffer out-buf
1216 (goto-char headerpt
)
1219 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1220 matches
(if (= matches
1) "" "es")
1221 regexp
(buffer-name buf
)))
1223 (add-text-properties beg end
1226 `(font-lock-face ,title-face
))
1227 `(occur-title ,buf
))))
1228 (goto-char (point-min)))))))
1230 ;; CODING is buffer-file-coding-system of the first buffer
1231 ;; that locally binds it. Let's use it also for the output
1233 (set-buffer-file-coding-system coding
))
1234 ;; Return the number of matches
1238 ;; It would be nice to use \\[...], but there is no reasonable way
1239 ;; to make that display both SPC and Y.
1240 (defconst query-replace-help
1241 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1242 RET or `q' to exit, Period to replace one match and exit,
1243 Comma to replace but not move point immediately,
1244 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1245 C-w to delete match and recursive edit,
1246 C-l to clear the screen, redisplay, and offer same replacement again,
1247 ! to replace all remaining matches with no more questions,
1248 ^ to move point back to previous match,
1249 E to edit the replacement string"
1250 "Help message while in `query-replace'.")
1252 (defvar query-replace-map
1253 (let ((map (make-sparse-keymap)))
1254 (define-key map
" " 'act
)
1255 (define-key map
"\d" 'skip
)
1256 (define-key map
[delete] 'skip)
1257 (define-key map [backspace] 'skip)
1258 (define-key map "y" 'act)
1259 (define-key map "n" 'skip)
1260 (define-key map "Y" 'act)
1261 (define-key map "N" 'skip)
1262 (define-key map "e" 'edit-replacement)
1263 (define-key map "E" 'edit-replacement)
1264 (define-key map "," 'act-and-show)
1265 (define-key map "q" 'exit)
1266 (define-key map "\r" 'exit)
1267 (define-key map [return] 'exit)
1268 (define-key map "." 'act-and-exit)
1269 (define-key map "\C-r" 'edit)
1270 (define-key map "\C-w" 'delete-and-edit)
1271 (define-key map "\C-l" 'recenter)
1272 (define-key map "!" 'automatic)
1273 (define-key map "^" 'backup)
1274 (define-key map "\C-h" 'help)
1275 (define-key map [f1] 'help)
1276 (define-key map [help] 'help)
1277 (define-key map "?" 'help)
1278 (define-key map "\C-g" 'quit)
1279 (define-key map "\C-]" 'quit)
1280 (define-key map "\e" 'exit-prefix)
1281 (define-key map [escape] 'exit-prefix)
1283 "Keymap that defines the responses to questions in `query-replace'.
1284 The \"bindings\" in this map are not commands; they are answers.
1285 The valid answers include `act', `skip', `act-and-show',
1286 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1287 `automatic', `backup', `exit-prefix', and `help'.")
1289 (defun replace-match-string-symbols (n)
1290 "Process a list (and any sub-lists), expanding certain symbols.
1292 N (match-string N) (where N is a string of digits)
1293 #N (string-to-number (match-string N))
1295 #& (string-to-number (match-string 0))
1298 Note that these symbols must be preceeded by a backslash in order to
1299 type them using Lisp syntax."
1303 (replace-match-string-symbols (car n))) ;Process sub-list
1305 (let ((name (symbol-name (car n))))
1307 ((string-match "^[0-9]+$" name)
1308 (setcar n (list 'match-string (string-to-number name))))
1309 ((string-match "^#[0-9]+$" name)
1310 (setcar n (list 'string-to-number
1312 (string-to-number (substring name 1))))))
1314 (setcar n '(match-string 0)))
1315 ((string= "#&" name)
1316 (setcar n '(string-to-number (match-string 0))))
1318 (setcar n 'replace-count))))))
1321 (defun replace-eval-replacement (expression replace-count)
1322 (let ((replacement (eval expression)))
1323 (if (stringp replacement)
1325 (prin1-to-string replacement t))))
1327 (defun replace-quote (replacement)
1328 "Quote a replacement string.
1329 This just doubles all backslashes in REPLACEMENT and
1330 returns the resulting string. If REPLACEMENT is not
1331 a string, it is first passed through `prin1-to-string'
1332 with the `noescape' argument set.
1334 `match-data' is preserved across the call."
1336 (replace-regexp-in-string "\\\\" "\\\\"
1337 (if (stringp replacement)
1339 (prin1-to-string replacement t))
1342 (defun replace-loop-through-replacements (data replace-count)
1343 ;; DATA is a vector contaning the following values:
1344 ;; 0 next-rotate-count
1346 ;; 2 next-replacement
1348 (if (= (aref data 0) replace-count)
1350 (aset data 0 (+ replace-count (aref data 1)))
1351 (let ((next (cdr (aref data 2))))
1352 (aset data 2 (if (consp next) next (aref data 3))))))
1353 (car (aref data 2)))
1355 (defun replace-match-data (integers reuse &optional new)
1356 "Like `match-data', but markers in REUSE get invalidated.
1357 If NEW is non-nil, it is set and returned instead of fresh data,
1358 but coerced to the correct value of INTEGERS."
1361 (set-match-data new)
1363 (eq (null integers) (markerp (car reuse)))
1365 (match-data integers reuse t)))
1367 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1368 "Make a replacement with `replace-match', editing `\\?'.
1369 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1370 check for `\\?' is made to save time. MATCH-DATA is used for the
1371 replacement. In case editing is done, it is changed to use markers.
1373 The return value is non-nil if there has been no `\\?' or NOEDIT was
1374 passed in. If LITERAL is set, no checking is done, anyway."
1375 (unless (or literal noedit)
1377 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1380 (read-string "Edit replacement string: "
1383 (replace-match "" t t newtext 3)
1384 (1+ (match-beginning 3)))
1387 nil match-data match-data))))
1389 (set-match-data match-data)
1390 (replace-match newtext fixedcase literal)
1393 (defun perform-replace (from-string replacements
1394 query-flag regexp-flag delimited-flag
1395 &optional repeat-count map start end)
1396 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1397 Don't use this in your own program unless you want to query and set the mark
1398 just as `query-replace' does. Instead, write a simple loop like this:
1400 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1401 (replace-match \"foobar\" nil nil))
1403 which will run faster and probably do exactly what you want. Please
1404 see the documentation of `replace-match' to find out how to simulate
1407 This function returns nil if and only if there were no matches to
1408 make, or the user didn't cancel the call."
1409 (or map (setq map query-replace-map))
1410 (and query-flag minibuffer-auto-raise
1411 (raise-frame (window-frame (minibuffer-window))))
1412 (let ((nocasify (not (and case-fold-search case-replace
1413 (string-equal from-string
1414 (downcase from-string)))))
1415 (case-fold-search (and case-fold-search
1416 (string-equal from-string
1417 (downcase from-string))))
1418 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1419 (search-function (if regexp-flag 're-search-forward 'search-forward))
1420 (search-string from-string)
1421 (real-match-data nil) ; the match data for the current match
1422 (next-replacement nil)
1423 ;; This is non-nil if we know there is nothing for the user
1424 ;; to edit in the replacement.
1429 (nonempty-match nil)
1431 ;; If non-nil, it is marker saying where in the buffer to stop.
1434 ;; Data for the next match. If a cons, it has the same format as
1435 ;; (match-data); otherwise it is t if a match is possible at point.
1441 (substitute-command-keys
1442 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1443 minibuffer-prompt-properties))))
1445 ;; If region is active, in Transient Mark mode, operate on region.
1447 (setq limit (copy-marker (max start end)))
1448 (goto-char (min start end))
1451 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1452 ;; containing a function and its first argument. The function is
1453 ;; called to generate each replacement like this:
1454 ;; (funcall (car replacements) (cdr replacements) replace-count)
1455 ;; It must return a string.
1457 ((stringp replacements)
1458 (setq next-replacement replacements
1460 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1461 (or repeat-count (setq repeat-count 1))
1462 (setq replacements (cons 'replace-loop-through-replacements
1463 (vector repeat-count repeat-count
1464 replacements replacements)))))
1467 (setq search-function 're-search-forward
1468 search-string (concat "\\b"
1469 (if regexp-flag from-string
1470 (regexp-quote from-string))
1472 (when query-replace-lazy-highlight
1473 (setq isearch-lazy-highlight-last-string nil))
1478 ;; Loop finding occurrences that perhaps should be replaced.
1479 (while (and keep-going
1480 (not (or (eobp) (and limit (>= (point) limit))))
1481 ;; Use the next match if it is already known;
1482 ;; otherwise, search for a match after moving forward
1483 ;; one char if progress is required.
1484 (setq real-match-data
1485 (cond ((consp match-again)
1486 (goto-char (nth 1 match-again))
1488 t real-match-data match-again))
1489 ;; MATCH-AGAIN non-nil means accept an
1493 (funcall search-function search-string
1495 ;; For speed, use only integers and
1496 ;; reuse the list used last time.
1497 (replace-match-data t real-match-data)))
1498 ((and (< (1+ (point)) (point-max))
1500 (< (1+ (point)) limit)))
1501 ;; If not accepting adjacent matches,
1502 ;; move one char to the right before
1503 ;; searching again. Undo the motion
1504 ;; if the search fails.
1505 (let ((opoint (point)))
1508 search-function search-string
1515 ;; Record whether the match is nonempty, to avoid an infinite loop
1516 ;; repeatedly matching the same empty string.
1517 (setq nonempty-match
1518 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1520 ;; If the match is empty, record that the next one can't be
1523 ;; Otherwise, if matching a regular expression, do the next
1524 ;; match now, since the replacement for this match may
1525 ;; affect whether the next match is adjacent to this one.
1526 ;; If that match is empty, don't use it.
1529 (or (not regexp-flag)
1530 (and (looking-at search-string)
1531 (let ((match (match-data)))
1532 (and (/= (nth 0 match) (nth 1 match))
1535 ;; Optionally ignore matches that have a read-only property.
1536 (unless (and query-replace-skip-read-only
1537 (text-property-not-all
1538 (nth 0 real-match-data) (nth 1 real-match-data)
1541 ;; Calculate the replacement string, if necessary.
1543 (set-match-data real-match-data)
1544 (setq next-replacement
1545 (funcall (car replacements) (cdr replacements)
1547 (if (not query-flag)
1548 (let ((inhibit-read-only
1549 query-replace-skip-read-only))
1550 (unless (or literal noedit)
1552 (nth 0 real-match-data) (nth 1 real-match-data)
1553 start end search-string
1554 (or delimited-flag regexp-flag) case-fold-search))
1556 (replace-match-maybe-edit
1557 next-replacement nocasify literal
1558 noedit real-match-data)
1559 replace-count (1+ replace-count)))
1561 (let (done replaced key def)
1562 ;; Loop reading commands until one of them sets done,
1563 ;; which means it has finished handling this
1564 ;; occurrence. Any command that sets `done' should
1565 ;; leave behind proper match data for the stack.
1566 ;; Commands not setting `done' need to adjust
1567 ;; `real-match-data'.
1569 (set-match-data real-match-data)
1571 (match-beginning 0) (match-end 0)
1572 start end search-string
1573 (or delimited-flag regexp-flag) case-fold-search)
1574 ;; Bind message-log-max so we don't fill up the message log
1575 ;; with a bunch of identical messages.
1576 (let ((message-log-max nil))
1578 (query-replace-descr from-string)
1579 (query-replace-descr next-replacement)))
1580 (setq key (read-event))
1581 ;; Necessary in case something happens during read-event
1582 ;; that clobbers the match data.
1583 (set-match-data real-match-data)
1584 (setq key (vector key))
1585 (setq def (lookup-key map key))
1586 ;; Restore the match data while we process the command.
1587 (cond ((eq def 'help)
1588 (with-output-to-temp-buffer "*Help*"
1590 (concat "Query replacing "
1591 (if regexp-flag "regexp " "")
1592 from-string " with "
1593 next-replacement ".\n\n"
1594 (substitute-command-keys
1595 query-replace-help)))
1596 (with-current-buffer standard-output
1599 (setq keep-going nil)
1603 (let ((elt (pop stack)))
1604 (goto-char (nth 0 elt))
1605 (setq replaced (nth 1 elt)
1610 (message "No previous match")
1611 (ding 'no-terminate)
1616 (replace-match-maybe-edit
1617 next-replacement nocasify literal
1618 noedit real-match-data)
1619 replace-count (1+ replace-count)))
1620 (setq done t replaced t))
1621 ((eq def 'act-and-exit)
1624 (replace-match-maybe-edit
1625 next-replacement nocasify literal
1626 noedit real-match-data)
1627 replace-count (1+ replace-count)))
1628 (setq keep-going nil)
1629 (setq done t replaced t))
1630 ((eq def 'act-and-show)
1633 (replace-match-maybe-edit
1634 next-replacement nocasify literal
1635 noedit real-match-data)
1636 replace-count (1+ replace-count)
1637 real-match-data (replace-match-data
1640 ((eq def 'automatic)
1643 (replace-match-maybe-edit
1644 next-replacement nocasify literal
1645 noedit real-match-data)
1646 replace-count (1+ replace-count)))
1647 (setq done t query-flag nil replaced t))
1653 (let ((opos (point-marker)))
1654 (setq real-match-data (replace-match-data
1657 (goto-char (match-beginning 0))
1659 (save-window-excursion
1662 (set-marker opos nil))
1663 ;; Before we make the replacement,
1664 ;; decide whether the search string
1665 ;; can match again just after this match.
1666 (if (and regexp-flag nonempty-match)
1667 (setq match-again (and (looking-at search-string)
1669 ;; Edit replacement.
1670 ((eq def 'edit-replacement)
1671 (setq real-match-data (replace-match-data
1675 (read-string "Edit replacement string: "
1679 (set-match-data real-match-data)
1681 (replace-match-maybe-edit
1682 next-replacement nocasify literal noedit
1687 ((eq def 'delete-and-edit)
1688 (replace-match "" t t)
1689 (setq real-match-data (replace-match-data
1690 nil real-match-data))
1691 (replace-dehighlight)
1692 (save-excursion (recursive-edit))
1694 ;; Note: we do not need to treat `exit-prefix'
1695 ;; specially here, since we reread
1696 ;; any unrecognized character.
1698 (setq this-command 'mode-exited)
1699 (setq keep-going nil)
1700 (setq unread-command-events
1701 (append (listify-key-sequence key)
1702 unread-command-events))
1704 (when query-replace-lazy-highlight
1705 ;; Force lazy rehighlighting only after replacements
1706 (if (not (memq def '(skip backup)))
1707 (setq isearch-lazy-highlight-last-string nil))))
1708 ;; Record previous position for ^ when we move on.
1709 ;; Change markers to numbers in the match data
1710 ;; since lots of markers slow down editing.
1711 (push (list (point) replaced
1712 ;;; If the replacement has already happened, all we need is the
1713 ;;; current match start and end. We could get this with a trivial
1715 ;;; (save-excursion (goto-char (match-beginning 0))
1716 ;;; (search-forward (match-string 0))
1718 ;;; if we really wanted to avoid manually constructing match data.
1719 ;;; Adding current-buffer is necessary so that match-data calls can
1720 ;;; return markers which are appropriate for editing.
1729 (replace-dehighlight))
1730 (or unread-command-events
1731 (message "Replaced %d occurrence%s"
1733 (if (= replace-count 1) "" "s")))
1734 (and keep-going stack)))
1736 (defvar replace-overlay nil)
1738 (defun replace-highlight (match-beg match-end range-beg range-end
1739 string regexp case-fold)
1740 (if query-replace-highlight
1742 (move-overlay replace-overlay match-beg match-end (current-buffer))
1743 (setq replace-overlay (make-overlay match-beg match-end))
1744 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
1745 (overlay-put replace-overlay 'face 'query-replace)))
1746 (if query-replace-lazy-highlight
1747 (let ((isearch-string string)
1748 (isearch-regexp regexp)
1749 (search-whitespace-regexp nil)
1750 (isearch-case-fold-search case-fold))
1751 (isearch-lazy-highlight-new-loop range-beg range-end))))
1753 (defun replace-dehighlight ()
1754 (when replace-overlay
1755 (delete-overlay replace-overlay))
1756 (when query-replace-lazy-highlight
1757 (lazy-highlight-cleanup lazy-highlight-cleanup)
1758 (setq isearch-lazy-highlight-last-string nil)))
1760 ;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1761 ;;; replace.el ends here