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 (list from to current-prefix-arg
)))
72 (defun query-replace (from-string to-string
&optional delimited
)
73 "Replace some occurrences of FROM-STRING with TO-STRING.
74 As each match is found, the user must type a character saying
75 what to do with it. For directions, type \\[help-command] at that time.
77 In Transient Mark mode, if the mark is active, operate on the contents
78 of the region. Otherwise, operate from point to the end of the buffer.
80 If `query-replace-interactive' is non-nil, the last incremental search
81 string is used as FROM-STRING--you don't have to specify it with the
84 Replacement transfers the case of the old text to the new text,
85 if `case-replace' and `case-fold-search'
86 are non-nil and FROM-STRING has no uppercase letters.
87 \(Preserving case means that if the string matched is all caps, or capitalized,
88 then its replacement is upcased or capitalized.)
90 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
91 only matches surrounded by word boundaries.
93 To customize possible responses, change the \"bindings\" in `query-replace-map'."
94 (interactive (query-replace-read-args "Query replace" nil
))
95 (perform-replace from-string to-string t nil delimited
))
97 (define-key esc-map
"%" 'query-replace
)
99 (defun query-replace-regexp (regexp to-string
&optional delimited
)
100 "Replace some things after point matching REGEXP with TO-STRING.
101 As each match is found, the user must type a character saying
102 what to do with it. For directions, type \\[help-command] at that time.
104 In Transient Mark mode, if the mark is active, operate on the contents
105 of the region. Otherwise, operate from point to the end of the buffer.
107 If `query-replace-interactive' is non-nil, the last incremental search
108 regexp is used as REGEXP--you don't have to specify it with the
111 Preserves case in each replacement if `case-replace' and `case-fold-search'
112 are non-nil and REGEXP has no uppercase letters.
113 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
114 only matches surrounded by word boundaries.
115 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
116 and `\\=\\N' (where N is a digit) stands for
117 whatever what matched the Nth `\\(...\\)' in REGEXP."
118 (interactive (query-replace-read-args "Query replace regexp" t
))
119 (perform-replace regexp to-string t t delimited
))
120 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
122 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited
)
123 "Replace some things after point matching REGEXP with the result of TO-EXPR.
124 As each match is found, the user must type a character saying
125 what to do with it. For directions, type \\[help-command] at that time.
127 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
128 reference `replace-count' to get the number of replacements already made.
129 If the result of TO-EXPR is not a string, it is converted to one using
130 `prin1-to-string' with the NOESCAPE argument (which see).
132 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
133 `\\0'to stand for whatever matched the whole of REGEXP, and `\\=\\N' (where
134 N is a digit) stands for whatever what matched the Nth `\\(...\\)' in REGEXP.
135 Use `\\#&' or `\\#N' if you want a number instead of a string.
137 In Transient Mark mode, if the mark is active, operate on the contents
138 of the region. Otherwise, operate from point to the end of the buffer.
140 If `query-replace-interactive' is non-nil, the last incremental search
141 regexp is used as REGEXP--you don't have to specify it with the
144 Preserves case in each replacement if `case-replace' and `case-fold-search'
145 are non-nil and REGEXP has no uppercase letters.
146 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
147 only matches surrounded by word boundaries."
150 (if query-replace-interactive
151 (setq from
(car regexp-search-ring
))
152 (setq from
(read-from-minibuffer "Query replace regexp: "
154 query-replace-from-history-variable
156 (setq to
(list (read-from-minibuffer
157 (format "Query replace regexp %s with eval: " from
)
158 nil nil t query-replace-to-history-variable from t
)))
159 ;; We make TO a list because replace-match-string-symbols requires one,
160 ;; and the user might enter a single token.
161 (replace-match-string-symbols to
)
162 (list from
(car to
) current-prefix-arg
)))
163 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
166 (defun map-query-replace-regexp (regexp to-strings
&optional delimited
)
167 "Replace some matches for REGEXP with various strings, in rotation.
168 The second argument TO-STRINGS contains the replacement strings, separated
169 by spaces. This command works like `query-replace-regexp' except
170 that each successive replacement uses the next successive replacement string,
171 wrapping around from the last such string to the first.
173 In Transient Mark mode, if the mark is active, operate on the contents
174 of the region. Otherwise, operate from point to the end of the buffer.
176 Non-interactively, TO-STRINGS may be a list of replacement strings.
178 If `query-replace-interactive' is non-nil, the last incremental search
179 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
181 A prefix argument N says to use each replacement string N times
182 before rotating to the next."
185 (setq from
(if query-replace-interactive
186 (car regexp-search-ring
)
187 (read-from-minibuffer "Map query replace (regexp): "
189 'query-replace-history nil t
)))
190 (setq to
(read-from-minibuffer
191 (format "Query replace %s with (space-separated strings): "
194 'query-replace-history from t
))
195 (list from to current-prefix-arg
)))
197 (if (listp to-strings
)
198 (setq replacements to-strings
)
199 (while (/= (length to-strings
) 0)
200 (if (string-match " " to-strings
)
203 (list (substring to-strings
0
204 (string-match " " to-strings
))))
205 to-strings
(substring to-strings
206 (1+ (string-match " " to-strings
))))
207 (setq replacements
(append replacements
(list to-strings
))
209 (perform-replace regexp replacements t t nil delimited
)))
211 (defun replace-string (from-string to-string
&optional delimited
)
212 "Replace occurrences of FROM-STRING with TO-STRING.
213 Preserve case in each match if `case-replace' and `case-fold-search'
214 are non-nil and FROM-STRING has no uppercase letters.
215 \(Preserving case means that if the string matched is all caps, or capitalized,
216 then its replacement is upcased or capitalized.)
218 In Transient Mark mode, if the mark is active, operate on the contents
219 of the region. Otherwise, operate from point to the end of the buffer.
221 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
222 only matches surrounded by word boundaries.
224 If `query-replace-interactive' is non-nil, the last incremental search
225 string is used as FROM-STRING--you don't have to specify it with the
228 This function is usually the wrong thing to use in a Lisp program.
229 What you probably want is a loop like this:
230 (while (search-forward FROM-STRING nil t)
231 (replace-match TO-STRING nil t))
232 which will run faster and will not set the mark or print anything.
233 \(You may need a more complex loop if FROM-STRING can match the null string
234 and TO-STRING is also null.)"
235 (interactive (query-replace-read-args "Replace string" nil
))
236 (perform-replace from-string to-string nil nil delimited
))
238 (defun replace-regexp (regexp to-string
&optional delimited
)
239 "Replace things after point matching REGEXP with TO-STRING.
240 Preserve case in each match if `case-replace' and `case-fold-search'
241 are non-nil and REGEXP has no uppercase letters.
242 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
243 only matches surrounded by word boundaries.
244 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
245 and `\\=\\N' (where N is a digit) stands for
246 whatever what matched the Nth `\\(...\\)' in REGEXP.
248 In Transient Mark mode, if the mark is active, operate on the contents
249 of the region. Otherwise, operate from point to the end of the buffer.
251 If `query-replace-interactive' is non-nil, the last incremental search
252 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
254 This function is usually the wrong thing to use in a Lisp program.
255 What you probably want is a loop like this:
256 (while (re-search-forward REGEXP nil t)
257 (replace-match TO-STRING nil nil))
258 which will run faster and will not set the mark or print anything."
259 (interactive (query-replace-read-args "Replace regexp" t
))
260 (perform-replace regexp to-string nil t delimited
))
262 (defvar regexp-history nil
263 "History list for some commands that read regular expressions.")
265 (defalias 'delete-non-matching-lines
'keep-lines
)
266 (defun keep-lines (regexp)
267 "Delete all lines except those containing matches for REGEXP.
268 A match split across lines preserves all the lines it lies in.
269 Applies to all lines after point.
271 If REGEXP contains upper case characters (excluding those preceded by `\\'),
272 the matching is case-sensitive."
273 (interactive (list (read-from-minibuffer
274 "Keep lines (containing match for regexp): "
275 nil nil nil
'regexp-history nil t
)))
277 (or (bolp) (forward-line 1))
278 (let ((start (point))
279 (case-fold-search (and case-fold-search
280 (isearch-no-upper-case-p regexp t
))))
282 ;; Start is first char not preserved by previous match.
283 (if (not (re-search-forward regexp nil
'move
))
284 (delete-region start
(point-max))
285 (let ((end (save-excursion (goto-char (match-beginning 0))
288 ;; Now end is first char preserved by the new match.
290 (delete-region start end
))))
291 (setq start
(save-excursion (forward-line 1)
293 ;; If the match was empty, avoid matching again at same place.
294 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
295 (forward-char 1))))))
297 (defalias 'delete-matching-lines
'flush-lines
)
298 (defun flush-lines (regexp)
299 "Delete lines containing matches for REGEXP.
300 If a match is split across lines, all the lines it lies in are deleted.
301 Applies to lines after point.
303 If REGEXP contains upper case characters (excluding those preceded by `\\'),
304 the matching is case-sensitive."
305 (interactive (list (read-from-minibuffer
306 "Flush lines (containing match for regexp): "
307 nil nil nil
'regexp-history nil t
)))
308 (let ((case-fold-search (and case-fold-search
309 (isearch-no-upper-case-p regexp t
))))
311 (while (and (not (eobp))
312 (re-search-forward regexp nil t
))
313 (delete-region (save-excursion (goto-char (match-beginning 0))
316 (progn (forward-line 1) (point)))))))
318 (defalias 'count-matches
'how-many
)
319 (defun how-many (regexp)
320 "Print number of matches for REGEXP following point.
322 If REGEXP contains upper case characters (excluding those preceded by `\\'),
323 the matching is case-sensitive."
324 (interactive (list (read-from-minibuffer
325 "How many matches for (regexp): "
326 nil nil nil
'regexp-history nil t
)))
327 (let ((count 0) opoint
328 (case-fold-search (and case-fold-search
329 (isearch-no-upper-case-p regexp t
))))
331 (while (and (not (eobp))
332 (progn (setq opoint
(point))
333 (re-search-forward regexp nil t
)))
334 (if (= opoint
(point))
336 (setq count
(1+ count
))))
337 (message "%d occurrences" count
))))
339 (defvar occur-mode-map
())
342 (setq occur-mode-map
(make-sparse-keymap))
343 (define-key occur-mode-map
[mouse-2
] 'occur-mode-mouse-goto
)
344 (define-key occur-mode-map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
345 (define-key occur-mode-map
"\C-m" 'occur-mode-goto-occurrence
)
346 (define-key occur-mode-map
"\M-n" 'occur-next
)
347 (define-key occur-mode-map
"\M-p" 'occur-prev
)
348 (define-key occur-mode-map
"g" 'revert-buffer
))
351 (defvar occur-buffer nil
352 "Name of buffer for last occur.")
355 (defvar occur-nlines nil
356 "Number of lines of context to show around matching line.")
358 (defvar occur-command-arguments nil
359 "Arguments that were given to `occur' when it made this buffer.")
361 (put 'occur-mode
'mode-class
'special
)
364 "Major mode for output from \\[occur].
365 \\<occur-mode-map>Move point to one of the items in this buffer, then use
366 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
367 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
370 (kill-all-local-variables)
371 (use-local-map occur-mode-map
)
372 (setq major-mode
'occur-mode
)
373 (setq mode-name
"Occur")
374 (make-local-variable 'revert-buffer-function
)
375 (setq revert-buffer-function
'occur-revert-function
)
376 (make-local-variable 'occur-buffer
)
377 (make-local-variable 'occur-nlines
)
378 (make-local-variable 'occur-command-arguments
)
379 (run-hooks 'occur-mode-hook
))
381 ;; Handle revert-buffer for *Occur* buffers.
382 (defun occur-revert-function (ignore1 ignore2
)
383 (let ((args occur-command-arguments
))
385 (set-buffer occur-buffer
)
386 (apply 'occur args
))))
388 (defun occur-mode-mouse-goto (event)
389 "In Occur mode, go to the occurrence whose line you click on."
393 (set-buffer (window-buffer (posn-window (event-end event
))))
395 (goto-char (posn-point (event-end event
)))
396 (setq pos
(occur-mode-find-occurrence))
397 (setq buffer occur-buffer
)))
398 (pop-to-buffer buffer
)
399 (goto-char (marker-position pos
))))
401 (defun occur-mode-find-occurrence ()
402 (if (or (null occur-buffer
)
403 (null (buffer-name occur-buffer
)))
405 (setq occur-buffer nil
)
406 (error "Buffer in which occurrences were found is deleted")))
407 (let ((pos (get-text-property (point) 'occur
)))
409 (error "No occurrence on this line")
412 (defun occur-mode-goto-occurrence ()
413 "Go to the occurrence the current line describes."
415 (let ((pos (occur-mode-find-occurrence)))
416 (pop-to-buffer occur-buffer
)
417 (goto-char (marker-position pos
))))
419 (defun occur-next (&optional n
)
420 "Move to the Nth (default 1) next match in the *Occur* buffer."
422 (if (not n
) (setq n
1))
425 (if (get-text-property (point) 'occur-point
)
427 (setq r
(next-single-property-change (point) 'occur-point
))
430 (error "no more matches"))
435 (defun occur-prev (&optional n
)
436 "Move to the Nth (default 1) previous match in the *Occur* buffer."
438 (if (not n
) (setq n
1))
442 (setq r
(get-text-property (point) 'occur-point
))
443 (if r
(forward-char -
1))
445 (setq r
(previous-single-property-change (point) 'occur-point
))
448 (error "no earlier matches"))
452 (defcustom list-matching-lines-default-context-lines
0
453 "*Default number of context lines to include around a `list-matching-lines'
454 match. A negative number means to include that many lines before the match.
455 A positive number means to include that many lines both before and after."
459 (defalias 'list-matching-lines
'occur
)
461 (defvar list-matching-lines-face
'bold
462 "*Face used by M-x list-matching-lines to show the text that matches.
463 If the value is nil, don't highlight the matching portions specially.")
465 (defun occur (regexp &optional nlines
)
466 "Show all lines in the current buffer containing a match for REGEXP.
468 If a match spreads across multiple lines, all those lines are shown.
470 Each line is displayed with NLINES lines before and after, or -NLINES
471 before if NLINES is negative.
472 NLINES defaults to `list-matching-lines-default-context-lines'.
473 Interactively it is the prefix arg.
475 The lines are shown in a buffer named `*Occur*'.
476 It serves as a menu to find any of the occurrences in this buffer.
477 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
479 If REGEXP contains upper case characters (excluding those preceded by `\\'),
480 the matching is case-sensitive."
482 (list (let* ((default (car regexp-history
))
484 (read-from-minibuffer
486 (format "List lines matching regexp (default `%s'): "
488 "List lines matching regexp: ")
489 nil nil nil
'regexp-history default t
)))
490 (and (equal input
"") default
491 (setq input default
))
494 (let ((nlines (if nlines
495 (prefix-numeric-value nlines
)
496 list-matching-lines-default-context-lines
))
498 ;;flag to prevent printing separator for first match
499 (occur-num-matches 0)
500 (buffer (current-buffer))
501 (dir default-directory
)
504 ;;position of most recent match
506 (case-fold-search (and case-fold-search
507 (isearch-no-upper-case-p regexp t
)))
509 ;; Marker to the start of context immediately following
510 ;; the matched text in *Occur*.
513 ;;; (beginning-of-line)
514 ;;; (setq linenum (1+ (count-lines (point-min) (point))))
515 ;;; (setq prevpos (point)))
517 (goto-char (point-min))
518 ;; Check first whether there are any matches at all.
519 (if (not (re-search-forward regexp nil t
))
520 (message "No matches for `%s'" regexp
)
521 ;; Back up, so the search loop below will find the first match.
522 (goto-char (match-beginning 0))
523 (with-output-to-temp-buffer "*Occur*"
525 (set-buffer standard-output
)
526 (setq default-directory dir
)
527 ;; We will insert the number of lines, and "lines", later.
528 (insert " matching ")
529 (let ((print-escape-newlines t
))
531 (insert " in buffer " (buffer-name buffer
) ?. ?
\n)
533 (setq occur-buffer buffer
)
534 (setq occur-nlines nlines
)
535 (setq occur-command-arguments
536 (list regexp nlines
)))
537 (if (eq buffer standard-output
)
538 (goto-char (point-max)))
540 ;; Find next match, but give up if prev match was at end of buffer.
541 (while (and (not (= prevpos
(point-max)))
542 (re-search-forward regexp nil t
))
543 (goto-char (match-beginning 0))
546 (setq linenum
(+ linenum
(count-lines prevpos
(point)))))
547 (setq prevpos
(point))
548 (goto-char (match-end 0))
550 ;;start point of text in source buffer to be put
553 (goto-char (match-beginning 0))
554 (forward-line (if (< nlines
0)
559 ;; end point of text in source buffer to be put
562 (goto-char (match-end 0))
564 (forward-line (1+ nlines
))
568 ;; Amount of context before matching text
569 (- (match-beginning 0) start
))
571 ;; Length of matching text
572 (- (match-end 0) (match-beginning 0)))
573 (tag (format "%5d" linenum
))
574 (empty (make-string (length tag
) ?\
))
577 ;; Number of lines of context to show for current match.
579 ;; Marker pointing to end of match in source buffer.
581 ;; Marker pointing to start of text for one
585 ;; Marker pointing to end of text for one match
590 (setq occur-marker
(make-marker))
591 (set-marker occur-marker
(point))
592 (set-buffer standard-output
)
593 (setq occur-num-matches
(1+ occur-num-matches
))
594 (or first
(zerop nlines
)
595 (insert "--------\n"))
598 ;; Insert matching text including context lines from
599 ;; source buffer into *Occur*
600 (set-marker text-beg
(point))
601 (setq insertion-start
(point))
602 (insert-buffer-substring buffer start end
)
603 (or (and (/= (+ start match-beg
) end
)
604 (with-current-buffer buffer
605 (eq (char-before end
) ?
\n)))
607 (set-marker final-context-start
608 (+ (- (point) (- end
(match-end 0)))
612 (goto-char (match-end 0))
616 (set-marker text-end
(point))
618 ;; Highlight text that was matched.
619 (if list-matching-lines-face
621 (+ (marker-position text-beg
) match-beg
)
622 (+ (marker-position text-beg
) match-beg match-len
)
623 'face list-matching-lines-face
))
625 ;; `occur-point' property is used by occur-next and
626 ;; occur-prev to move between matching lines.
628 (+ (marker-position text-beg
) match-beg match-len
)
629 (+ (marker-position text-beg
) match-beg match-len
1)
632 ;; Now go back to the start of the matching text
633 ;; adding the space and colon to the start of each line.
634 (goto-char insertion-start
)
635 ;; Insert space and colon for lines of context before match.
636 (setq tem
(if (< linenum nlines
)
644 ;; Insert line number and colon for the lines of
646 (let ((this-linenum linenum
))
647 (while (< (point) final-context-start
)
649 (setq tag
(format "%5d" this-linenum
)))
653 (setq this-linenum
(1+ this-linenum
)))
654 (while (and (not (eobp)) (<= (point) final-context-start
))
657 (setq this-linenum
(1+ this-linenum
))))
659 ;; Insert space and colon for lines of context after match.
660 (while (and (< (point) (point-max)) (< tem nlines
))
665 ;; Add text properties. The `occur' prop is used to
666 ;; store the marker of the matching text in the
668 (put-text-property (marker-position text-beg
)
669 (- (marker-position text-end
) 1)
670 'mouse-face
'highlight
)
671 (put-text-property (marker-position text-beg
)
672 (marker-position text-end
)
674 (goto-char (point-max)))
676 (set-buffer standard-output
)
677 ;; Go back to top of *Occur* and finish off by printing the
678 ;; number of matching lines.
679 (goto-char (point-min))
680 (let ((message-string
681 (if (= occur-num-matches
1)
683 (format "%d lines" occur-num-matches
))))
684 (insert message-string
)
686 (message "%s matched" message-string
)))
687 (setq buffer-read-only t
)))))))
689 ;; It would be nice to use \\[...], but there is no reasonable way
690 ;; to make that display both SPC and Y.
691 (defconst query-replace-help
692 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
693 RET or `q' to exit, Period to replace one match and exit,
694 Comma to replace but not move point immediately,
695 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
696 C-w to delete match and recursive edit,
697 C-l to clear the screen, redisplay, and offer same replacement again,
698 ! to replace all remaining matches with no more questions,
699 ^ to move point back to previous match."
700 "Help message while in query-replace")
702 (defvar query-replace-map
(make-sparse-keymap)
703 "Keymap that defines the responses to questions in `query-replace'.
704 The \"bindings\" in this map are not commands; they are answers.
705 The valid answers include `act', `skip', `act-and-show',
706 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
707 `automatic', `backup', `exit-prefix', and `help'.")
709 (define-key query-replace-map
" " 'act
)
710 (define-key query-replace-map
"\d" 'skip
)
711 (define-key query-replace-map
[delete] 'skip)
712 (define-key query-replace-map [backspace] 'skip)
713 (define-key query-replace-map "y" 'act)
714 (define-key query-replace-map "n" 'skip)
715 (define-key query-replace-map "Y" 'act)
716 (define-key query-replace-map "N" 'skip)
717 (define-key query-replace-map "," 'act-and-show)
718 (define-key query-replace-map "q" 'exit)
719 (define-key query-replace-map "\r" 'exit)
720 (define-key query-replace-map [return] 'exit)
721 (define-key query-replace-map "." 'act-and-exit)
722 (define-key query-replace-map "\C-r" 'edit)
723 (define-key query-replace-map "\C-w" 'delete-and-edit)
724 (define-key query-replace-map "\C-l" 'recenter)
725 (define-key query-replace-map "!" 'automatic)
726 (define-key query-replace-map "^" 'backup)
727 (define-key query-replace-map "\C-h" 'help)
728 (define-key query-replace-map [f1] 'help)
729 (define-key query-replace-map [help] 'help)
730 (define-key query-replace-map "?" 'help)
731 (define-key query-replace-map "\C-g" 'quit)
732 (define-key query-replace-map "\C-]" 'quit)
733 (define-key query-replace-map "\e" 'exit-prefix)
734 (define-key query-replace-map [escape] 'exit-prefix)
736 (defun replace-match-string-symbols (n)
737 ;; Process a list (and any sub-lists), expanding certain symbols:
739 ;; N (match-string N) (where N is a string of digits)
740 ;; #N (string-to-number (match-string N))
741 ;; & (match-string 0)
742 ;; #& (string-to-number (match-string 0))
744 ;; Note that these symbols must be preceeded by a backslash in order to
749 (replace-match-string-symbols (car n))) ;Process sub-list
751 (let ((name (symbol-name (car n))))
753 ((string-match "^[0-9]+$" name)
754 (setcar n (list 'match-string (string-to-number name))))
755 ((string-match "^#[0-9]+$" name)
756 (setcar n (list 'string-to-number
758 (string-to-number (substring name 1))))))
760 (setcar n '(match-string 0)))
762 (setcar n '(string-to-number (match-string 0))))))))
765 (defun replace-eval-replacement (expression replace-count)
766 (let ((replacement (eval expression)))
767 (if (stringp replacement)
769 (prin1-to-string replacement t))))
771 (defun replace-loop-through-replacements (data replace-count)
772 ;; DATA is a vector contaning the following values:
773 ;; 0 next-rotate-count
775 ;; 2 next-replacement
777 (if (= (aref data 0) replace-count)
779 (aset data 0 (+ replace-count (aref data 1)))
780 (let ((next (cdr (aref data 2))))
781 (aset data 2 (if (consp next) next (aref data 3))))))
784 (defun perform-replace (from-string replacements
785 query-flag regexp-flag delimited-flag
786 &optional repeat-count map)
787 "Subroutine of `query-replace'. Its complexity handles interactive queries.
788 Don't use this in your own program unless you want to query and set the mark
789 just as `query-replace' does. Instead, write a simple loop like this:
790 (while (re-search-forward \"foo[ \t]+bar\" nil t)
791 (replace-match \"foobar\" nil nil))
792 which will run faster and probably do exactly what you want."
793 (or map (setq map query-replace-map))
794 (and query-flag minibuffer-auto-raise
795 (raise-frame (window-frame (minibuffer-window))))
796 (let ((nocasify (not (and case-fold-search case-replace
797 (string-equal from-string
798 (downcase from-string)))))
799 (case-fold-search (and case-fold-search
800 (string-equal from-string
801 (downcase from-string))))
802 (literal (not regexp-flag))
803 (search-function (if regexp-flag 're-search-forward 'search-forward))
804 (search-string from-string)
805 (real-match-data nil) ; the match data for the current match
806 (next-replacement nil)
812 ;; If non-nil, it is marker saying where in the buffer to stop.
815 ;; Data for the next match. If a cons, it has the same format as
816 ;; (match-data); otherwise it is t if a match is possible at point.
821 (substitute-command-keys
822 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
824 ;; If region is active, in Transient Mark mode, operate on region.
825 (if (and transient-mark-mode mark-active)
827 (setq limit (copy-marker (region-end)))
828 (goto-char (region-beginning))
831 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
832 ;; containing a function and its first argument. The function is
833 ;; called to generate each replacement like this:
834 ;; (funcall (car replacements) (cdr replacements) replace-count)
835 ;; It must return a string.
837 ((stringp replacements)
838 (setq next-replacement replacements
840 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
841 (or repeat-count (setq repeat-count 1))
842 (setq replacements (cons 'replace-loop-through-replacements
843 (vector repeat-count repeat-count
844 replacements replacements)))))
847 (setq search-function 're-search-forward
848 search-string (concat "\\b"
849 (if regexp-flag from-string
850 (regexp-quote from-string))
855 ;; Loop finding occurrences that perhaps should be replaced.
856 (while (and keep-going
858 ;; Use the next match if it is already known;
859 ;; otherwise, search for a match after moving forward
860 ;; one char if progress is required.
861 (setq real-match-data
862 (if (consp match-again)
863 (progn (goto-char (nth 1 match-again))
866 ;; MATCH-AGAIN nil means in the
867 ;; regexp case that there's no
868 ;; match adjacent to the last
869 ;; one. So, we could move
870 ;; forward, but we don't want to
871 ;; because that moves point 1
872 ;; position after the last
873 ;; replacement when everything
876 (progn (forward-char 1) (not (eobp))))
877 (funcall search-function search-string limit t)
878 ;; For speed, use only integers and
879 ;; reuse the list used last time.
880 (match-data t real-match-data)))))
882 ;; Record whether the match is nonempty, to avoid an infinite loop
883 ;; repeatedly matching the same empty string.
885 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
887 ;; If the match is empty, record that the next one can't be adjacent.
888 ;; Otherwise, if matching a regular expression, do the next
889 ;; match now, since the replacement for this match may
890 ;; affect whether the next match is adjacent to this one.
893 (or (not regexp-flag)
894 (and (looking-at search-string)
897 ;; Calculate the replacement string, if necessary.
899 (set-match-data real-match-data)
900 (setq next-replacement
901 (funcall (car replacements) (cdr replacements)
905 (set-match-data real-match-data)
906 (replace-match next-replacement nocasify literal)
907 (setq replace-count (1+ replace-count)))
909 (let (done replaced key def)
910 ;; Loop reading commands until one of them sets done,
911 ;; which means it has finished handling this occurrence.
913 (set-match-data real-match-data)
914 (replace-highlight (match-beginning 0) (match-end 0))
915 ;; Bind message-log-max so we don't fill up the message log
916 ;; with a bunch of identical messages.
917 (let ((message-log-max nil))
918 (message message from-string next-replacement))
919 (setq key (read-event))
920 ;; Necessary in case something happens during read-event
921 ;; that clobbers the match data.
922 (set-match-data real-match-data)
923 (setq key (vector key))
924 (setq def (lookup-key map key))
925 ;; Restore the match data while we process the command.
926 (cond ((eq def 'help)
927 (with-output-to-temp-buffer "*Help*"
929 (concat "Query replacing "
930 (if regexp-flag "regexp " "")
932 next-replacement ".\n\n"
933 (substitute-command-keys
934 query-replace-help)))
936 (set-buffer standard-output)
939 (setq keep-going nil)
943 (let ((elt (car stack)))
944 (goto-char (car elt))
945 (setq replaced (eq t (cdr elt)))
947 (set-match-data (cdr elt)))
948 (setq stack (cdr stack)))
949 (message "No previous match")
955 (replace-match next-replacement nocasify literal)
956 (setq replace-count (1+ replace-count))))
957 (setq done t replaced t))
958 ((eq def 'act-and-exit)
961 (replace-match next-replacement nocasify literal)
962 (setq replace-count (1+ replace-count))))
963 (setq keep-going nil)
964 (setq done t replaced t))
965 ((eq def 'act-and-show)
968 (replace-match next-replacement nocasify literal)
969 (setq replace-count (1+ replace-count))
974 (replace-match next-replacement nocasify literal)
975 (setq replace-count (1+ replace-count))))
976 (setq done t query-flag nil replaced t))
982 (let ((opos (point-marker)))
983 (goto-char (match-beginning 0))
985 (funcall search-function search-string limit t)
986 (setq real-match-data (match-data)))
987 (save-excursion (recursive-edit))
989 (set-match-data real-match-data)
990 ;; Before we make the replacement,
991 ;; decide whether the search string
992 ;; can match again just after this match.
993 (if (and regexp-flag nonempty-match)
994 (setq match-again (and (looking-at search-string)
996 ((eq def 'delete-and-edit)
997 (delete-region (match-beginning 0) (match-end 0))
1000 (save-excursion (recursive-edit))))
1002 ;; Note: we do not need to treat `exit-prefix'
1003 ;; specially here, since we reread
1004 ;; any unrecognized character.
1006 (setq this-command 'mode-exited)
1007 (setq keep-going nil)
1008 (setq unread-command-events
1009 (append (listify-key-sequence key)
1010 unread-command-events))
1012 ;; Record previous position for ^ when we move on.
1013 ;; Change markers to numbers in the match data
1014 ;; since lots of markers slow down editing.
1017 (or replaced (match-data t)))
1019 (replace-dehighlight))
1020 (or unread-command-events
1021 (message "Replaced %d occurrence%s"
1023 (if (= replace-count 1) "" "s")))
1024 (and keep-going stack)))
1026 (defcustom query-replace-highlight t
1027 "*Non-nil means to highlight words during query replacement."
1031 (defvar replace-overlay nil)
1033 (defun replace-dehighlight ()
1034 (and replace-overlay
1036 (delete-overlay replace-overlay)
1037 (setq replace-overlay nil))))
1039 (defun replace-highlight (start end)
1040 (and query-replace-highlight
1044 (setq replace-overlay (make-overlay start end))
1045 (overlay-put replace-overlay 'face
1046 (if (internal-find-face 'query-replace)
1047 'query-replace 'region))))
1048 (move-overlay replace-overlay start end (current-buffer)))))
1050 ;;; replace.el ends here