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