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