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