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
))
519 ;;flag to prevent printing separator for first match
520 (occur-num-matches 0)
521 (buffer (current-buffer))
522 (dir default-directory
)
525 ;;position of most recent match
527 (case-fold-search (and case-fold-search
528 (isearch-no-upper-case-p regexp t
)))
530 ;; Marker to the start of context immediately following
531 ;; the matched text in *Occur*.
534 ;;; (beginning-of-line)
535 ;;; (setq linenum (1+ (count-lines (point-min) (point))))
536 ;;; (setq prevpos (point)))
538 (goto-char (point-min))
539 ;; Check first whether there are any matches at all.
540 (if (not (re-search-forward regexp nil t
))
541 (message "No matches for `%s'" regexp
)
542 ;; Back up, so the search loop below will find the first match.
543 (goto-char (match-beginning 0))
544 (with-output-to-temp-buffer "*Occur*"
546 (set-buffer standard-output
)
547 (setq default-directory dir
)
548 ;; We will insert the number of lines, and "lines", later.
549 (insert " matching ")
550 (let ((print-escape-newlines t
))
552 (insert " in buffer " (buffer-name buffer
) ?. ?
\n)
554 (setq occur-buffer buffer
)
555 (setq occur-nlines nlines
)
556 (setq occur-command-arguments
557 (list regexp nlines
)))
558 (if (eq buffer standard-output
)
559 (goto-char (point-max)))
561 ;; Find next match, but give up if prev match was at end of buffer.
562 (while (and (not (= prevpos
(point-max)))
563 (re-search-forward regexp nil t
))
564 (goto-char (match-beginning 0))
567 (setq linenum
(+ linenum
(count-lines prevpos
(point)))))
568 (setq prevpos
(point))
569 (goto-char (match-end 0))
571 ;;start point of text in source buffer to be put
574 (goto-char (match-beginning 0))
575 (forward-line (if (< nlines
0)
580 ;; end point of text in source buffer to be put
583 (goto-char (match-end 0))
585 (forward-line (1+ nlines
))
589 ;; Amount of context before matching text
590 (- (match-beginning 0) start
))
592 ;; Length of matching text
593 (- (match-end 0) (match-beginning 0)))
594 (tag (format "%5d" linenum
))
595 (empty (make-string (length tag
) ?\
))
598 ;; Number of lines of context to show for current match.
600 ;; Marker pointing to end of match in source buffer.
602 ;; Marker pointing to start of text for one
606 ;; Marker pointing to end of text for one match
611 (setq occur-marker
(make-marker))
612 (set-marker occur-marker
(point))
613 (set-buffer standard-output
)
614 (setq occur-num-matches
(1+ occur-num-matches
))
615 (or first
(zerop nlines
)
616 (insert "--------\n"))
619 ;; Insert matching text including context lines from
620 ;; source buffer into *Occur*
621 (set-marker text-beg
(point))
622 (setq insertion-start
(point))
623 (insert-buffer-substring buffer start end
)
624 (or (and (/= (+ start match-beg
) end
)
625 (with-current-buffer buffer
626 (eq (char-before end
) ?
\n)))
628 (set-marker final-context-start
629 (+ (- (point) (- end
(match-end 0)))
633 (goto-char (match-end 0))
637 (set-marker text-end
(point))
639 ;; Highlight text that was matched.
640 (if list-matching-lines-face
642 (+ (marker-position text-beg
) match-beg
)
643 (+ (marker-position text-beg
) match-beg match-len
)
644 'face list-matching-lines-face
))
646 ;; `occur-point' property is used by occur-next and
647 ;; occur-prev to move between matching lines.
649 (+ (marker-position text-beg
) match-beg match-len
)
650 (+ (marker-position text-beg
) match-beg match-len
1)
653 ;; Now go back to the start of the matching text
654 ;; adding the space and colon to the start of each line.
655 (goto-char insertion-start
)
656 ;; Insert space and colon for lines of context before match.
657 (setq tem
(if (< linenum nlines
)
665 ;; Insert line number and colon for the lines of
667 (let ((this-linenum linenum
))
668 (while (< (point) final-context-start
)
670 (setq tag
(format "%5d" this-linenum
)))
674 (setq this-linenum
(1+ this-linenum
)))
675 (while (and (not (eobp)) (<= (point) final-context-start
))
678 (setq this-linenum
(1+ this-linenum
))))
680 ;; Insert space and colon for lines of context after match.
681 (while (and (< (point) (point-max)) (< tem nlines
))
686 ;; Add text properties. The `occur' prop is used to
687 ;; store the marker of the matching text in the
689 (put-text-property (marker-position text-beg
)
690 (- (marker-position text-end
) 1)
691 'mouse-face
'highlight
)
692 (put-text-property (marker-position text-beg
)
693 (marker-position text-end
)
695 (goto-char (point-max)))
697 (set-buffer standard-output
)
698 ;; Go back to top of *Occur* and finish off by printing the
699 ;; number of matching lines.
700 (goto-char (point-min))
701 (let ((message-string
702 (if (= occur-num-matches
1)
704 (format "%d lines" occur-num-matches
))))
705 (insert message-string
)
707 (message "%s matched" message-string
)))
708 (setq buffer-read-only t
)))))))
710 ;; It would be nice to use \\[...], but there is no reasonable way
711 ;; to make that display both SPC and Y.
712 (defconst query-replace-help
713 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
714 RET or `q' to exit, Period to replace one match and exit,
715 Comma to replace but not move point immediately,
716 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
717 C-w to delete match and recursive edit,
718 C-l to clear the screen, redisplay, and offer same replacement again,
719 ! to replace all remaining matches with no more questions,
720 ^ to move point back to previous match,
721 E to edit the replacement string"
722 "Help message while in query-replace")
724 (defvar query-replace-map
(make-sparse-keymap)
725 "Keymap that defines the responses to questions in `query-replace'.
726 The \"bindings\" in this map are not commands; they are answers.
727 The valid answers include `act', `skip', `act-and-show',
728 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
729 `automatic', `backup', `exit-prefix', and `help'.")
731 (define-key query-replace-map
" " 'act
)
732 (define-key query-replace-map
"\d" 'skip
)
733 (define-key query-replace-map
[delete] 'skip)
734 (define-key query-replace-map [backspace] 'skip)
735 (define-key query-replace-map "y" 'act)
736 (define-key query-replace-map "n" 'skip)
737 (define-key query-replace-map "Y" 'act)
738 (define-key query-replace-map "N" 'skip)
739 (define-key query-replace-map "E" 'edit-replacement)
740 (define-key query-replace-map "," 'act-and-show)
741 (define-key query-replace-map "q" 'exit)
742 (define-key query-replace-map "\r" 'exit)
743 (define-key query-replace-map [return] 'exit)
744 (define-key query-replace-map "." 'act-and-exit)
745 (define-key query-replace-map "\C-r" 'edit)
746 (define-key query-replace-map "\C-w" 'delete-and-edit)
747 (define-key query-replace-map "\C-l" 'recenter)
748 (define-key query-replace-map "!" 'automatic)
749 (define-key query-replace-map "^" 'backup)
750 (define-key query-replace-map "\C-h" 'help)
751 (define-key query-replace-map [f1] 'help)
752 (define-key query-replace-map [help] 'help)
753 (define-key query-replace-map "?" 'help)
754 (define-key query-replace-map "\C-g" 'quit)
755 (define-key query-replace-map "\C-]" 'quit)
756 (define-key query-replace-map "\e" 'exit-prefix)
757 (define-key query-replace-map [escape] 'exit-prefix)
759 (defun replace-match-string-symbols (n)
760 "Process a list (and any sub-lists), expanding certain symbols.
762 N (match-string N) (where N is a string of digits)
763 #N (string-to-number (match-string N))
765 #& (string-to-number (match-string 0))
767 Note that these symbols must be preceeded by a backslash in order to
772 (replace-match-string-symbols (car n))) ;Process sub-list
774 (let ((name (symbol-name (car n))))
776 ((string-match "^[0-9]+$" name)
777 (setcar n (list 'match-string (string-to-number name))))
778 ((string-match "^#[0-9]+$" name)
779 (setcar n (list 'string-to-number
781 (string-to-number (substring name 1))))))
783 (setcar n '(match-string 0)))
785 (setcar n '(string-to-number (match-string 0))))))))
788 (defun replace-eval-replacement (expression replace-count)
789 (let ((replacement (eval expression)))
790 (if (stringp replacement)
792 (prin1-to-string replacement t))))
794 (defun replace-loop-through-replacements (data replace-count)
795 ;; DATA is a vector contaning the following values:
796 ;; 0 next-rotate-count
798 ;; 2 next-replacement
800 (if (= (aref data 0) replace-count)
802 (aset data 0 (+ replace-count (aref data 1)))
803 (let ((next (cdr (aref data 2))))
804 (aset data 2 (if (consp next) next (aref data 3))))))
807 (defun perform-replace (from-string replacements start end
808 query-flag regexp-flag delimited-flag
809 &optional repeat-count map)
810 "Subroutine of `query-replace'. Its complexity handles interactive queries.
811 Don't use this in your own program unless you want to query and set the mark
812 just as `query-replace' does. Instead, write a simple loop like this:
813 (while (re-search-forward \"foo[ \t]+bar\" nil t)
814 (replace-match \"foobar\" nil nil))
815 which will run faster and probably do exactly what you want."
816 (or map (setq map query-replace-map))
817 (and query-flag minibuffer-auto-raise
818 (raise-frame (window-frame (minibuffer-window))))
819 (let ((nocasify (not (and case-fold-search case-replace
820 (string-equal from-string
821 (downcase from-string)))))
822 (case-fold-search (and case-fold-search
823 (string-equal from-string
824 (downcase from-string))))
825 (literal (not regexp-flag))
826 (search-function (if regexp-flag 're-search-forward 'search-forward))
827 (search-string from-string)
828 (real-match-data nil) ; the match data for the current match
829 (next-replacement nil)
835 ;; If non-nil, it is marker saying where in the buffer to stop.
838 ;; Data for the next match. If a cons, it has the same format as
839 ;; (match-data); otherwise it is t if a match is possible at point.
844 (substitute-command-keys
845 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
847 ;; If region is active, in Transient Mark mode, operate on region.
849 (setq limit (copy-marker (max start end)))
850 (goto-char (min start end))
853 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
854 ;; containing a function and its first argument. The function is
855 ;; called to generate each replacement like this:
856 ;; (funcall (car replacements) (cdr replacements) replace-count)
857 ;; It must return a string.
859 ((stringp replacements)
860 (setq next-replacement replacements
862 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
863 (or repeat-count (setq repeat-count 1))
864 (setq replacements (cons 'replace-loop-through-replacements
865 (vector repeat-count repeat-count
866 replacements replacements)))))
869 (setq search-function 're-search-forward
870 search-string (concat "\\b"
871 (if regexp-flag from-string
872 (regexp-quote from-string))
877 ;; Loop finding occurrences that perhaps should be replaced.
878 (while (and keep-going
880 ;; Use the next match if it is already known;
881 ;; otherwise, search for a match after moving forward
882 ;; one char if progress is required.
883 (setq real-match-data
884 (if (consp match-again)
885 (progn (goto-char (nth 1 match-again))
888 ;; MATCH-AGAIN nil means in the
889 ;; regexp case that there's no
890 ;; match adjacent to the last
891 ;; one. So, we could move
892 ;; forward, but we don't want to
893 ;; because that moves point 1
894 ;; position after the last
895 ;; replacement when everything
898 (progn (forward-char 1) (not (eobp))))
899 (funcall search-function search-string limit t)
900 ;; For speed, use only integers and
901 ;; reuse the list used last time.
902 (match-data t real-match-data)))))
904 ;; Record whether the match is nonempty, to avoid an infinite loop
905 ;; repeatedly matching the same empty string.
907 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
909 ;; If the match is empty, record that the next one can't be adjacent.
910 ;; Otherwise, if matching a regular expression, do the next
911 ;; match now, since the replacement for this match may
912 ;; affect whether the next match is adjacent to this one.
915 (or (not regexp-flag)
916 (and (looking-at search-string)
919 ;; Calculate the replacement string, if necessary.
921 (set-match-data real-match-data)
922 (setq next-replacement
923 (funcall (car replacements) (cdr replacements)
927 (set-match-data real-match-data)
928 (replace-match next-replacement nocasify literal)
929 (setq replace-count (1+ replace-count)))
931 (let (done replaced key def)
932 ;; Loop reading commands until one of them sets done,
933 ;; which means it has finished handling this occurrence.
935 (set-match-data real-match-data)
936 (replace-highlight (match-beginning 0) (match-end 0))
937 ;; Bind message-log-max so we don't fill up the message log
938 ;; with a bunch of identical messages.
939 (let ((message-log-max nil))
940 (message message from-string next-replacement))
941 (setq key (read-event))
942 ;; Necessary in case something happens during read-event
943 ;; that clobbers the match data.
944 (set-match-data real-match-data)
945 (setq key (vector key))
946 (setq def (lookup-key map key))
947 ;; Restore the match data while we process the command.
948 (cond ((eq def 'help)
949 (with-output-to-temp-buffer "*Help*"
951 (concat "Query replacing "
952 (if regexp-flag "regexp " "")
954 next-replacement ".\n\n"
955 (substitute-command-keys
956 query-replace-help)))
958 (set-buffer standard-output)
961 (setq keep-going nil)
965 (let ((elt (car stack)))
966 (goto-char (car elt))
967 (setq replaced (eq t (cdr elt)))
969 (set-match-data (cdr elt)))
970 (setq stack (cdr stack)))
971 (message "No previous match")
977 (replace-match next-replacement nocasify literal)
978 (setq replace-count (1+ replace-count))))
979 (setq done t replaced t))
980 ((eq def 'act-and-exit)
983 (replace-match next-replacement nocasify literal)
984 (setq replace-count (1+ replace-count))))
985 (setq keep-going nil)
986 (setq done t replaced t))
987 ((eq def 'act-and-show)
990 (replace-match next-replacement nocasify literal)
991 (setq replace-count (1+ replace-count))
996 (replace-match next-replacement nocasify literal)
997 (setq replace-count (1+ replace-count))))
998 (setq done t query-flag nil replaced t))
1004 (let ((opos (point-marker)))
1005 (goto-char (match-beginning 0))
1007 (funcall search-function search-string limit t)
1008 (setq real-match-data (match-data)))
1009 (save-excursion (recursive-edit))
1011 (set-match-data real-match-data)
1012 ;; Before we make the replacement,
1013 ;; decide whether the search string
1014 ;; can match again just after this match.
1015 (if (and regexp-flag nonempty-match)
1016 (setq match-again (and (looking-at search-string)
1019 ;; Edit replacement.
1020 ((eq def 'edit-replacement)
1021 (setq next-replacement
1022 (read-input "Edit replacement string: "
1025 (replace-match next-replacement nocasify literal))
1028 ((eq def 'delete-and-edit)
1029 (delete-region (match-beginning 0) (match-end 0))
1032 (save-excursion (recursive-edit))))
1034 ;; Note: we do not need to treat `exit-prefix'
1035 ;; specially here, since we reread
1036 ;; any unrecognized character.
1038 (setq this-command 'mode-exited)
1039 (setq keep-going nil)
1040 (setq unread-command-events
1041 (append (listify-key-sequence key)
1042 unread-command-events))
1044 ;; Record previous position for ^ when we move on.
1045 ;; Change markers to numbers in the match data
1046 ;; since lots of markers slow down editing.
1049 (or replaced (match-data t)))
1051 (replace-dehighlight))
1052 (or unread-command-events
1053 (message "Replaced %d occurrence%s"
1055 (if (= replace-count 1) "" "s")))
1056 (and keep-going stack)))
1058 (defcustom query-replace-highlight t
1059 "*Non-nil means to highlight words during query replacement."
1063 (defvar replace-overlay nil)
1065 (defun replace-dehighlight ()
1066 (and replace-overlay
1068 (delete-overlay replace-overlay)
1069 (setq replace-overlay nil))))
1071 (defun replace-highlight (start end)
1072 (and query-replace-highlight
1076 (setq replace-overlay (make-overlay start end))
1077 (overlay-put replace-overlay 'face
1078 (if (facep 'query-replace)
1079 'query-replace 'region))))
1080 (move-overlay replace-overlay start end (current-buffer)))))
1082 ;;; replace.el ends here