*** empty log message ***
[bpt/emacs.git] / lisp / replace.el
1 ;;; replace.el --- replace commands for Emacs.
2
3 ;; Copyright (C) 1985, 86, 87, 92, 94, 96, 1997 Free Software Foundation, Inc.
4
5 ;; This file is part of GNU Emacs.
6
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)
10 ;; any later version.
11
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.
16
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.
21
22 ;;; Commentary:
23
24 ;; This package supplies the string and regular-expression replace functions
25 ;; documented in the Emacs user's manual.
26
27 ;;; Code:
28
29 (defcustom case-replace t
30 "*Non-nil means query-replace should preserve case in replacements."
31 :type 'boolean
32 :group 'matching)
33
34 (defvar query-replace-history nil)
35
36 (defvar query-replace-interactive nil
37 "Non-nil means `query-replace' uses the last search string.
38 That becomes the \"string to replace\".")
39
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."
45 :group 'matching
46 :type 'symbol
47 :version "20.3")
48
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
53 strings or patterns."
54 :group 'matching
55 :type 'symbol
56 :version "20.3")
57
58 (defun query-replace-read-args (string regexp-flag)
59 (let (from to)
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)
63 nil nil nil
64 query-replace-from-history-variable
65 nil t)))
66 (setq to (read-from-minibuffer (format "%s %s with: " string from)
67 nil nil nil
68 query-replace-to-history-variable from t))
69 (list from to current-prefix-arg)))
70
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.
75
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.
78
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
81 minibuffer.
82
83 Preserves case in each replacement if `case-replace' and `case-fold-search'
84 are non-nil and FROM-STRING has no uppercase letters.
85 \(Preserving case means that if the string matched is all caps, or capitalized,
86 then its replacement is upcased or capitalized.)
87
88 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
89 only matches surrounded by word boundaries.
90
91 To customize possible responses, change the \"bindings\" in `query-replace-map'."
92 (interactive (query-replace-read-args "Query replace" nil))
93 (perform-replace from-string to-string t nil arg))
94
95 (define-key esc-map "%" 'query-replace)
96
97 (defun query-replace-regexp (regexp to-string &optional arg)
98 "Replace some things after point matching REGEXP with TO-STRING.
99 As each match is found, the user must type a character saying
100 what to do with it. For directions, type \\[help-command] at that time.
101
102 In Transient Mark mode, if the mark is active, operate on the contents
103 of the region. Otherwise, operate from point to the end of the buffer.
104
105 If `query-replace-interactive' is non-nil, the last incremental search
106 regexp is used as REGEXP--you don't have to specify it with the
107 minibuffer.
108
109 Preserves case in each replacement if `case-replace' and `case-fold-search'
110 are non-nil and REGEXP has no uppercase letters.
111 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
112 only matches surrounded by word boundaries.
113 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
114 and `\\=\\N' (where N is a digit) stands for
115 whatever what matched the Nth `\\(...\\)' in REGEXP."
116 (interactive (query-replace-read-args "Query replace regexp" t))
117 (perform-replace regexp to-string t t arg))
118
119 (defun map-query-replace-regexp (regexp to-strings &optional arg)
120 "Replace some matches for REGEXP with various strings, in rotation.
121 The second argument TO-STRINGS contains the replacement strings, separated
122 by spaces. This command works like `query-replace-regexp' except
123 that each successive replacement uses the next successive replacement string,
124 wrapping around from the last such string to the first.
125
126 In Transient Mark mode, if the mark is active, operate on the contents
127 of the region. Otherwise, operate from point to the end of the buffer.
128
129 Non-interactively, TO-STRINGS may be a list of replacement strings.
130
131 If `query-replace-interactive' is non-nil, the last incremental search
132 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
133
134 A prefix argument N says to use each replacement string N times
135 before rotating to the next."
136 (interactive
137 (let (from to)
138 (setq from (if query-replace-interactive
139 (car regexp-search-ring)
140 (read-from-minibuffer "Map query replace (regexp): "
141 nil nil nil
142 'query-replace-history nil t)))
143 (setq to (read-from-minibuffer
144 (format "Query replace %s with (space-separated strings): "
145 from)
146 nil nil nil
147 'query-replace-history from t))
148 (list from to current-prefix-arg)))
149 (let (replacements)
150 (if (listp to-strings)
151 (setq replacements to-strings)
152 (while (/= (length to-strings) 0)
153 (if (string-match " " to-strings)
154 (setq replacements
155 (append replacements
156 (list (substring to-strings 0
157 (string-match " " to-strings))))
158 to-strings (substring to-strings
159 (1+ (string-match " " to-strings))))
160 (setq replacements (append replacements (list to-strings))
161 to-strings ""))))
162 (perform-replace regexp replacements t t nil arg)))
163
164 (defun replace-string (from-string to-string &optional delimited)
165 "Replace occurrences of FROM-STRING with TO-STRING.
166 Preserve case in each match if `case-replace' and `case-fold-search'
167 are non-nil and FROM-STRING has no uppercase letters.
168 \(Preserving case means that if the string matched is all caps, or capitalized,
169 then its replacement is upcased or capitalized.)
170
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.
173
174 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
175 only matches surrounded by word boundaries.
176
177 If `query-replace-interactive' is non-nil, the last incremental search
178 string is used as FROM-STRING--you don't have to specify it with the
179 minibuffer.
180
181 This function is usually the wrong thing to use in a Lisp program.
182 What you probably want is a loop like this:
183 (while (search-forward FROM-STRING nil t)
184 (replace-match TO-STRING nil t))
185 which will run faster and will not set the mark or print anything.
186 \(You may need a more complex loop if FROM-STRING can match the null string
187 and TO-STRING is also null.)"
188 (interactive (query-replace-read-args "Replace string" nil))
189 (perform-replace from-string to-string nil nil delimited))
190
191 (defun replace-regexp (regexp to-string &optional delimited)
192 "Replace things after point matching REGEXP with TO-STRING.
193 Preserve case in each match if `case-replace' and `case-fold-search'
194 are non-nil and REGEXP has no uppercase letters.
195 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
196 only matches surrounded by word boundaries.
197 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
198 and `\\=\\N' (where N is a digit) stands for
199 whatever what matched the Nth `\\(...\\)' in REGEXP.
200
201 In Transient Mark mode, if the mark is active, operate on the contents
202 of the region. Otherwise, operate from point to the end of the buffer.
203
204 If `query-replace-interactive' is non-nil, the last incremental search
205 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
206
207 This function is usually the wrong thing to use in a Lisp program.
208 What you probably want is a loop like this:
209 (while (re-search-forward REGEXP nil t)
210 (replace-match TO-STRING nil nil))
211 which will run faster and will not set the mark or print anything."
212 (interactive (query-replace-read-args "Replace regexp" t))
213 (perform-replace regexp to-string nil t delimited))
214 \f
215 (defvar regexp-history nil
216 "History list for some commands that read regular expressions.")
217
218 (defalias 'delete-non-matching-lines 'keep-lines)
219 (defun keep-lines (regexp)
220 "Delete all lines except those containing matches for REGEXP.
221 A match split across lines preserves all the lines it lies in.
222 Applies to all lines after point."
223 (interactive (list (read-from-minibuffer
224 "Keep lines (containing match for regexp): "
225 nil nil nil 'regexp-history nil t)))
226 (save-excursion
227 (or (bolp) (forward-line 1))
228 (let ((start (point)))
229 (while (not (eobp))
230 ;; Start is first char not preserved by previous match.
231 (if (not (re-search-forward regexp nil 'move))
232 (delete-region start (point-max))
233 (let ((end (save-excursion (goto-char (match-beginning 0))
234 (beginning-of-line)
235 (point))))
236 ;; Now end is first char preserved by the new match.
237 (if (< start end)
238 (delete-region start end))))
239 (setq start (save-excursion (forward-line 1)
240 (point)))
241 ;; If the match was empty, avoid matching again at same place.
242 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
243 (forward-char 1))))))
244
245 (defalias 'delete-matching-lines 'flush-lines)
246 (defun flush-lines (regexp)
247 "Delete lines containing matches for REGEXP.
248 If a match is split across lines, all the lines it lies in are deleted.
249 Applies to lines after point."
250 (interactive (list (read-from-minibuffer
251 "Flush lines (containing match for regexp): "
252 nil nil nil 'regexp-history nil t)))
253 (save-excursion
254 (while (and (not (eobp))
255 (re-search-forward regexp nil t))
256 (delete-region (save-excursion (goto-char (match-beginning 0))
257 (beginning-of-line)
258 (point))
259 (progn (forward-line 1) (point))))))
260
261 (defalias 'count-matches 'how-many)
262 (defun how-many (regexp)
263 "Print number of matches for REGEXP following point."
264 (interactive (list(read-from-minibuffer
265 "How many matches for (regexp): "
266 nil nil nil 'regexp-history nil t)))
267 (let ((count 0) opoint)
268 (save-excursion
269 (while (and (not (eobp))
270 (progn (setq opoint (point))
271 (re-search-forward regexp nil t)))
272 (if (= opoint (point))
273 (forward-char 1)
274 (setq count (1+ count))))
275 (message "%d occurrences" count))))
276 \f
277 (defvar occur-mode-map ())
278 (if occur-mode-map
279 ()
280 (setq occur-mode-map (make-sparse-keymap))
281 (define-key occur-mode-map [mouse-2] 'occur-mode-mouse-goto)
282 (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence)
283 (define-key occur-mode-map "\C-m" 'occur-mode-goto-occurrence)
284 (define-key occur-mode-map "\M-n" 'occur-next)
285 (define-key occur-mode-map "\M-p" 'occur-prev)
286 (define-key occur-mode-map "g" 'revert-buffer))
287
288
289 (defvar occur-buffer nil
290 "Name of buffer for last occur.")
291
292
293 (defvar occur-nlines nil
294 "Number of lines of context to show around matching line.")
295
296 (defvar occur-command-arguments nil
297 "Arguments that were given to `occur' when it made this buffer.")
298
299 (put 'occur-mode 'mode-class 'special)
300
301 (defun occur-mode ()
302 "Major mode for output from \\[occur].
303 \\<occur-mode-map>Move point to one of the items in this buffer, then use
304 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
305 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
306
307 \\{occur-mode-map}"
308 (kill-all-local-variables)
309 (use-local-map occur-mode-map)
310 (setq major-mode 'occur-mode)
311 (setq mode-name "Occur")
312 (make-local-variable 'revert-buffer-function)
313 (setq revert-buffer-function 'occur-revert-function)
314 (make-local-variable 'occur-buffer)
315 (make-local-variable 'occur-nlines)
316 (make-local-variable 'occur-command-arguments)
317 (run-hooks 'occur-mode-hook))
318
319 ;; Handle revert-buffer for *Occur* buffers.
320 (defun occur-revert-function (ignore1 ignore2)
321 (let ((args occur-command-arguments ))
322 (save-excursion
323 (set-buffer occur-buffer)
324 (apply 'occur args))))
325
326 (defun occur-mode-mouse-goto (event)
327 "In Occur mode, go to the occurrence whose line you click on."
328 (interactive "e")
329 (let (buffer pos)
330 (save-excursion
331 (set-buffer (window-buffer (posn-window (event-end event))))
332 (save-excursion
333 (goto-char (posn-point (event-end event)))
334 (setq pos (occur-mode-find-occurrence))
335 (setq buffer occur-buffer)))
336 (pop-to-buffer buffer)
337 (goto-char (marker-position pos))))
338
339 (defun occur-mode-find-occurrence ()
340 (if (or (null occur-buffer)
341 (null (buffer-name occur-buffer)))
342 (progn
343 (setq occur-buffer nil)
344 (error "Buffer in which occurrences were found is deleted")))
345 (let ((pos (get-text-property (point) 'occur)))
346 (if (null pos)
347 (error "No occurrence on this line")
348 pos)))
349
350 (defun occur-mode-goto-occurrence ()
351 "Go to the occurrence the current line describes."
352 (interactive)
353 (let ((pos (occur-mode-find-occurrence)))
354 (pop-to-buffer occur-buffer)
355 (goto-char (marker-position pos))))
356
357 (defun occur-next (&optional n)
358 "Move to the Nth (default 1) next match in the *Occur* buffer."
359 (interactive "p")
360 (if (not n) (setq n 1))
361 (let ((r))
362 (while (> n 0)
363 (if (get-text-property (point) 'occur-point)
364 (forward-char 1))
365 (setq r (next-single-property-change (point) 'occur-point))
366 (if r
367 (goto-char r)
368 (error "no more matches"))
369 (setq n (1- n)))))
370
371
372
373 (defun occur-prev (&optional n)
374 "Move to the Nth (default 1) previous match in the *Occur* buffer."
375 (interactive "p")
376 (if (not n) (setq n 1))
377 (let ((r))
378 (while (> n 0)
379
380 (setq r (get-text-property (point) 'occur-point))
381 (if r (forward-char -1))
382
383 (setq r (previous-single-property-change (point) 'occur-point))
384 (if r
385 (goto-char (- r 1))
386 (error "no earlier matches"))
387
388 (setq n (1- n)))))
389 \f
390 (defcustom list-matching-lines-default-context-lines 0
391 "*Default number of context lines to include around a `list-matching-lines'
392 match. A negative number means to include that many lines before the match.
393 A positive number means to include that many lines both before and after."
394 :type 'integer
395 :group 'matching)
396
397 (defalias 'list-matching-lines 'occur)
398
399 (defvar list-matching-lines-face 'bold
400 "*Face used by M-x list-matching-lines to show the text that matches.
401 If the value is nil, don't highlight the matching portions specially.")
402
403 (defun occur (regexp &optional nlines)
404 "Show all lines in the current buffer containing a match for REGEXP.
405
406 If a match spreads across multiple lines, all those lines are shown.
407
408 Each line is displayed with NLINES lines before and after, or -NLINES
409 before if NLINES is negative.
410 NLINES defaults to `list-matching-lines-default-context-lines'.
411 Interactively it is the prefix arg.
412
413 The lines are shown in a buffer named `*Occur*'.
414 It serves as a menu to find any of the occurrences in this buffer.
415 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
416
417 If REGEXP contains upper case characters (excluding those preceded by `\\'),
418 the matching is case-sensitive."
419 (interactive
420 (list (let* ((default (car regexp-history))
421 (input
422 (read-from-minibuffer
423 (if default
424 (format "List lines matching regexp (default `%s'): "
425 default)
426 "List lines matching regexp: ")
427 nil nil nil 'regexp-history default t)))
428 (and (equal input "") default
429 (setq input default))
430 input)
431 current-prefix-arg))
432 (let ((nlines (if nlines
433 (prefix-numeric-value nlines)
434 list-matching-lines-default-context-lines))
435 (first t)
436 ;;flag to prevent printing separator for first match
437 (occur-num-matches 0)
438 (buffer (current-buffer))
439 (dir default-directory)
440 (linenum 1)
441 (prevpos
442 ;;position of most recent match
443 (point-min))
444 (case-fold-search (and case-fold-search
445 (isearch-no-upper-case-p regexp t)))
446 (final-context-start
447 ;; Marker to the start of context immediately following
448 ;; the matched text in *Occur*.
449 (make-marker)))
450 ;;; (save-excursion
451 ;;; (beginning-of-line)
452 ;;; (setq linenum (1+ (count-lines (point-min) (point))))
453 ;;; (setq prevpos (point)))
454 (save-excursion
455 (goto-char (point-min))
456 ;; Check first whether there are any matches at all.
457 (if (not (re-search-forward regexp nil t))
458 (message "No matches for `%s'" regexp)
459 ;; Back up, so the search loop below will find the first match.
460 (goto-char (match-beginning 0))
461 (with-output-to-temp-buffer "*Occur*"
462 (save-excursion
463 (set-buffer standard-output)
464 (setq default-directory dir)
465 ;; We will insert the number of lines, and "lines", later.
466 (insert " matching ")
467 (let ((print-escape-newlines t))
468 (prin1 regexp))
469 (insert " in buffer " (buffer-name buffer) ?. ?\n)
470 (occur-mode)
471 (setq occur-buffer buffer)
472 (setq occur-nlines nlines)
473 (setq occur-command-arguments
474 (list regexp nlines)))
475 (if (eq buffer standard-output)
476 (goto-char (point-max)))
477 (save-excursion
478 ;; Find next match, but give up if prev match was at end of buffer.
479 (while (and (not (= prevpos (point-max)))
480 (re-search-forward regexp nil t))
481 (goto-char (match-beginning 0))
482 (beginning-of-line)
483 (save-match-data
484 (setq linenum (+ linenum (count-lines prevpos (point)))))
485 (setq prevpos (point))
486 (goto-char (match-end 0))
487 (let* ((start
488 ;;start point of text in source buffer to be put
489 ;;into *Occur*
490 (save-excursion
491 (goto-char (match-beginning 0))
492 (forward-line (if (< nlines 0)
493 nlines
494 (- nlines)))
495 (point)))
496 (end
497 ;; end point of text in source buffer to be put
498 ;; into *Occur*
499 (save-excursion
500 (goto-char (match-end 0))
501 (if (> nlines 0)
502 (forward-line (1+ nlines))
503 (forward-line 1))
504 (point)))
505 (match-beg
506 ;; Amount of context before matching text
507 (- (match-beginning 0) start))
508 (match-len
509 ;; Length of matching text
510 (- (match-end 0) (match-beginning 0)))
511 (tag (format "%5d" linenum))
512 (empty (make-string (length tag) ?\ ))
513 tem
514 insertion-start
515 ;; Number of lines of context to show for current match.
516 occur-marker
517 ;; Marker pointing to end of match in source buffer.
518 (text-beg
519 ;; Marker pointing to start of text for one
520 ;; match in *Occur*.
521 (make-marker))
522 (text-end
523 ;; Marker pointing to end of text for one match
524 ;; in *Occur*.
525 (make-marker))
526 )
527 (save-excursion
528 (setq occur-marker (make-marker))
529 (set-marker occur-marker (point))
530 (set-buffer standard-output)
531 (setq occur-num-matches (1+ occur-num-matches))
532 (or first (zerop nlines)
533 (insert "--------\n"))
534 (setq first nil)
535
536 ;; Insert matching text including context lines from
537 ;; source buffer into *Occur*
538 (set-marker text-beg (point))
539 (setq insertion-start (point))
540 (insert-buffer-substring buffer start end)
541 (or (and (/= (+ start match-beg) end)
542 (with-current-buffer buffer
543 (eq (char-before end) ?\n)))
544 (insert "\n"))
545 (set-marker final-context-start
546 (+ (- (point) (- end (match-end 0)))
547 (if (save-excursion
548 (set-buffer buffer)
549 (save-excursion
550 (goto-char (match-end 0))
551 (end-of-line)
552 (bolp)))
553 1 0)))
554 (set-marker text-end (point))
555
556 ;; Highlight text that was matched.
557 (if list-matching-lines-face
558 (put-text-property
559 (+ (marker-position text-beg) match-beg)
560 (+ (marker-position text-beg) match-beg match-len)
561 'face list-matching-lines-face))
562
563 ;; `occur-point' property is used by occur-next and
564 ;; occur-prev to move between matching lines.
565 (put-text-property
566 (+ (marker-position text-beg) match-beg match-len)
567 (+ (marker-position text-beg) match-beg match-len 1)
568 'occur-point t)
569
570 ;; Now go back to the start of the matching text
571 ;; adding the space and colon to the start of each line.
572 (goto-char insertion-start)
573 ;; Insert space and colon for lines of context before match.
574 (setq tem (if (< linenum nlines)
575 (- nlines linenum)
576 nlines))
577 (while (> tem 0)
578 (insert empty ?:)
579 (forward-line 1)
580 (setq tem (1- tem)))
581
582 ;; Insert line number and colon for the lines of
583 ;; matching text.
584 (let ((this-linenum linenum))
585 (while (< (point) final-context-start)
586 (if (null tag)
587 (setq tag (format "%5d" this-linenum)))
588 (insert tag ?:)
589 (forward-line 1)
590 (setq tag nil)
591 (setq this-linenum (1+ this-linenum)))
592 (while (and (not (eobp)) (<= (point) final-context-start))
593 (insert empty ?:)
594 (forward-line 1)
595 (setq this-linenum (1+ this-linenum))))
596
597 ;; Insert space and colon for lines of context after match.
598 (while (and (< (point) (point-max)) (< tem nlines))
599 (insert empty ?:)
600 (forward-line 1)
601 (setq tem (1+ tem)))
602
603 ;; Add text properties. The `occur' prop is used to
604 ;; store the marker of the matching text in the
605 ;; source buffer.
606 (put-text-property (marker-position text-beg)
607 (- (marker-position text-end) 1)
608 'mouse-face 'highlight)
609 (put-text-property (marker-position text-beg)
610 (marker-position text-end)
611 'occur occur-marker)
612 (goto-char (point-max)))
613 (forward-line 1)))
614 (set-buffer standard-output)
615 ;; Go back to top of *Occur* and finish off by printing the
616 ;; number of matching lines.
617 (goto-char (point-min))
618 (let ((message-string
619 (if (= occur-num-matches 1)
620 "1 line"
621 (format "%d lines" occur-num-matches))))
622 (insert message-string)
623 (if (interactive-p)
624 (message "%s matched" message-string)))))))))
625 \f
626 ;; It would be nice to use \\[...], but there is no reasonable way
627 ;; to make that display both SPC and Y.
628 (defconst query-replace-help
629 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
630 RET or `q' to exit, Period to replace one match and exit,
631 Comma to replace but not move point immediately,
632 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
633 C-w to delete match and recursive edit,
634 C-l to clear the screen, redisplay, and offer same replacement again,
635 ! to replace all remaining matches with no more questions,
636 ^ to move point back to previous match."
637 "Help message while in query-replace")
638
639 (defvar query-replace-map (make-sparse-keymap)
640 "Keymap that defines the responses to questions in `query-replace'.
641 The \"bindings\" in this map are not commands; they are answers.
642 The valid answers include `act', `skip', `act-and-show',
643 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
644 `automatic', `backup', `exit-prefix', and `help'.")
645
646 (define-key query-replace-map " " 'act)
647 (define-key query-replace-map "\d" 'skip)
648 (define-key query-replace-map [delete] 'skip)
649 (define-key query-replace-map [backspace] 'skip)
650 (define-key query-replace-map "y" 'act)
651 (define-key query-replace-map "n" 'skip)
652 (define-key query-replace-map "Y" 'act)
653 (define-key query-replace-map "N" 'skip)
654 (define-key query-replace-map "," 'act-and-show)
655 (define-key query-replace-map "q" 'exit)
656 (define-key query-replace-map "\r" 'exit)
657 (define-key query-replace-map [return] 'exit)
658 (define-key query-replace-map "." 'act-and-exit)
659 (define-key query-replace-map "\C-r" 'edit)
660 (define-key query-replace-map "\C-w" 'delete-and-edit)
661 (define-key query-replace-map "\C-l" 'recenter)
662 (define-key query-replace-map "!" 'automatic)
663 (define-key query-replace-map "^" 'backup)
664 (define-key query-replace-map "\C-h" 'help)
665 (define-key query-replace-map [f1] 'help)
666 (define-key query-replace-map [help] 'help)
667 (define-key query-replace-map "?" 'help)
668 (define-key query-replace-map "\C-g" 'quit)
669 (define-key query-replace-map "\C-]" 'quit)
670 (define-key query-replace-map "\e" 'exit-prefix)
671 (define-key query-replace-map [escape] 'exit-prefix)
672
673 (defun perform-replace (from-string replacements
674 query-flag regexp-flag delimited-flag
675 &optional repeat-count map)
676 "Subroutine of `query-replace'. Its complexity handles interactive queries.
677 Don't use this in your own program unless you want to query and set the mark
678 just as `query-replace' does. Instead, write a simple loop like this:
679 (while (re-search-forward \"foo[ \t]+bar\" nil t)
680 (replace-match \"foobar\" nil nil))
681 which will run faster and probably do exactly what you want."
682 (or map (setq map query-replace-map))
683 (and query-flag minibuffer-auto-raise
684 (raise-frame (window-frame (minibuffer-window))))
685 (let ((nocasify (not (and case-fold-search case-replace
686 (string-equal from-string
687 (downcase from-string)))))
688 (literal (not regexp-flag))
689 (search-function (if regexp-flag 're-search-forward 'search-forward))
690 (search-string from-string)
691 (real-match-data nil) ; the match data for the current match
692 (next-replacement nil)
693 (replacement-index 0)
694 (keep-going t)
695 (stack nil)
696 (next-rotate-count 0)
697 (replace-count 0)
698 (nonempty-match nil)
699
700 ;; If non-nil, it is marker saying where in the buffer to stop.
701 (limit nil)
702
703 ;; Data for the next match. If a cons, it has the same format as
704 ;; (match-data); otherwise it is t if a match is possible at point.
705 (match-again t)
706
707 (message
708 (if query-flag
709 (substitute-command-keys
710 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
711
712 ;; If region is active, in Transient Mark mode, operate on region.
713 (if (and transient-mark-mode mark-active)
714 (progn
715 (setq limit (copy-marker (region-end)))
716 (goto-char (region-beginning))
717 (deactivate-mark)))
718 (if (stringp replacements)
719 (setq next-replacement replacements)
720 (or repeat-count (setq repeat-count 1)))
721 (if delimited-flag
722 (setq search-function 're-search-forward
723 search-string (concat "\\b"
724 (if regexp-flag from-string
725 (regexp-quote from-string))
726 "\\b")))
727 (push-mark)
728 (undo-boundary)
729 (unwind-protect
730 ;; Loop finding occurrences that perhaps should be replaced.
731 (while (and keep-going
732 (not (eobp))
733 ;; Use the next match if it is already known;
734 ;; otherwise, search for a match after moving forward
735 ;; one char if progress is required.
736 (setq real-match-data
737 (if (consp match-again)
738 (progn (goto-char (nth 1 match-again))
739 match-again)
740 (and (or match-again
741 (progn
742 (forward-char 1)
743 (not (eobp))))
744 (funcall search-function search-string limit t)
745 ;; For speed, use only integers and
746 ;; reuse the list used last time.
747 (match-data t real-match-data)))))
748
749 ;; Record whether the match is nonempty, to avoid an infinite loop
750 ;; repeatedly matching the same empty string.
751 (setq nonempty-match
752 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
753
754 ;; If the match is empty, record that the next one can't be adjacent.
755 ;; Otherwise, if matching a regular expression, do the next
756 ;; match now, since the replacement for this match may
757 ;; affect whether the next match is adjacent to this one.
758 (setq match-again
759 (and nonempty-match
760 (or (not regexp-flag)
761 (and (looking-at search-string)
762 (match-data)))))
763
764 ;; If time for a change, advance to next replacement string.
765 (if (and (listp replacements)
766 (= next-rotate-count replace-count))
767 (progn
768 (setq next-rotate-count
769 (+ next-rotate-count repeat-count))
770 (setq next-replacement (nth replacement-index replacements))
771 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
772 (if (not query-flag)
773 (progn
774 (set-match-data real-match-data)
775 (replace-match next-replacement nocasify literal)
776 (setq replace-count (1+ replace-count)))
777 (undo-boundary)
778 (let (done replaced key def)
779 ;; Loop reading commands until one of them sets done,
780 ;; which means it has finished handling this occurrence.
781 (while (not done)
782 (set-match-data real-match-data)
783 (replace-highlight (match-beginning 0) (match-end 0))
784 ;; Bind message-log-max so we don't fill up the message log
785 ;; with a bunch of identical messages.
786 (let ((message-log-max nil))
787 (message message from-string next-replacement))
788 (setq key (read-event))
789 ;; Necessary in case something happens during read-event
790 ;; that clobbers the match data.
791 (set-match-data real-match-data)
792 (setq key (vector key))
793 (setq def (lookup-key map key))
794 ;; Restore the match data while we process the command.
795 (cond ((eq def 'help)
796 (with-output-to-temp-buffer "*Help*"
797 (princ
798 (concat "Query replacing "
799 (if regexp-flag "regexp " "")
800 from-string " with "
801 next-replacement ".\n\n"
802 (substitute-command-keys
803 query-replace-help)))
804 (save-excursion
805 (set-buffer standard-output)
806 (help-mode))))
807 ((eq def 'exit)
808 (setq keep-going nil)
809 (setq done t))
810 ((eq def 'backup)
811 (if stack
812 (let ((elt (car stack)))
813 (goto-char (car elt))
814 (setq replaced (eq t (cdr elt)))
815 (or replaced
816 (set-match-data (cdr elt)))
817 (setq stack (cdr stack)))
818 (message "No previous match")
819 (ding 'no-terminate)
820 (sit-for 1)))
821 ((eq def 'act)
822 (or replaced
823 (progn
824 (replace-match next-replacement nocasify literal)
825 (setq replace-count (1+ replace-count))))
826 (setq done t replaced t))
827 ((eq def 'act-and-exit)
828 (or replaced
829 (progn
830 (replace-match next-replacement nocasify literal)
831 (setq replace-count (1+ replace-count))))
832 (setq keep-going nil)
833 (setq done t replaced t))
834 ((eq def 'act-and-show)
835 (if (not replaced)
836 (progn
837 (replace-match next-replacement nocasify literal)
838 (setq replace-count (1+ replace-count))
839 (setq replaced t))))
840 ((eq def 'automatic)
841 (or replaced
842 (progn
843 (replace-match next-replacement nocasify literal)
844 (setq replace-count (1+ replace-count))))
845 (setq done t query-flag nil replaced t))
846 ((eq def 'skip)
847 (setq done t))
848 ((eq def 'recenter)
849 (recenter nil))
850 ((eq def 'edit)
851 (goto-char (match-beginning 0))
852 (funcall search-function search-string limit t)
853 (setq real-match-data (match-data))
854 (save-excursion (recursive-edit))
855 (set-match-data real-match-data)
856 ;; Before we make the replacement,
857 ;; decide whether the search string
858 ;; can match again just after this match.
859 (if (and regexp-flag nonempty-match)
860 (setq match-again (and (looking-at search-string)
861 (match-data)))))
862 ((eq def 'delete-and-edit)
863 (delete-region (match-beginning 0) (match-end 0))
864 (set-match-data
865 (prog1 (match-data)
866 (save-excursion (recursive-edit))))
867 (setq replaced t))
868 ;; Note: we do not need to treat `exit-prefix'
869 ;; specially here, since we reread
870 ;; any unrecognized character.
871 (t
872 (setq this-command 'mode-exited)
873 (setq keep-going nil)
874 (setq unread-command-events
875 (append (listify-key-sequence key)
876 unread-command-events))
877 (setq done t))))
878 ;; Record previous position for ^ when we move on.
879 ;; Change markers to numbers in the match data
880 ;; since lots of markers slow down editing.
881 (setq stack
882 (cons (cons (point)
883 (or replaced (match-data t)))
884 stack)))))
885 (replace-dehighlight))
886 (or unread-command-events
887 (message "Replaced %d occurrence%s"
888 replace-count
889 (if (= replace-count 1) "" "s")))
890 (and keep-going stack)))
891
892 (defcustom query-replace-highlight t
893 "*Non-nil means to highlight words during query replacement."
894 :type 'boolean
895 :group 'matching)
896
897 (defvar replace-overlay nil)
898
899 (defun replace-dehighlight ()
900 (and replace-overlay
901 (progn
902 (delete-overlay replace-overlay)
903 (setq replace-overlay nil))))
904
905 (defun replace-highlight (start end)
906 (and query-replace-highlight
907 (progn
908 (or replace-overlay
909 (progn
910 (setq replace-overlay (make-overlay start end))
911 (overlay-put replace-overlay 'face
912 (if (internal-find-face 'query-replace)
913 'query-replace 'region))))
914 (move-overlay replace-overlay start end (current-buffer)))))
915
916 ;;; replace.el ends here