1 ;;; replace.el --- replace commands for Emacs.
3 ;; Copyright (C) 1985, 86, 87, 92, 94, 96, 1997 Free Software Foundation, Inc.
5 ;; This file is part of GNU Emacs.
7 ;; GNU Emacs is free software; you can redistribute it and/or modify
8 ;; it under the terms of the GNU General Public License as published by
9 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; GNU Emacs is distributed in the hope that it will be useful,
13 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 ;; GNU General Public License for more details.
17 ;; You should have received a copy of the GNU General Public License
18 ;; along with GNU Emacs; see the file COPYING. If not, write to the
19 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20 ;; Boston, MA 02111-1307, USA.
24 ;; This package supplies the string and regular-expression replace functions
25 ;; documented in the Emacs user's manual.
29 (defcustom case-replace t
30 "*Non-nil means query-replace should preserve case in replacements."
34 (defvar query-replace-history nil)
36 (defvar query-replace-interactive nil
37 "Non-nil means `query-replace' uses the last search string.
38 That becomes the \"string to replace\".")
40 (defcustom query-replace-from-history-variable 'query-replace-history
41 "History list to use for the FROM argument of query-replace commands.
42 The value of this variable should be a symbol; that symbol
43 is used as a variable to hold a history list for the strings
44 or patterns to be replaced."
49 (defcustom query-replace-to-history-variable 'query-replace-history
50 "History list to use for the TO argument of query-replace commands.
51 The value of this variable should be a symbol; that symbol
52 is used as a variable to hold a history list for replacement
58 (defun query-replace-read-args (string regexp-flag)
60 (if query-replace-interactive
61 (setq from (car (if regexp-flag regexp-search-ring search-ring)))
62 (setq from (read-from-minibuffer (format "%s: " string)
64 query-replace-from-history-variable
66 (setq to (read-from-minibuffer (format "%s %s with: " string from)
68 query-replace-to-history-variable from t))
69 (list from to current-prefix-arg)))
71 (defun query-replace (from-string to-string &optional arg)
72 "Replace some occurrences of FROM-STRING with TO-STRING.
73 As each match is found, the user must type a character saying
74 what to do with it. For directions, type \\[help-command] at that time.
76 In Transient Mark mode, if the mark is active, operate on the contents
77 of the region. Otherwise, operate from point to the end of the buffer.
79 If `query-replace-interactive' is non-nil, the last incremental search
80 string is used as FROM-STRING--you don't have to specify it with the
83 Replacement transfers the case of the old text to the new text,
84 if `case-replace' and `case-fold-search'
85 are non-nil and FROM-STRING has no uppercase letters.
86 \(Preserving case means that if the string matched is all caps, or capitalized,
87 then its replacement is upcased or capitalized.)
89 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
90 only matches surrounded by word boundaries.
92 To customize possible responses, change the \"bindings\" in `query-replace-map'."
93 (interactive (query-replace-read-args "Query replace" nil))
94 (perform-replace from-string to-string t nil arg))
96 (define-key esc-map "%" 'query-replace)
98 (defun query-replace-regexp (regexp to-string &optional arg)
99 "Replace some things after point matching REGEXP with TO-STRING.
100 As each match is found, the user must type a character saying
101 what to do with it. For directions, type \\[help-command] at that time.
103 In Transient Mark mode, if the mark is active, operate on the contents
104 of the region. Otherwise, operate from point to the end of the buffer.
106 If `query-replace-interactive' is non-nil, the last incremental search
107 regexp is used as REGEXP--you don't have to specify it with the
110 Preserves case in each replacement if `case-replace' and `case-fold-search'
111 are non-nil and REGEXP has no uppercase letters.
112 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
113 only matches surrounded by word boundaries.
114 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
115 and `\\=\\N' (where N is a digit) stands for
116 whatever what matched the Nth `\\(...\\)' in REGEXP."
117 (interactive (query-replace-read-args "Query replace regexp" t))
118 (perform-replace regexp to-string t t arg))
119 (define-key esc-map [?\C-%] 'query-replace-regexp)
121 (defun query-replace-regexp-eval (regexp to-expr &optional arg)
122 "Replace some things after point matching REGEXP with the result of TO-EXPR.
123 As each match is found, the user must type a character saying
124 what to do with it. For directions, type \\[help-command] at that time.
126 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
127 reference `replace-count' to get the number of replacements already made.
128 If the result of TO-EXPR is not a string, it is converted to one using
129 `prin1-to-string' with the NOESCAPE argument (which see).
131 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
132 `\\0'to stand for whatever matched the whole of REGEXP, and `\\=\\N' (where
133 N is a digit) stands for whatever what matched the Nth `\\(...\\)' in REGEXP.
134 Use `\\#&' or `\\#N' if you want a number instead of a string.
136 In Transient Mark mode, if the mark is active, operate on the contents
137 of the region. Otherwise, operate from point to the end of the buffer.
139 If `query-replace-interactive' is non-nil, the last incremental search
140 regexp is used as REGEXP--you don't have to specify it with the
143 Preserves case in each replacement if `case-replace' and `case-fold-search'
144 are non-nil and REGEXP has no uppercase letters.
145 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
146 only matches surrounded by word boundaries."
149 (if query-replace-interactive
150 (setq from (car regexp-search-ring))
151 (setq from (read-from-minibuffer "Query replace regexp: "
153 query-replace-from-history-variable
155 (setq to (list (read-from-minibuffer
156 (format "Query replace regexp %s with eval: " from)
157 nil nil t query-replace-to-history-variable from t)))
158 ;; We make TO a list because replace-match-string-symbols requires one,
159 ;; and the user might enter a single token.
160 (replace-match-string-symbols to)
161 (list from (car to) current-prefix-arg)))
162 (perform-replace regexp (cons 'replace-eval-replacement to-expr) t t arg))
164 (defun map-query-replace-regexp (regexp to-strings &optional arg)
165 "Replace some matches for REGEXP with various strings, in rotation.
166 The second argument TO-STRINGS contains the replacement strings, separated
167 by spaces. This command works like `query-replace-regexp' except
168 that each successive replacement uses the next successive replacement string,
169 wrapping around from the last such string to the first.
171 In Transient Mark mode, if the mark is active, operate on the contents
172 of the region. Otherwise, operate from point to the end of the buffer.
174 Non-interactively, TO-STRINGS may be a list of replacement strings.
176 If `query-replace-interactive' is non-nil, the last incremental search
177 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
179 A prefix argument N says to use each replacement string N times
180 before rotating to the next."
183 (setq from (if query-replace-interactive
184 (car regexp-search-ring)
185 (read-from-minibuffer "Map query replace (regexp): "
187 'query-replace-history nil t)))
188 (setq to (read-from-minibuffer
189 (format "Query replace %s with (space-separated strings): "
192 'query-replace-history from t))
193 (list from to current-prefix-arg)))
195 (if (listp to-strings)
196 (setq replacements to-strings)
197 (while (/= (length to-strings) 0)
198 (if (string-match " " to-strings)
201 (list (substring to-strings 0
202 (string-match " " to-strings))))
203 to-strings (substring to-strings
204 (1+ (string-match " " to-strings))))
205 (setq replacements (append replacements (list to-strings))
207 (perform-replace regexp replacements t t nil arg)))
209 (defun replace-string (from-string to-string &optional delimited)
210 "Replace occurrences of FROM-STRING with TO-STRING.
211 Preserve case in each match if `case-replace' and `case-fold-search'
212 are non-nil and FROM-STRING has no uppercase letters.
213 \(Preserving case means that if the string matched is all caps, or capitalized,
214 then its replacement is upcased or capitalized.)
216 In Transient Mark mode, if the mark is active, operate on the contents
217 of the region. Otherwise, operate from point to the end of the buffer.
219 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
220 only matches surrounded by word boundaries.
222 If `query-replace-interactive' is non-nil, the last incremental search
223 string is used as FROM-STRING--you don't have to specify it with the
226 This function is usually the wrong thing to use in a Lisp program.
227 What you probably want is a loop like this:
228 (while (search-forward FROM-STRING nil t)
229 (replace-match TO-STRING nil t))
230 which will run faster and will not set the mark or print anything.
231 \(You may need a more complex loop if FROM-STRING can match the null string
232 and TO-STRING is also null.)"
233 (interactive (query-replace-read-args "Replace string" nil))
234 (perform-replace from-string to-string nil nil delimited))
236 (defun replace-regexp (regexp to-string &optional delimited)
237 "Replace things after point matching REGEXP with TO-STRING.
238 Preserve case in each match if `case-replace' and `case-fold-search'
239 are non-nil and REGEXP has no uppercase letters.
240 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
241 only matches surrounded by word boundaries.
242 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
243 and `\\=\\N' (where N is a digit) stands for
244 whatever what matched the Nth `\\(...\\)' in REGEXP.
246 In Transient Mark mode, if the mark is active, operate on the contents
247 of the region. Otherwise, operate from point to the end of the buffer.
249 If `query-replace-interactive' is non-nil, the last incremental search
250 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
252 This function is usually the wrong thing to use in a Lisp program.
253 What you probably want is a loop like this:
254 (while (re-search-forward REGEXP nil t)
255 (replace-match TO-STRING nil nil))
256 which will run faster and will not set the mark or print anything."
257 (interactive (query-replace-read-args "Replace regexp" t))
258 (perform-replace regexp to-string nil t delimited))
260 (defvar regexp-history nil
261 "History list for some commands that read regular expressions.")
263 (defalias 'delete-non-matching-lines 'keep-lines)
264 (defun keep-lines (regexp)
265 "Delete all lines except those containing matches for REGEXP.
266 A match split across lines preserves all the lines it lies in.
267 Applies to all lines after point.
269 If REGEXP contains upper case characters (excluding those preceded by `\\'),
270 the matching is case-sensitive."
271 (interactive (list (read-from-minibuffer
272 "Keep lines (containing match for regexp): "
273 nil nil nil 'regexp-history nil t)))
275 (or (bolp) (forward-line 1))
276 (let ((start (point))
277 (case-fold-search (and case-fold-search
278 (isearch-no-upper-case-p regexp t))))
280 ;; Start is first char not preserved by previous match.
281 (if (not (re-search-forward regexp nil 'move))
282 (delete-region start (point-max))
283 (let ((end (save-excursion (goto-char (match-beginning 0))
286 ;; Now end is first char preserved by the new match.
288 (delete-region start end))))
289 (setq start (save-excursion (forward-line 1)
291 ;; If the match was empty, avoid matching again at same place.
292 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
293 (forward-char 1))))))
295 (defalias 'delete-matching-lines 'flush-lines)
296 (defun flush-lines (regexp)
297 "Delete lines containing matches for REGEXP.
298 If a match is split across lines, all the lines it lies in are deleted.
299 Applies to lines after point.
301 If REGEXP contains upper case characters (excluding those preceded by `\\'),
302 the matching is case-sensitive."
303 (interactive (list (read-from-minibuffer
304 "Flush lines (containing match for regexp): "
305 nil nil nil 'regexp-history nil t)))
306 (let ((case-fold-search (and case-fold-search
307 (isearch-no-upper-case-p regexp t))))
309 (while (and (not (eobp))
310 (re-search-forward regexp nil t))
311 (delete-region (save-excursion (goto-char (match-beginning 0))
314 (progn (forward-line 1) (point)))))))
316 (defalias 'count-matches 'how-many)
317 (defun how-many (regexp)
318 "Print number of matches for REGEXP following point.
320 If REGEXP contains upper case characters (excluding those preceded by `\\'),
321 the matching is case-sensitive."
322 (interactive (list (read-from-minibuffer
323 "How many matches for (regexp): "
324 nil nil nil 'regexp-history nil t)))
325 (let ((count 0) opoint
326 (case-fold-search (and case-fold-search
327 (isearch-no-upper-case-p regexp t))))
329 (while (and (not (eobp))
330 (progn (setq opoint (point))
331 (re-search-forward regexp nil t)))
332 (if (= opoint (point))
334 (setq count (1+ count))))
335 (message "%d occurrences" count))))
337 (defvar occur-mode-map ())
340 (setq occur-mode-map (make-sparse-keymap))
341 (define-key occur-mode-map [mouse-2] 'occur-mode-mouse-goto)
342 (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence)
343 (define-key occur-mode-map "\C-m" 'occur-mode-goto-occurrence)
344 (define-key occur-mode-map "\M-n" 'occur-next)
345 (define-key occur-mode-map "\M-p" 'occur-prev)
346 (define-key occur-mode-map "g" 'revert-buffer))
349 (defvar occur-buffer nil
350 "Name of buffer for last occur.")
353 (defvar occur-nlines nil
354 "Number of lines of context to show around matching line.")
356 (defvar occur-command-arguments nil
357 "Arguments that were given to `occur' when it made this buffer.")
359 (put 'occur-mode 'mode-class 'special)
362 "Major mode for output from \\[occur].
363 \\<occur-mode-map>Move point to one of the items in this buffer, then use
364 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
365 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
368 (kill-all-local-variables)
369 (use-local-map occur-mode-map)
370 (setq major-mode 'occur-mode)
371 (setq mode-name "Occur")
372 (make-local-variable 'revert-buffer-function)
373 (setq revert-buffer-function 'occur-revert-function)
374 (make-local-variable 'occur-buffer)
375 (make-local-variable 'occur-nlines)
376 (make-local-variable 'occur-command-arguments)
377 (run-hooks 'occur-mode-hook))
379 ;; Handle revert-buffer for *Occur* buffers.
380 (defun occur-revert-function (ignore1 ignore2)
381 (let ((args occur-command-arguments ))
383 (set-buffer occur-buffer)
384 (apply 'occur args))))
386 (defun occur-mode-mouse-goto (event)
387 "In Occur mode, go to the occurrence whose line you click on."
391 (set-buffer (window-buffer (posn-window (event-end event))))
393 (goto-char (posn-point (event-end event)))
394 (setq pos (occur-mode-find-occurrence))
395 (setq buffer occur-buffer)))
396 (pop-to-buffer buffer)
397 (goto-char (marker-position pos))))
399 (defun occur-mode-find-occurrence ()
400 (if (or (null occur-buffer)
401 (null (buffer-name occur-buffer)))
403 (setq occur-buffer nil)
404 (error "Buffer in which occurrences were found is deleted")))
405 (let ((pos (get-text-property (point) 'occur)))
407 (error "No occurrence on this line")
410 (defun occur-mode-goto-occurrence ()
411 "Go to the occurrence the current line describes."
413 (let ((pos (occur-mode-find-occurrence)))
414 (pop-to-buffer occur-buffer)
415 (goto-char (marker-position pos))))
417 (defun occur-next (&optional n)
418 "Move to the Nth (default 1) next match in the *Occur* buffer."
420 (if (not n) (setq n 1))
423 (if (get-text-property (point) 'occur-point)
425 (setq r (next-single-property-change (point) 'occur-point))
428 (error "no more matches"))
433 (defun occur-prev (&optional n)
434 "Move to the Nth (default 1) previous match in the *Occur* buffer."
436 (if (not n) (setq n 1))
440 (setq r (get-text-property (point) 'occur-point))
441 (if r (forward-char -1))
443 (setq r (previous-single-property-change (point) 'occur-point))
446 (error "no earlier matches"))
450 (defcustom list-matching-lines-default-context-lines 0
451 "*Default number of context lines to include around a `list-matching-lines'
452 match. A negative number means to include that many lines before the match.
453 A positive number means to include that many lines both before and after."
457 (defalias 'list-matching-lines 'occur)
459 (defvar list-matching-lines-face 'bold
460 "*Face used by M-x list-matching-lines to show the text that matches.
461 If the value is nil, don't highlight the matching portions specially.")
463 (defun occur (regexp &optional nlines)
464 "Show all lines in the current buffer containing a match for REGEXP.
466 If a match spreads across multiple lines, all those lines are shown.
468 Each line is displayed with NLINES lines before and after, or -NLINES
469 before if NLINES is negative.
470 NLINES defaults to `list-matching-lines-default-context-lines'.
471 Interactively it is the prefix arg.
473 The lines are shown in a buffer named `*Occur*'.
474 It serves as a menu to find any of the occurrences in this buffer.
475 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
477 If REGEXP contains upper case characters (excluding those preceded by `\\'),
478 the matching is case-sensitive."
480 (list (let* ((default (car regexp-history))
482 (read-from-minibuffer
484 (format "List lines matching regexp (default `%s'): "
486 "List lines matching regexp: ")
487 nil nil nil 'regexp-history default t)))
488 (and (equal input "") default
489 (setq input default))
492 (let ((nlines (if nlines
493 (prefix-numeric-value nlines)
494 list-matching-lines-default-context-lines))
496 ;;flag to prevent printing separator for first match
497 (occur-num-matches 0)
498 (buffer (current-buffer))
499 (dir default-directory)
502 ;;position of most recent match
504 (case-fold-search (and case-fold-search
505 (isearch-no-upper-case-p regexp t)))
507 ;; Marker to the start of context immediately following
508 ;; the matched text in *Occur*.
511 ;;; (beginning-of-line)
512 ;;; (setq linenum (1+ (count-lines (point-min) (point))))
513 ;;; (setq prevpos (point)))
515 (goto-char (point-min))
516 ;; Check first whether there are any matches at all.
517 (if (not (re-search-forward regexp nil t))
518 (message "No matches for `%s'" regexp)
519 ;; Back up, so the search loop below will find the first match.
520 (goto-char (match-beginning 0))
521 (with-output-to-temp-buffer "*Occur*"
523 (set-buffer standard-output)
524 (setq default-directory dir)
525 ;; We will insert the number of lines, and "lines", later.
526 (insert " matching ")
527 (let ((print-escape-newlines t))
529 (insert " in buffer " (buffer-name buffer) ?. ?\n)
531 (setq occur-buffer buffer)
532 (setq occur-nlines nlines)
533 (setq occur-command-arguments
534 (list regexp nlines)))
535 (if (eq buffer standard-output)
536 (goto-char (point-max)))
538 ;; Find next match, but give up if prev match was at end of buffer.
539 (while (and (not (= prevpos (point-max)))
540 (re-search-forward regexp nil t))
541 (goto-char (match-beginning 0))
544 (setq linenum (+ linenum (count-lines prevpos (point)))))
545 (setq prevpos (point))
546 (goto-char (match-end 0))
548 ;;start point of text in source buffer to be put
551 (goto-char (match-beginning 0))
552 (forward-line (if (< nlines 0)
557 ;; end point of text in source buffer to be put
560 (goto-char (match-end 0))
562 (forward-line (1+ nlines))
566 ;; Amount of context before matching text
567 (- (match-beginning 0) start))
569 ;; Length of matching text
570 (- (match-end 0) (match-beginning 0)))
571 (tag (format "%5d" linenum))
572 (empty (make-string (length tag) ?\ ))
575 ;; Number of lines of context to show for current match.
577 ;; Marker pointing to end of match in source buffer.
579 ;; Marker pointing to start of text for one
583 ;; Marker pointing to end of text for one match
588 (setq occur-marker (make-marker))
589 (set-marker occur-marker (point))
590 (set-buffer standard-output)
591 (setq occur-num-matches (1+ occur-num-matches))
592 (or first (zerop nlines)
593 (insert "--------\n"))
596 ;; Insert matching text including context lines from
597 ;; source buffer into *Occur*
598 (set-marker text-beg (point))
599 (setq insertion-start (point))
600 (insert-buffer-substring buffer start end)
601 (or (and (/= (+ start match-beg) end)
602 (with-current-buffer buffer
603 (eq (char-before end) ?\n)))
605 (set-marker final-context-start
606 (+ (- (point) (- end (match-end 0)))
610 (goto-char (match-end 0))
614 (set-marker text-end (point))
616 ;; Highlight text that was matched.
617 (if list-matching-lines-face
619 (+ (marker-position text-beg) match-beg)
620 (+ (marker-position text-beg) match-beg match-len)
621 'face list-matching-lines-face))
623 ;; `occur-point' property is used by occur-next and
624 ;; occur-prev to move between matching lines.
626 (+ (marker-position text-beg) match-beg match-len)
627 (+ (marker-position text-beg) match-beg match-len 1)
630 ;; Now go back to the start of the matching text
631 ;; adding the space and colon to the start of each line.
632 (goto-char insertion-start)
633 ;; Insert space and colon for lines of context before match.
634 (setq tem (if (< linenum nlines)
642 ;; Insert line number and colon for the lines of
644 (let ((this-linenum linenum))
645 (while (< (point) final-context-start)
647 (setq tag (format "%5d" this-linenum)))
651 (setq this-linenum (1+ this-linenum)))
652 (while (and (not (eobp)) (<= (point) final-context-start))
655 (setq this-linenum (1+ this-linenum))))
657 ;; Insert space and colon for lines of context after match.
658 (while (and (< (point) (point-max)) (< tem nlines))
663 ;; Add text properties. The `occur' prop is used to
664 ;; store the marker of the matching text in the
666 (put-text-property (marker-position text-beg)
667 (- (marker-position text-end) 1)
668 'mouse-face 'highlight)
669 (put-text-property (marker-position text-beg)
670 (marker-position text-end)
672 (goto-char (point-max)))
674 (set-buffer standard-output)
675 ;; Go back to top of *Occur* and finish off by printing the
676 ;; number of matching lines.
677 (goto-char (point-min))
678 (let ((message-string
679 (if (= occur-num-matches 1)
681 (format "%d lines" occur-num-matches))))
682 (insert message-string)
684 (message "%s matched" message-string)))
685 (setq buffer-read-only t)))))))
687 ;; It would be nice to use \\[...], but there is no reasonable way
688 ;; to make that display both SPC and Y.
689 (defconst query-replace-help
690 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
691 RET or `q' to exit, Period to replace one match and exit,
692 Comma to replace but not move point immediately,
693 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
694 C-w to delete match and recursive edit,
695 C-l to clear the screen, redisplay, and offer same replacement again,
696 ! to replace all remaining matches with no more questions,
697 ^ to move point back to previous match."
698 "Help message while in query-replace")
700 (defvar query-replace-map (make-sparse-keymap)
701 "Keymap that defines the responses to questions in `query-replace'.
702 The \"bindings\" in this map are not commands; they are answers.
703 The valid answers include `act', `skip', `act-and-show',
704 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
705 `automatic', `backup', `exit-prefix', and `help'.")
707 (define-key query-replace-map " " 'act)
708 (define-key query-replace-map "\d" 'skip)
709 (define-key query-replace-map [delete] 'skip)
710 (define-key query-replace-map [backspace] 'skip)
711 (define-key query-replace-map "y" 'act)
712 (define-key query-replace-map "n" 'skip)
713 (define-key query-replace-map "Y" 'act)
714 (define-key query-replace-map "N" 'skip)
715 (define-key query-replace-map "," 'act-and-show)
716 (define-key query-replace-map "q" 'exit)
717 (define-key query-replace-map "\r" 'exit)
718 (define-key query-replace-map [return] 'exit)
719 (define-key query-replace-map "." 'act-and-exit)
720 (define-key query-replace-map "\C-r" 'edit)
721 (define-key query-replace-map "\C-w" 'delete-and-edit)
722 (define-key query-replace-map "\C-l" 'recenter)
723 (define-key query-replace-map "!" 'automatic)
724 (define-key query-replace-map "^" 'backup)
725 (define-key query-replace-map "\C-h" 'help)
726 (define-key query-replace-map [f1] 'help)
727 (define-key query-replace-map [help] 'help)
728 (define-key query-replace-map "?" 'help)
729 (define-key query-replace-map "\C-g" 'quit)
730 (define-key query-replace-map "\C-]" 'quit)
731 (define-key query-replace-map "\e" 'exit-prefix)
732 (define-key query-replace-map [escape] 'exit-prefix)
734 (defun replace-match-string-symbols (n)
735 ;; Process a list (and any sub-lists), expanding certain symbols:
737 ;; N (match-string N) (where N is a string of digits)
738 ;; #N (string-to-number (match-string N))
739 ;; & (match-string 0)
740 ;; #& (string-to-number (match-string 0))
742 ;; Note that these symbols must be preceeded by a backslash in order to
747 (replace-match-string-symbols (car n))) ;Process sub-list
749 (let ((name (symbol-name (car n))))
751 ((string-match "^[0-9]+$" name)
752 (setcar n (list 'match-string (string-to-number name))))
753 ((string-match "^#[0-9]+$" name)
754 (setcar n (list 'string-to-number
756 (string-to-number (substring name 1))))))
758 (setcar n '(match-string 0)))
760 (setcar n '(string-to-number (match-string 0))))))))
763 (defun replace-eval-replacement (expression replace-count)
764 (let ((replacement (eval expression)))
765 (if (stringp replacement)
767 (prin1-to-string replacement t))))
769 (defun replace-loop-through-replacements (data replace-count)
770 ;; DATA is a vector contaning the following values:
771 ;; 0 next-rotate-count
773 ;; 2 next-replacement
775 (if (= (aref data 0) replace-count)
777 (aset data 0 (+ replace-count (aref data 1)))
778 (let ((next (cdr (aref data 2))))
779 (aset data 2 (if (consp next) next (aref data 3))))))
782 (defun perform-replace (from-string replacements
783 query-flag regexp-flag delimited-flag
784 &optional repeat-count map)
785 "Subroutine of `query-replace'. Its complexity handles interactive queries.
786 Don't use this in your own program unless you want to query and set the mark
787 just as `query-replace' does. Instead, write a simple loop like this:
788 (while (re-search-forward \"foo[ \t]+bar\" nil t)
789 (replace-match \"foobar\" nil nil))
790 which will run faster and probably do exactly what you want."
791 (or map (setq map query-replace-map))
792 (and query-flag minibuffer-auto-raise
793 (raise-frame (window-frame (minibuffer-window))))
794 (let ((nocasify (not (and case-fold-search case-replace
795 (string-equal from-string
796 (downcase from-string)))))
797 (case-fold-search (and case-fold-search
798 (string-equal from-string
799 (downcase from-string))))
800 (literal (not regexp-flag))
801 (search-function (if regexp-flag 're-search-forward 'search-forward))
802 (search-string from-string)
803 (real-match-data nil) ; the match data for the current match
804 (next-replacement nil)
810 ;; If non-nil, it is marker saying where in the buffer to stop.
813 ;; Data for the next match. If a cons, it has the same format as
814 ;; (match-data); otherwise it is t if a match is possible at point.
819 (substitute-command-keys
820 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
822 ;; If region is active, in Transient Mark mode, operate on region.
823 (if (and transient-mark-mode mark-active)
825 (setq limit (copy-marker (region-end)))
826 (goto-char (region-beginning))
829 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
830 ;; containing a function and its first argument. The function is
831 ;; called to generate each replacement like this:
832 ;; (funcall (car replacements) (cdr replacements) replace-count)
833 ;; It must return a string.
835 ((stringp replacements)
836 (setq next-replacement replacements
838 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
839 (or repeat-count (setq repeat-count 1))
840 (setq replacements (cons 'replace-loop-through-replacements
841 (vector repeat-count repeat-count
842 replacements replacements)))))
845 (setq search-function 're-search-forward
846 search-string (concat "\\b"
847 (if regexp-flag from-string
848 (regexp-quote from-string))
853 ;; Loop finding occurrences that perhaps should be replaced.
854 (while (and keep-going
856 ;; Use the next match if it is already known;
857 ;; otherwise, search for a match after moving forward
858 ;; one char if progress is required.
859 (setq real-match-data
860 (if (consp match-again)
861 (progn (goto-char (nth 1 match-again))
867 (funcall search-function search-string limit t)
868 ;; For speed, use only integers and
869 ;; reuse the list used last time.
870 (match-data t real-match-data)))))
872 ;; Record whether the match is nonempty, to avoid an infinite loop
873 ;; repeatedly matching the same empty string.
875 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
877 ;; If the match is empty, record that the next one can't be adjacent.
878 ;; Otherwise, if matching a regular expression, do the next
879 ;; match now, since the replacement for this match may
880 ;; affect whether the next match is adjacent to this one.
883 (or (not regexp-flag)
884 (and (looking-at search-string)
887 ;; Calculate the replacement string, if necessary.
889 (set-match-data real-match-data)
890 (setq next-replacement
891 (funcall (car replacements) (cdr replacements)
895 (set-match-data real-match-data)
896 (replace-match next-replacement nocasify literal)
897 (setq replace-count (1+ replace-count)))
899 (let (done replaced key def)
900 ;; Loop reading commands until one of them sets done,
901 ;; which means it has finished handling this occurrence.
903 (set-match-data real-match-data)
904 (replace-highlight (match-beginning 0) (match-end 0))
905 ;; Bind message-log-max so we don't fill up the message log
906 ;; with a bunch of identical messages.
907 (let ((message-log-max nil))
908 (message message from-string next-replacement))
909 (setq key (read-event))
910 ;; Necessary in case something happens during read-event
911 ;; that clobbers the match data.
912 (set-match-data real-match-data)
913 (setq key (vector key))
914 (setq def (lookup-key map key))
915 ;; Restore the match data while we process the command.
916 (cond ((eq def 'help)
917 (with-output-to-temp-buffer "*Help*"
919 (concat "Query replacing "
920 (if regexp-flag "regexp " "")
922 next-replacement ".\n\n"
923 (substitute-command-keys
924 query-replace-help)))
926 (set-buffer standard-output)
929 (setq keep-going nil)
933 (let ((elt (car stack)))
934 (goto-char (car elt))
935 (setq replaced (eq t (cdr elt)))
937 (set-match-data (cdr elt)))
938 (setq stack (cdr stack)))
939 (message "No previous match")
945 (replace-match next-replacement nocasify literal)
946 (setq replace-count (1+ replace-count))))
947 (setq done t replaced t))
948 ((eq def 'act-and-exit)
951 (replace-match next-replacement nocasify literal)
952 (setq replace-count (1+ replace-count))))
953 (setq keep-going nil)
954 (setq done t replaced t))
955 ((eq def 'act-and-show)
958 (replace-match next-replacement nocasify literal)
959 (setq replace-count (1+ replace-count))
964 (replace-match next-replacement nocasify literal)
965 (setq replace-count (1+ replace-count))))
966 (setq done t query-flag nil replaced t))
972 (let ((opos (point-marker)))
973 (goto-char (match-beginning 0))
975 (funcall search-function search-string limit t)
976 (setq real-match-data (match-data)))
977 (save-excursion (recursive-edit))
979 (set-match-data real-match-data)
980 ;; Before we make the replacement,
981 ;; decide whether the search string
982 ;; can match again just after this match.
983 (if (and regexp-flag nonempty-match)
984 (setq match-again (and (looking-at search-string)
986 ((eq def 'delete-and-edit)
987 (delete-region (match-beginning 0) (match-end 0))
990 (save-excursion (recursive-edit))))
992 ;; Note: we do not need to treat `exit-prefix'
993 ;; specially here, since we reread
994 ;; any unrecognized character.
996 (setq this-command 'mode-exited)
997 (setq keep-going nil)
998 (setq unread-command-events
999 (append (listify-key-sequence key)
1000 unread-command-events))
1002 ;; Record previous position for ^ when we move on.
1003 ;; Change markers to numbers in the match data
1004 ;; since lots of markers slow down editing.
1007 (or replaced (match-data t)))
1009 (replace-dehighlight))
1010 (or unread-command-events
1011 (message "Replaced %d occurrence%s"
1013 (if (= replace-count 1) "" "s")))
1014 (and keep-going stack)))
1016 (defcustom query-replace-highlight t
1017 "*Non-nil means to highlight words during query replacement."
1021 (defvar replace-overlay nil)
1023 (defun replace-dehighlight ()
1024 (and replace-overlay
1026 (delete-overlay replace-overlay)
1027 (setq replace-overlay nil))))
1029 (defun replace-highlight (start end)
1030 (and query-replace-highlight
1034 (setq replace-overlay (make-overlay start end))
1035 (overlay-put replace-overlay 'face
1036 (if (internal-find-face 'query-replace)
1037 'query-replace 'region))))
1038 (move-overlay replace-overlay start end (current-buffer)))))
1040 ;;; replace.el ends here