1 ;;; replace.el --- replace commands for Emacs.
3 ;; Copyright (C) 1985, 86, 87, 92, 94, 96, 1997, 2000
4 ;; Free Software Foundation, Inc.
6 ;; This file is part of GNU Emacs.
8 ;; GNU Emacs is free software; you can redistribute it and/or modify
9 ;; it under the terms of the GNU General Public License as published by
10 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; GNU Emacs is distributed in the hope that it will be useful,
14 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
15 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 ;; GNU General Public License for more details.
18 ;; You should have received a copy of the GNU General Public License
19 ;; along with GNU Emacs; see the file COPYING. If not, write to the
20 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
21 ;; Boston, MA 02111-1307, USA.
25 ;; This package supplies the string and regular-expression replace functions
26 ;; documented in the Emacs user's manual.
30 (defcustom case-replace t
31 "*Non-nil means query-replace should preserve case in replacements."
35 (defvar query-replace-history nil
)
37 (defvar query-replace-interactive nil
38 "Non-nil means `query-replace' uses the last search string.
39 That becomes the \"string to replace\".")
41 (defcustom query-replace-from-history-variable
'query-replace-history
42 "History list to use for the FROM argument of query-replace commands.
43 The value of this variable should be a symbol; that symbol
44 is used as a variable to hold a history list for the strings
45 or patterns to be replaced."
50 (defcustom query-replace-to-history-variable
'query-replace-history
51 "History list to use for the TO argument of query-replace commands.
52 The value of this variable should be a symbol; that symbol
53 is used as a variable to hold a history list for replacement
59 (defun query-replace-read-args (string regexp-flag
)
61 (if query-replace-interactive
62 (setq from
(car (if regexp-flag regexp-search-ring search-ring
)))
63 (setq from
(read-from-minibuffer (format "%s: " string
)
65 query-replace-from-history-variable
67 (setq to
(read-from-minibuffer (format "%s %s with: " string from
)
69 query-replace-to-history-variable from t
))
70 (if (and transient-mark-mode mark-active
)
71 (list from to current-prefix-arg
(region-beginning) (region-end))
72 (list from to current-prefix-arg nil nil
))))
74 (defun query-replace (from-string to-string
&optional delimited start end
)
75 "Replace some occurrences of FROM-STRING with TO-STRING.
76 As each match is found, the user must type a character saying
77 what to do with it. For directions, type \\[help-command] at that time.
79 In Transient Mark mode, if the mark is active, operate on the contents
80 of the region. Otherwise, operate from point to the end of the buffer.
82 If `query-replace-interactive' is non-nil, the last incremental search
83 string is used as FROM-STRING--you don't have to specify it with the
86 Replacement transfers the case of the old text to the new text,
87 if `case-replace' and `case-fold-search'
88 are non-nil and FROM-STRING has no uppercase letters.
89 \(Preserving case means that if the string matched is all caps, or capitalized,
90 then its replacement is upcased or capitalized.)
92 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
93 only matches surrounded by word boundaries.
94 Fourth and fifth arg START and END specify the region to operate on.
96 To customize possible responses, change the \"bindings\" in `query-replace-map'."
97 (interactive (query-replace-read-args "Query replace" nil
))
98 (perform-replace from-string to-string start end t nil delimited
))
100 (define-key esc-map
"%" 'query-replace
)
102 (defun query-replace-regexp (regexp to-string
&optional delimited start end
)
103 "Replace some things after point matching REGEXP with TO-STRING.
104 As each match is found, the user must type a character saying
105 what to do with it. For directions, type \\[help-command] at that time.
107 In Transient Mark mode, if the mark is active, operate on the contents
108 of the region. Otherwise, operate from point to the end of the buffer.
110 If `query-replace-interactive' is non-nil, the last incremental search
111 regexp is used as REGEXP--you don't have to specify it with the
114 Preserves case in each replacement if `case-replace' and `case-fold-search'
115 are non-nil and REGEXP has no uppercase letters.
117 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
118 only matches surrounded by word boundaries.
119 Fourth and fifth arg START and END specify the region to operate on.
121 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
122 and `\\=\\N' (where N is a digit) stands for
123 whatever what matched the Nth `\\(...\\)' in REGEXP."
124 (interactive (query-replace-read-args "Query replace regexp" t
))
125 (perform-replace regexp to-string start end t t delimited
))
126 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
128 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
129 "Replace some things after point matching REGEXP with the result of TO-EXPR.
130 As each match is found, the user must type a character saying
131 what to do with it. For directions, type \\[help-command] at that time.
133 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
134 reference `replace-count' to get the number of replacements already made.
135 If the result of TO-EXPR is not a string, it is converted to one using
136 `prin1-to-string' with the NOESCAPE argument (which see).
138 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
139 `\\0'to stand for whatever matched the whole of REGEXP, and `\\=\\N' (where
140 N is a digit) stands for whatever what matched the Nth `\\(...\\)' in REGEXP.
141 Use `\\#&' or `\\#N' if you want a number instead of a string.
143 In Transient Mark mode, if the mark is active, operate on the contents
144 of the region. Otherwise, operate from point to the end of the buffer.
146 If `query-replace-interactive' is non-nil, the last incremental search
147 regexp is used as REGEXP--you don't have to specify it with the
150 Preserves case in each replacement if `case-replace' and `case-fold-search'
151 are non-nil and REGEXP has no uppercase letters.
153 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
154 only matches surrounded by word boundaries.
155 Fourth and fifth arg START and END specify the region to operate on."
157 (let (from to start end
)
158 (when (and transient-mark-mode mark-active
)
159 (setq start
(region-beginning)
161 (if query-replace-interactive
162 (setq from
(car regexp-search-ring
))
163 (setq from
(read-from-minibuffer "Query replace regexp: "
165 query-replace-from-history-variable
167 (setq to
(list (read-from-minibuffer
168 (format "Query replace regexp %s with eval: " from
)
169 nil nil t query-replace-to-history-variable from t
)))
170 ;; We make TO a list because replace-match-string-symbols requires one,
171 ;; and the user might enter a single token.
172 (replace-match-string-symbols to
)
173 (list from
(car to
) start end current-prefix-arg
)))
174 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
175 start end t t delimited
))
177 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
178 "Replace some matches for REGEXP with various strings, in rotation.
179 The second argument TO-STRINGS contains the replacement strings,
180 separated by spaces. Third arg DELIMITED (prefix arg if interactive),
181 if non-nil, means replace only matches surrounded by word boundaries.
182 This command works like `query-replace-regexp' except that each
183 successive replacement uses the next successive replacement string,
184 wrapping around from the last such string to the first.
186 In Transient Mark mode, if the mark is active, operate on the contents
187 of the region. Otherwise, operate from point to the end of the buffer.
189 Non-interactively, TO-STRINGS may be a list of replacement strings.
191 If `query-replace-interactive' is non-nil, the last incremental search
192 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
194 A prefix argument N says to use each replacement string N times
195 before rotating to the next.
196 Fourth and fifth arg START and END specify the region to operate on."
198 (let (from to start end
)
199 (when (and transient-mark-mode mark-active
)
200 (setq start
(region-beginning)
202 (setq from
(if query-replace-interactive
203 (car regexp-search-ring
)
204 (read-from-minibuffer "Map query replace (regexp): "
206 'query-replace-history nil t
)))
207 (setq to
(read-from-minibuffer
208 (format "Query replace %s with (space-separated strings): "
211 'query-replace-history from t
))
212 (list from to start end current-prefix-arg
)))
214 (if (listp to-strings
)
215 (setq replacements to-strings
)
216 (while (/= (length to-strings
) 0)
217 (if (string-match " " to-strings
)
220 (list (substring to-strings
0
221 (string-match " " to-strings
))))
222 to-strings
(substring to-strings
223 (1+ (string-match " " to-strings
))))
224 (setq replacements
(append replacements
(list to-strings
))
226 (perform-replace regexp replacements start end t t nil n
)))
228 (defun replace-string (from-string to-string
&optional delimited start end
)
229 "Replace occurrences of FROM-STRING with TO-STRING.
230 Preserve case in each match if `case-replace' and `case-fold-search'
231 are non-nil and FROM-STRING has no uppercase letters.
232 \(Preserving case means that if the string matched is all caps, or capitalized,
233 then its replacement is upcased or capitalized.)
235 In Transient Mark mode, if the mark is active, operate on the contents
236 of the region. Otherwise, operate from point to the end of the buffer.
238 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
239 only matches surrounded by word boundaries.
240 Fourth and fifth arg START and END specify the region to operate on.
242 If `query-replace-interactive' is non-nil, the last incremental search
243 string is used as FROM-STRING--you don't have to specify it with the
246 This function is usually the wrong thing to use in a Lisp program.
247 What you probably want is a loop like this:
248 (while (search-forward FROM-STRING nil t)
249 (replace-match TO-STRING nil t))
250 which will run faster and will not set the mark or print anything.
251 \(You may need a more complex loop if FROM-STRING can match the null string
252 and TO-STRING is also null.)"
253 (interactive (query-replace-read-args "Replace string" nil
))
254 (perform-replace from-string to-string start end nil nil delimited
))
256 (defun replace-regexp (regexp to-string
&optional delimited start end
)
257 "Replace things after point matching REGEXP with TO-STRING.
258 Preserve case in each match if `case-replace' and `case-fold-search'
259 are non-nil and REGEXP has no uppercase letters.
261 In Transient Mark mode, if the mark is active, operate on the contents
262 of the region. Otherwise, operate from point to the end of the buffer.
264 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
265 only matches surrounded by word boundaries.
266 Fourth and fifth arg START and END specify the region to operate on.
268 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
269 and `\\=\\N' (where N is a digit) stands for
270 whatever what matched the Nth `\\(...\\)' in REGEXP.
272 If `query-replace-interactive' is non-nil, the last incremental search
273 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
275 This function is usually the wrong thing to use in a Lisp program.
276 What you probably want is a loop like this:
277 (while (re-search-forward REGEXP nil t)
278 (replace-match TO-STRING nil nil))
279 which will run faster and will not set the mark or print anything."
280 (interactive (query-replace-read-args "Replace regexp" t
))
281 (perform-replace regexp to-string start end nil t delimited
))
283 (defvar regexp-history nil
284 "History list for some commands that read regular expressions.")
286 (defalias 'delete-non-matching-lines
'keep-lines
)
287 (defun keep-lines (regexp)
288 "Delete all lines except those containing matches for REGEXP.
289 A match split across lines preserves all the lines it lies in.
290 Applies to all lines after point.
292 If REGEXP contains upper case characters (excluding those preceded by `\\'),
293 the matching is case-sensitive."
294 (interactive (list (read-from-minibuffer
295 "Keep lines (containing match for regexp): "
296 nil nil nil
'regexp-history nil t
)))
298 (or (bolp) (forward-line 1))
299 (let ((start (point))
300 (case-fold-search (and case-fold-search
301 (isearch-no-upper-case-p regexp t
))))
303 ;; Start is first char not preserved by previous match.
304 (if (not (re-search-forward regexp nil
'move
))
305 (delete-region start
(point-max))
306 (let ((end (save-excursion (goto-char (match-beginning 0))
309 ;; Now end is first char preserved by the new match.
311 (delete-region start end
))))
312 (setq start
(save-excursion (forward-line 1)
314 ;; If the match was empty, avoid matching again at same place.
315 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
316 (forward-char 1))))))
318 (defalias 'delete-matching-lines
'flush-lines
)
319 (defun flush-lines (regexp)
320 "Delete lines containing matches for REGEXP.
321 If a match is split across lines, all the lines it lies in are deleted.
322 Applies to lines after point.
324 If REGEXP contains upper case characters (excluding those preceded by `\\'),
325 the matching is case-sensitive."
326 (interactive (list (read-from-minibuffer
327 "Flush lines (containing match for regexp): "
328 nil nil nil
'regexp-history nil t
)))
329 (let ((case-fold-search (and case-fold-search
330 (isearch-no-upper-case-p regexp t
))))
332 (while (and (not (eobp))
333 (re-search-forward regexp nil t
))
334 (delete-region (save-excursion (goto-char (match-beginning 0))
337 (progn (forward-line 1) (point)))))))
339 (defalias 'count-matches
'how-many
)
340 (defun how-many (regexp)
341 "Print number of matches for REGEXP following point.
343 If REGEXP contains upper case characters (excluding those preceded by `\\'),
344 the matching is case-sensitive."
345 (interactive (list (read-from-minibuffer
346 "How many matches for (regexp): "
347 nil nil nil
'regexp-history nil t
)))
348 (let ((count 0) opoint
349 (case-fold-search (and case-fold-search
350 (isearch-no-upper-case-p regexp t
))))
352 (while (and (not (eobp))
353 (progn (setq opoint
(point))
354 (re-search-forward regexp nil t
)))
355 (if (= opoint
(point))
357 (setq count
(1+ count
))))
358 (message "%d occurrences" count
))))
360 (defvar occur-mode-map
())
363 (setq occur-mode-map
(make-sparse-keymap))
364 (define-key occur-mode-map
[mouse-2
] 'occur-mode-mouse-goto
)
365 (define-key occur-mode-map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
366 (define-key occur-mode-map
"\C-m" 'occur-mode-goto-occurrence
)
367 (define-key occur-mode-map
"\M-n" 'occur-next
)
368 (define-key occur-mode-map
"\M-p" 'occur-prev
)
369 (define-key occur-mode-map
"g" 'revert-buffer
))
372 (defvar occur-buffer nil
373 "Name of buffer for last occur.")
376 (defvar occur-nlines nil
377 "Number of lines of context to show around matching line.")
379 (defvar occur-command-arguments nil
380 "Arguments that were given to `occur' when it made this buffer.")
382 (put 'occur-mode
'mode-class
'special
)
385 "Major mode for output from \\[occur].
386 \\<occur-mode-map>Move point to one of the items in this buffer, then use
387 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
388 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
391 (kill-all-local-variables)
392 (use-local-map occur-mode-map
)
393 (setq major-mode
'occur-mode
)
394 (setq mode-name
"Occur")
395 (make-local-variable 'revert-buffer-function
)
396 (setq revert-buffer-function
'occur-revert-function
)
397 (make-local-variable 'occur-buffer
)
398 (make-local-variable 'occur-nlines
)
399 (make-local-variable 'occur-command-arguments
)
400 (run-hooks 'occur-mode-hook
))
402 (defun occur-revert-function (ignore1 ignore2
)
403 "Handle revert-buffer for *Occur* buffers."
404 (let ((args occur-command-arguments
))
406 (set-buffer occur-buffer
)
407 (apply 'occur args
))))
409 (defun occur-mode-mouse-goto (event)
410 "In Occur mode, go to the occurrence whose line you click on."
414 (set-buffer (window-buffer (posn-window (event-end event
))))
416 (goto-char (posn-point (event-end event
)))
417 (setq pos
(occur-mode-find-occurrence))
418 (setq buffer occur-buffer
)))
419 (pop-to-buffer buffer
)
420 (goto-char (marker-position pos
))))
422 (defun occur-mode-find-occurrence ()
423 (if (or (null occur-buffer
)
424 (null (buffer-name occur-buffer
)))
426 (setq occur-buffer nil
)
427 (error "Buffer in which occurrences were found is deleted")))
428 (let ((pos (get-text-property (point) 'occur
)))
430 (error "No occurrence on this line")
433 (defun occur-mode-goto-occurrence ()
434 "Go to the occurrence the current line describes."
436 (let ((pos (occur-mode-find-occurrence)))
437 (pop-to-buffer occur-buffer
)
438 (goto-char (marker-position pos
))))
440 (defun occur-next (&optional n
)
441 "Move to the Nth (default 1) next match in the *Occur* buffer."
443 (if (not n
) (setq n
1))
446 (if (get-text-property (point) 'occur-point
)
448 (setq r
(next-single-property-change (point) 'occur-point
))
451 (error "No more matches"))
456 (defun occur-prev (&optional n
)
457 "Move to the Nth (default 1) previous match in the *Occur* buffer."
459 (if (not n
) (setq n
1))
463 (setq r
(get-text-property (point) 'occur-point
))
464 (if r
(forward-char -
1))
466 (setq r
(previous-single-property-change (point) 'occur-point
))
469 (error "No earlier matches"))
473 (defcustom list-matching-lines-default-context-lines
0
474 "*Default number of context lines included around `list-matching-lines' matches.
475 A negative number means to include that many lines before the match.
476 A positive number means to include that many lines both before and after."
480 (defalias 'list-matching-lines
'occur
)
482 (defvar list-matching-lines-face
'bold
483 "*Face used by \\[list-matching-lines] to show the text that matches.
484 If the value is nil, don't highlight the matching portions specially.")
486 (defun occur (regexp &optional nlines
)
487 "Show all lines in the current buffer containing a match for REGEXP.
489 If a match spreads across multiple lines, all those lines are shown.
491 Each line is displayed with NLINES lines before and after, or -NLINES
492 before if NLINES is negative.
493 NLINES defaults to `list-matching-lines-default-context-lines'.
494 Interactively it is the prefix arg.
496 The lines are shown in a buffer named `*Occur*'.
497 It serves as a menu to find any of the occurrences in this buffer.
498 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
500 If REGEXP contains upper case characters (excluding those preceded by `\\'),
501 the matching is case-sensitive."
503 (list (let* ((default (car regexp-history
))
505 (read-from-minibuffer
507 (format "List lines matching regexp (default `%s'): "
509 "List lines matching regexp: ")
510 nil nil nil
'regexp-history default t
)))
511 (and (equal input
"") default
512 (setq input default
))
515 (let* ((nlines (if nlines
516 (prefix-numeric-value nlines
)
517 list-matching-lines-default-context-lines
))
518 (current-tab-width tab-width
)
519 ;; Minimum width of line number plus trailing colon.
520 (min-line-number-width 6)
521 ;; Actual width of line number prefix. Choose a width that's
522 ;; a multiple of `tab-width' in the original buffer so that
523 ;; lines in *Occur* appear right.
524 (line-number-width (* (/ (- (+ min-line-number-width
529 ;; Format string for line numbers.
530 (line-number-format (format "%%%dd" line-number-width
))
531 (empty (make-string line-number-width ?\
))
533 ;;flag to prevent printing separator for first match
534 (occur-num-matches 0)
535 (buffer (current-buffer))
536 (dir default-directory
)
539 ;;position of most recent match
541 (case-fold-search (and case-fold-search
542 (isearch-no-upper-case-p regexp t
)))
544 ;; Marker to the start of context immediately following
545 ;; the matched text in *Occur*.
548 ;;; (beginning-of-line)
549 ;;; (setq linenum (1+ (count-lines (point-min) (point))))
550 ;;; (setq prevpos (point)))
552 (goto-char (point-min))
553 ;; Check first whether there are any matches at all.
554 (if (not (re-search-forward regexp nil t
))
555 (message "No matches for `%s'" regexp
)
556 ;; Back up, so the search loop below will find the first match.
557 (goto-char (match-beginning 0))
558 (with-output-to-temp-buffer "*Occur*"
560 (set-buffer standard-output
)
561 (setq default-directory dir
)
562 ;; We will insert the number of lines, and "lines", later.
563 (insert " matching ")
564 (let ((print-escape-newlines t
))
566 (insert " in buffer " (buffer-name buffer
) ?. ?
\n)
568 (setq occur-buffer buffer
)
569 (setq occur-nlines nlines
)
570 (setq occur-command-arguments
571 (list regexp nlines
)))
572 (if (eq buffer standard-output
)
573 (goto-char (point-max)))
575 ;; Find next match, but give up if prev match was at end of buffer.
576 (while (and (not (= prevpos
(point-max)))
577 (re-search-forward regexp nil t
))
578 (goto-char (match-beginning 0))
581 (setq linenum
(+ linenum
(count-lines prevpos
(point)))))
582 (setq prevpos
(point))
583 (goto-char (match-end 0))
584 (let* (;;start point of text in source buffer to be put
586 (start (save-excursion
587 (goto-char (match-beginning 0))
588 (forward-line (if (< nlines
0)
592 ;; end point of text in source buffer to be put
595 (goto-char (match-end 0))
597 (forward-line (1+ nlines
))
600 ;; Amount of context before matching text
601 (match-beg (- (match-beginning 0) start
))
602 ;; Length of matching text
603 (match-len (- (match-end 0) (match-beginning 0)))
604 (tag (format line-number-format linenum
))
607 ;; Number of lines of context to show for current match.
609 ;; Marker pointing to end of match in source buffer.
611 ;; Marker pointing to start of text for one
615 ;; Marker pointing to end of text for one match
619 (setq occur-marker
(make-marker))
620 (set-marker occur-marker
(point))
621 (set-buffer standard-output
)
622 (setq occur-num-matches
(1+ occur-num-matches
))
623 (or first
(zerop nlines
)
624 (insert "--------\n"))
627 (set-buffer "*Occur*")
628 (setq tab-width current-tab-width
))
630 ;; Insert matching text including context lines from
631 ;; source buffer into *Occur*
632 (set-marker text-beg
(point))
633 (setq insertion-start
(point))
634 (insert-buffer-substring buffer start end
)
635 (or (and (/= (+ start match-beg
) end
)
636 (with-current-buffer buffer
637 (eq (char-before end
) ?
\n)))
639 (set-marker final-context-start
640 (+ (- (point) (- end
(match-end 0)))
644 (goto-char (match-end 0))
648 (set-marker text-end
(point))
650 ;; Highlight text that was matched.
651 (if list-matching-lines-face
653 (+ (marker-position text-beg
) match-beg
)
654 (+ (marker-position text-beg
) match-beg match-len
)
655 'face list-matching-lines-face
))
657 ;; `occur-point' property is used by occur-next and
658 ;; occur-prev to move between matching lines.
660 (+ (marker-position text-beg
) match-beg match-len
)
661 (+ (marker-position text-beg
) match-beg match-len
1)
664 ;; Now go back to the start of the matching text
665 ;; adding the space and colon to the start of each line.
666 (goto-char insertion-start
)
667 ;; Insert space and colon for lines of context before match.
668 (setq tem
(if (< linenum nlines
)
676 ;; Insert line number and colon for the lines of
678 (let ((this-linenum linenum
))
679 (while (< (point) final-context-start
)
681 (setq tag
(format line-number-format this-linenum
)))
685 (setq this-linenum
(1+ this-linenum
)))
686 (while (and (not (eobp)) (<= (point) final-context-start
))
689 (setq this-linenum
(1+ this-linenum
))))
691 ;; Insert space and colon for lines of context after match.
692 (while (and (< (point) (point-max)) (< tem nlines
))
697 ;; Add text properties. The `occur' prop is used to
698 ;; store the marker of the matching text in the
700 (put-text-property (marker-position text-beg
)
701 (- (marker-position text-end
) 1)
702 'mouse-face
'highlight
)
703 (put-text-property (marker-position text-beg
)
704 (marker-position text-end
)
706 (goto-char (point-max)))
708 (set-buffer standard-output
)
709 ;; Go back to top of *Occur* and finish off by printing the
710 ;; number of matching lines.
711 (goto-char (point-min))
712 (let ((message-string
713 (if (= occur-num-matches
1)
715 (format "%d lines" occur-num-matches
))))
716 (insert message-string
)
718 (message "%s matched" message-string
)))
719 (setq buffer-read-only t
)))))))
721 ;; It would be nice to use \\[...], but there is no reasonable way
722 ;; to make that display both SPC and Y.
723 (defconst query-replace-help
724 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
725 RET or `q' to exit, Period to replace one match and exit,
726 Comma to replace but not move point immediately,
727 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
728 C-w to delete match and recursive edit,
729 C-l to clear the screen, redisplay, and offer same replacement again,
730 ! to replace all remaining matches with no more questions,
731 ^ to move point back to previous match,
732 E to edit the replacement string"
733 "Help message while in query-replace")
735 (defvar query-replace-map
(make-sparse-keymap)
736 "Keymap that defines the responses to questions in `query-replace'.
737 The \"bindings\" in this map are not commands; they are answers.
738 The valid answers include `act', `skip', `act-and-show',
739 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
740 `automatic', `backup', `exit-prefix', and `help'.")
742 (define-key query-replace-map
" " 'act
)
743 (define-key query-replace-map
"\d" 'skip
)
744 (define-key query-replace-map
[delete] 'skip)
745 (define-key query-replace-map [backspace] 'skip)
746 (define-key query-replace-map "y" 'act)
747 (define-key query-replace-map "n" 'skip)
748 (define-key query-replace-map "Y" 'act)
749 (define-key query-replace-map "N" 'skip)
750 (define-key query-replace-map "e" 'edit-replacement)
751 (define-key query-replace-map "E" 'edit-replacement)
752 (define-key query-replace-map "," 'act-and-show)
753 (define-key query-replace-map "q" 'exit)
754 (define-key query-replace-map "\r" 'exit)
755 (define-key query-replace-map [return] 'exit)
756 (define-key query-replace-map "." 'act-and-exit)
757 (define-key query-replace-map "\C-r" 'edit)
758 (define-key query-replace-map "\C-w" 'delete-and-edit)
759 (define-key query-replace-map "\C-l" 'recenter)
760 (define-key query-replace-map "!" 'automatic)
761 (define-key query-replace-map "^" 'backup)
762 (define-key query-replace-map "\C-h" 'help)
763 (define-key query-replace-map [f1] 'help)
764 (define-key query-replace-map [help] 'help)
765 (define-key query-replace-map "?" 'help)
766 (define-key query-replace-map "\C-g" 'quit)
767 (define-key query-replace-map "\C-]" 'quit)
768 (define-key query-replace-map "\e" 'exit-prefix)
769 (define-key query-replace-map [escape] 'exit-prefix)
771 (defun replace-match-string-symbols (n)
772 "Process a list (and any sub-lists), expanding certain symbols.
774 N (match-string N) (where N is a string of digits)
775 #N (string-to-number (match-string N))
777 #& (string-to-number (match-string 0))
779 Note that these symbols must be preceeded by a backslash in order to
784 (replace-match-string-symbols (car n))) ;Process sub-list
786 (let ((name (symbol-name (car n))))
788 ((string-match "^[0-9]+$" name)
789 (setcar n (list 'match-string (string-to-number name))))
790 ((string-match "^#[0-9]+$" name)
791 (setcar n (list 'string-to-number
793 (string-to-number (substring name 1))))))
795 (setcar n '(match-string 0)))
797 (setcar n '(string-to-number (match-string 0))))))))
800 (defun replace-eval-replacement (expression replace-count)
801 (let ((replacement (eval expression)))
802 (if (stringp replacement)
804 (prin1-to-string replacement t))))
806 (defun replace-loop-through-replacements (data replace-count)
807 ;; DATA is a vector contaning the following values:
808 ;; 0 next-rotate-count
810 ;; 2 next-replacement
812 (if (= (aref data 0) replace-count)
814 (aset data 0 (+ replace-count (aref data 1)))
815 (let ((next (cdr (aref data 2))))
816 (aset data 2 (if (consp next) next (aref data 3))))))
819 (defun perform-replace (from-string replacements start end
820 query-flag regexp-flag delimited-flag
821 &optional repeat-count map)
822 "Subroutine of `query-replace'. Its complexity handles interactive queries.
823 Don't use this in your own program unless you want to query and set the mark
824 just as `query-replace' does. Instead, write a simple loop like this:
825 (while (re-search-forward \"foo[ \t]+bar\" nil t)
826 (replace-match \"foobar\" nil nil))
827 which will run faster and probably do exactly what you want."
828 (or map (setq map query-replace-map))
829 (and query-flag minibuffer-auto-raise
830 (raise-frame (window-frame (minibuffer-window))))
831 (let ((nocasify (not (and case-fold-search case-replace
832 (string-equal from-string
833 (downcase from-string)))))
834 (case-fold-search (and case-fold-search
835 (string-equal from-string
836 (downcase from-string))))
837 (literal (not regexp-flag))
838 (search-function (if regexp-flag 're-search-forward 'search-forward))
839 (search-string from-string)
840 (real-match-data nil) ; the match data for the current match
841 (next-replacement nil)
847 ;; If non-nil, it is marker saying where in the buffer to stop.
850 ;; Data for the next match. If a cons, it has the same format as
851 ;; (match-data); otherwise it is t if a match is possible at point.
856 (substitute-command-keys
857 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
859 ;; If region is active, in Transient Mark mode, operate on region.
861 (setq limit (copy-marker (max start end)))
862 (goto-char (min start end))
865 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
866 ;; containing a function and its first argument. The function is
867 ;; called to generate each replacement like this:
868 ;; (funcall (car replacements) (cdr replacements) replace-count)
869 ;; It must return a string.
871 ((stringp replacements)
872 (setq next-replacement replacements
874 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
875 (or repeat-count (setq repeat-count 1))
876 (setq replacements (cons 'replace-loop-through-replacements
877 (vector repeat-count repeat-count
878 replacements replacements)))))
881 (setq search-function 're-search-forward
882 search-string (concat "\\b"
883 (if regexp-flag from-string
884 (regexp-quote from-string))
889 ;; Loop finding occurrences that perhaps should be replaced.
890 (while (and keep-going
892 ;; Use the next match if it is already known;
893 ;; otherwise, search for a match after moving forward
894 ;; one char if progress is required.
895 (setq real-match-data
896 (if (consp match-again)
897 (progn (goto-char (nth 1 match-again))
900 ;; MATCH-AGAIN non-nil means we
901 ;; accept an adjacent match. If
902 ;; we don't, move one char to the
903 ;; right. This takes us a
904 ;; character too far at the end,
905 ;; but this is undone after the
907 (progn (forward-char 1) (not (eobp))))
908 (funcall search-function search-string limit t)
909 ;; For speed, use only integers and
910 ;; reuse the list used last time.
911 (match-data t real-match-data)))))
913 ;; Record whether the match is nonempty, to avoid an infinite loop
914 ;; repeatedly matching the same empty string.
916 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
918 ;; If the match is empty, record that the next one can't be adjacent.
919 ;; Otherwise, if matching a regular expression, do the next
920 ;; match now, since the replacement for this match may
921 ;; affect whether the next match is adjacent to this one.
924 (or (not regexp-flag)
925 (and (looking-at search-string)
928 ;; Calculate the replacement string, if necessary.
930 (set-match-data real-match-data)
931 (setq next-replacement
932 (funcall (car replacements) (cdr replacements)
936 (set-match-data real-match-data)
937 (replace-match next-replacement nocasify literal)
938 (setq replace-count (1+ replace-count)))
940 (let (done replaced key def)
941 ;; Loop reading commands until one of them sets done,
942 ;; which means it has finished handling this occurrence.
944 (set-match-data real-match-data)
945 (replace-highlight (match-beginning 0) (match-end 0))
946 ;; Bind message-log-max so we don't fill up the message log
947 ;; with a bunch of identical messages.
948 (let ((message-log-max nil))
949 (message message from-string next-replacement))
950 (setq key (read-event))
951 ;; Necessary in case something happens during read-event
952 ;; that clobbers the match data.
953 (set-match-data real-match-data)
954 (setq key (vector key))
955 (setq def (lookup-key map key))
956 ;; Restore the match data while we process the command.
957 (cond ((eq def 'help)
958 (with-output-to-temp-buffer "*Help*"
960 (concat "Query replacing "
961 (if regexp-flag "regexp " "")
963 next-replacement ".\n\n"
964 (substitute-command-keys
965 query-replace-help)))
967 (set-buffer standard-output)
970 (setq keep-going nil)
974 (let ((elt (car stack)))
975 (goto-char (car elt))
976 (setq replaced (eq t (cdr elt)))
978 (set-match-data (cdr elt)))
979 (setq stack (cdr stack)))
980 (message "No previous match")
986 (replace-match next-replacement nocasify literal)
987 (setq replace-count (1+ replace-count))))
988 (setq done t replaced t))
989 ((eq def 'act-and-exit)
992 (replace-match next-replacement nocasify literal)
993 (setq replace-count (1+ replace-count))))
994 (setq keep-going nil)
995 (setq done t replaced t))
996 ((eq def 'act-and-show)
999 (replace-match next-replacement nocasify literal)
1000 (setq replace-count (1+ replace-count))
1001 (setq replaced t))))
1002 ((eq def 'automatic)
1005 (replace-match next-replacement nocasify literal)
1006 (setq replace-count (1+ replace-count))))
1007 (setq done t query-flag nil replaced t))
1013 (let ((opos (point-marker)))
1014 (goto-char (match-beginning 0))
1016 (funcall search-function search-string limit t)
1017 (setq real-match-data (match-data)))
1018 (save-excursion (recursive-edit))
1020 (set-match-data real-match-data)
1021 ;; Before we make the replacement,
1022 ;; decide whether the search string
1023 ;; can match again just after this match.
1024 (if (and regexp-flag nonempty-match)
1025 (setq match-again (and (looking-at search-string)
1028 ;; Edit replacement.
1029 ((eq def 'edit-replacement)
1030 (setq next-replacement
1031 (read-input "Edit replacement string: "
1034 (replace-match next-replacement nocasify literal))
1037 ((eq def 'delete-and-edit)
1038 (delete-region (match-beginning 0) (match-end 0))
1041 (save-excursion (recursive-edit))))
1043 ;; Note: we do not need to treat `exit-prefix'
1044 ;; specially here, since we reread
1045 ;; any unrecognized character.
1047 (setq this-command 'mode-exited)
1048 (setq keep-going nil)
1049 (setq unread-command-events
1050 (append (listify-key-sequence key)
1051 unread-command-events))
1053 ;; Record previous position for ^ when we move on.
1054 ;; Change markers to numbers in the match data
1055 ;; since lots of markers slow down editing.
1058 (or replaced (match-data t)))
1061 ;; The code preventing adjacent regexp matches in the condition
1062 ;; of the while-loop above will haven taken us one character
1063 ;; beyond the last replacement. Undo that.
1064 (when (and regexp-flag (not match-again) (> replace-count 0))
1067 (replace-dehighlight))
1068 (or unread-command-events
1069 (message "Replaced %d occurrence%s"
1071 (if (= replace-count 1) "" "s")))
1072 (and keep-going stack)))
1074 (defcustom query-replace-highlight t
1075 "*Non-nil means to highlight words during query replacement."
1079 (defvar replace-overlay nil)
1081 (defun replace-dehighlight ()
1082 (and replace-overlay
1084 (delete-overlay replace-overlay)
1085 (setq replace-overlay nil))))
1087 (defun replace-highlight (start end)
1088 (and query-replace-highlight
1092 (setq replace-overlay (make-overlay start end))
1093 (overlay-put replace-overlay 'face
1094 (if (facep 'query-replace)
1095 'query-replace 'region))))
1096 (move-overlay replace-overlay start end (current-buffer)))))
1098 ;;; replace.el ends here