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