Remove CVS merge cookie left in.
[emacs.git] / lisp / replace.el
blob8645e81420b19a414953d31243daeb23a1f94aa0
1 ;;; replace.el --- replace commands for Emacs.
3 ;; Copyright (C) 1985, 86, 87, 92, 94, 96, 1997, 2000
4 ;; Free Software Foundation, Inc.
6 ;; This file is part of GNU Emacs.
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.
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.
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.
23 ;;; Commentary:
25 ;; This package supplies the string and regular-expression replace functions
26 ;; documented in the Emacs user's manual.
28 ;;; Code:
30 (defcustom case-replace t
31 "*Non-nil means query-replace should preserve case in replacements."
32 :type 'boolean
33 :group 'matching)
35 (defvar query-replace-history nil)
37 (defvar query-replace-interactive nil
38 "Non-nil means `query-replace' uses the last search string.
39 That becomes the \"string to replace\".")
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")
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")
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))))
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.
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.
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.
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.)
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.
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))
100 (define-key esc-map "%" 'query-replace)
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.
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.
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.
114 Preserves case in each replacement if `case-replace' and `case-fold-search'
115 are non-nil and REGEXP has no uppercase letters.
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.
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)
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.
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).
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.
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.
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.
150 Preserves case in each replacement if `case-replace' and `case-fold-search'
151 are non-nil and REGEXP has no uppercase letters.
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))
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.
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.
189 Non-interactively, TO-STRINGS may be a list of replacement strings.
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.
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)))
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.)
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.
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.
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.
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))
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.
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.
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.
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.
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.
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))
284 (defvar regexp-history nil
285 "History list for some commands that read regular expressions.")
288 (defalias 'delete-non-matching-lines 'keep-lines)
289 (defalias 'delete-matching-lines 'flush-lines)
290 (defalias 'count-matches 'how-many)
293 (defun keep-lines-read-args (prompt)
294 "Read arguments for `keep-lines' and friends.
295 Prompt for a regexp with PROMPT.
297 Value is a list (REGEXP START END).
299 If in Transient Mark node, and the mark is active, START is the
300 start of the region, and end is a marker for the end of the region.
301 Otherwise, START is the current point, and END is `point-max-marker'."
302 (let ((regexp (read-from-minibuffer prompt nil nil nil
303 'regexp-history nil t))
304 start end)
305 (if (and transient-mark-mode mark-active)
306 (setq start (region-beginning)
307 end (save-excursion (goto-char (region-end)) (point-marker)))
308 (setq start (point)
309 end (point-max-marker)))
310 (list regexp start end)))
313 (defun keep-lines (regexp &optional rstart rend)
314 "Delete all lines except those containing matches for REGEXP.
315 A match split across lines preserves all the lines it lies in.
316 Applies to all lines after point.
318 If REGEXP contains upper case characters (excluding those preceded by `\\'),
319 the matching is case-sensitive.
321 Second and third arg RSTART and REND specify the region to operate on.
323 In Transient Mark mode, if the mark is active, operate on the contents
324 of the region. Otherwise, operate from point to the end of the buffer."
325 (interactive
326 (keep-lines-read-args "Keep lines (containing match for regexp): "))
327 (if rstart
328 (goto-char (min rstart rend))
329 (setq rstart (point) rend (point-max-marker)))
330 (save-excursion
331 (or (bolp) (forward-line 1))
332 (let ((start (point))
333 (case-fold-search (and case-fold-search
334 (isearch-no-upper-case-p regexp t))))
335 (while (< (point) rend)
336 ;; Start is first char not preserved by previous match.
337 (if (not (re-search-forward regexp rend 'move))
338 (delete-region start rend)
339 (let ((end (save-excursion (goto-char (match-beginning 0))
340 (beginning-of-line)
341 (point))))
342 ;; Now end is first char preserved by the new match.
343 (if (< start end)
344 (delete-region start end))))
346 (setq start (save-excursion (forward-line 1) (point)))
347 ;; If the match was empty, avoid matching again at same place.
348 (and (< (point) rend)
349 (= (match-beginning 0) (match-end 0))
350 (forward-char 1))))))
353 (defun flush-lines (regexp &optional rstart rend)
354 "Delete lines containing matches for REGEXP.
355 If a match is split across lines, all the lines it lies in are deleted.
356 Applies to lines after point.
358 If REGEXP contains upper case characters (excluding those preceded by `\\'),
359 the matching is case-sensitive.
361 Second and third arg RSTART and REND specify the region to operate on.
363 In Transient Mark mode, if the mark is active, operate on the contents
364 of the region. Otherwise, operate from point to the end of the buffer."
365 (interactive
366 (keep-lines-read-args "Flush lines (containing match for regexp): "))
367 (if rstart
368 (goto-char (min rstart rend))
369 (setq rstart (point) rend (point-max-marker)))
370 (let ((case-fold-search (and case-fold-search
371 (isearch-no-upper-case-p regexp t))))
372 (save-excursion
373 (while (and (< (point) rend)
374 (re-search-forward regexp rend t))
375 (delete-region (save-excursion (goto-char (match-beginning 0))
376 (beginning-of-line)
377 (point))
378 (progn (forward-line 1) (point)))))))
381 (defun how-many (regexp &optional rstart rend)
382 "Print number of matches for REGEXP following point.
384 If REGEXP contains upper case characters (excluding those preceded by `\\'),
385 the matching is case-sensitive.
387 Second and third arg RSTART and REND specify the region to operate on.
389 In Transient Mark mode, if the mark is active, operate on the contents
390 of the region. Otherwise, operate from point to the end of the buffer."
391 (interactive
392 (keep-lines-read-args "How many matches for (regexp): "))
393 (if rstart
394 (goto-char (min rstart rend))
395 (setq rstart (point) rend (point-max-marker)))
396 (let ((count 0)
397 opoint
398 (case-fold-search (and case-fold-search
399 (isearch-no-upper-case-p regexp t))))
400 (save-excursion
401 (while (and (< (point) rend)
402 (progn (setq opoint (point))
403 (re-search-forward regexp rend t)))
404 (if (= opoint (point))
405 (forward-char 1)
406 (setq count (1+ count))))
407 (message "%d occurrences" count))))
410 (defvar occur-mode-map ())
411 (if occur-mode-map
413 (setq occur-mode-map (make-sparse-keymap))
414 (define-key occur-mode-map [mouse-2] 'occur-mode-mouse-goto)
415 (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence)
416 (define-key occur-mode-map "\C-m" 'occur-mode-goto-occurrence)
417 (define-key occur-mode-map "\M-n" 'occur-next)
418 (define-key occur-mode-map "\M-p" 'occur-prev)
419 (define-key occur-mode-map "g" 'revert-buffer))
422 (defvar occur-buffer nil
423 "Name of buffer for last occur.")
426 (defvar occur-nlines nil
427 "Number of lines of context to show around matching line.")
429 (defvar occur-command-arguments nil
430 "Arguments that were given to `occur' when it made this buffer.")
432 (put 'occur-mode 'mode-class 'special)
434 (defun occur-mode ()
435 "Major mode for output from \\[occur].
436 \\<occur-mode-map>Move point to one of the items in this buffer, then use
437 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
438 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
440 \\{occur-mode-map}"
441 (kill-all-local-variables)
442 (use-local-map occur-mode-map)
443 (setq major-mode 'occur-mode)
444 (setq mode-name "Occur")
445 (make-local-variable 'revert-buffer-function)
446 (setq revert-buffer-function 'occur-revert-function)
447 (make-local-variable 'occur-buffer)
448 (make-local-variable 'occur-nlines)
449 (make-local-variable 'occur-command-arguments)
450 (run-hooks 'occur-mode-hook))
452 (defun occur-revert-function (ignore1 ignore2)
453 "Handle revert-buffer for *Occur* buffers."
454 (let ((args occur-command-arguments ))
455 (save-excursion
456 (set-buffer occur-buffer)
457 (apply 'occur args))))
459 (defun occur-mode-mouse-goto (event)
460 "In Occur mode, go to the occurrence whose line you click on."
461 (interactive "e")
462 (let (buffer pos)
463 (save-excursion
464 (set-buffer (window-buffer (posn-window (event-end event))))
465 (save-excursion
466 (goto-char (posn-point (event-end event)))
467 (setq pos (occur-mode-find-occurrence))
468 (setq buffer occur-buffer)))
469 (pop-to-buffer buffer)
470 (goto-char (marker-position pos))))
472 (defun occur-mode-find-occurrence ()
473 (if (or (null occur-buffer)
474 (null (buffer-name occur-buffer)))
475 (progn
476 (setq occur-buffer nil)
477 (error "Buffer in which occurrences were found is deleted")))
478 (let ((pos (get-text-property (point) 'occur)))
479 (if (null pos)
480 (error "No occurrence on this line")
481 pos)))
483 (defun occur-mode-goto-occurrence ()
484 "Go to the occurrence the current line describes."
485 (interactive)
486 (let ((pos (occur-mode-find-occurrence)))
487 (pop-to-buffer occur-buffer)
488 (goto-char (marker-position pos))))
490 (defun occur-next (&optional n)
491 "Move to the Nth (default 1) next match in the *Occur* buffer."
492 (interactive "p")
493 (if (not n) (setq n 1))
494 (let ((r))
495 (while (> n 0)
496 (if (get-text-property (point) 'occur-point)
497 (forward-char 1))
498 (setq r (next-single-property-change (point) 'occur-point))
499 (if r
500 (goto-char r)
501 (error "No more matches"))
502 (setq n (1- n)))))
506 (defun occur-prev (&optional n)
507 "Move to the Nth (default 1) previous match in the *Occur* buffer."
508 (interactive "p")
509 (if (not n) (setq n 1))
510 (let ((r))
511 (while (> n 0)
513 (setq r (get-text-property (point) 'occur-point))
514 (if r (forward-char -1))
516 (setq r (previous-single-property-change (point) 'occur-point))
517 (if r
518 (goto-char (- r 1))
519 (error "No earlier matches"))
521 (setq n (1- n)))))
523 (defcustom list-matching-lines-default-context-lines 0
524 "*Default number of context lines included around `list-matching-lines' matches.
525 A negative number means to include that many lines before the match.
526 A positive number means to include that many lines both before and after."
527 :type 'integer
528 :group 'matching)
530 (defalias 'list-matching-lines 'occur)
532 (defvar list-matching-lines-face 'bold
533 "*Face used by \\[list-matching-lines] to show the text that matches.
534 If the value is nil, don't highlight the matching portions specially.")
536 (defun occur (regexp &optional nlines)
537 "Show all lines in the current buffer containing a match for REGEXP.
539 If a match spreads across multiple lines, all those lines are shown.
541 Each line is displayed with NLINES lines before and after, or -NLINES
542 before if NLINES is negative.
543 NLINES defaults to `list-matching-lines-default-context-lines'.
544 Interactively it is the prefix arg.
546 The lines are shown in a buffer named `*Occur*'.
547 It serves as a menu to find any of the occurrences in this buffer.
548 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
550 If REGEXP contains upper case characters (excluding those preceded by `\\'),
551 the matching is case-sensitive."
552 (interactive
553 (list (let* ((default (car regexp-history))
554 (input
555 (read-from-minibuffer
556 (if default
557 (format "List lines matching regexp (default `%s'): "
558 default)
559 "List lines matching regexp: ")
560 nil nil nil 'regexp-history default t)))
561 (and (equal input "") default
562 (setq input default))
563 input)
564 current-prefix-arg))
565 (let* ((nlines (if nlines
566 (prefix-numeric-value nlines)
567 list-matching-lines-default-context-lines))
568 (current-tab-width tab-width)
569 ;; Minimum width of line number plus trailing colon.
570 (min-line-number-width 6)
571 ;; Actual width of line number prefix. Choose a width that's
572 ;; a multiple of `tab-width' in the original buffer so that
573 ;; lines in *Occur* appear right.
574 (line-number-width (* (/ (- (+ min-line-number-width
575 tab-width)
577 tab-width)
578 tab-width))
579 ;; Format string for line numbers.
580 (line-number-format (format "%%%dd" line-number-width))
581 (empty (make-string line-number-width ?\ ))
582 (first t)
583 ;;flag to prevent printing separator for first match
584 (occur-num-matches 0)
585 (buffer (current-buffer))
586 (dir default-directory)
587 (linenum 1)
588 (prevpos
589 ;;position of most recent match
590 (point-min))
591 (case-fold-search (and case-fold-search
592 (isearch-no-upper-case-p regexp t)))
593 (final-context-start
594 ;; Marker to the start of context immediately following
595 ;; the matched text in *Occur*.
596 (make-marker)))
597 ;;; (save-excursion
598 ;;; (beginning-of-line)
599 ;;; (setq linenum (1+ (count-lines (point-min) (point))))
600 ;;; (setq prevpos (point)))
601 (save-excursion
602 (goto-char (point-min))
603 ;; Check first whether there are any matches at all.
604 (if (not (re-search-forward regexp nil t))
605 (message "No matches for `%s'" regexp)
606 ;; Back up, so the search loop below will find the first match.
607 (goto-char (match-beginning 0))
608 (with-output-to-temp-buffer "*Occur*"
609 (save-excursion
610 (set-buffer standard-output)
611 (setq default-directory dir)
612 ;; We will insert the number of lines, and "lines", later.
613 (insert " matching ")
614 (let ((print-escape-newlines t))
615 (prin1 regexp))
616 (insert " in buffer " (buffer-name buffer) ?. ?\n)
617 (occur-mode)
618 (setq occur-buffer buffer)
619 (setq occur-nlines nlines)
620 (setq occur-command-arguments
621 (list regexp nlines)))
622 (if (eq buffer standard-output)
623 (goto-char (point-max)))
624 (save-excursion
625 ;; Find next match, but give up if prev match was at end of buffer.
626 (while (and (not (= prevpos (point-max)))
627 (re-search-forward regexp nil t))
628 (goto-char (match-beginning 0))
629 (beginning-of-line)
630 (save-match-data
631 (setq linenum (+ linenum (count-lines prevpos (point)))))
632 (setq prevpos (point))
633 (goto-char (match-end 0))
634 (let* (;;start point of text in source buffer to be put
635 ;;into *Occur*
636 (start (save-excursion
637 (goto-char (match-beginning 0))
638 (forward-line (if (< nlines 0)
639 nlines
640 (- nlines)))
641 (point)))
642 ;; end point of text in source buffer to be put
643 ;; into *Occur*
644 (end (save-excursion
645 (goto-char (match-end 0))
646 (if (> nlines 0)
647 (forward-line (1+ nlines))
648 (forward-line 1))
649 (point)))
650 ;; Amount of context before matching text
651 (match-beg (- (match-beginning 0) start))
652 ;; Length of matching text
653 (match-len (- (match-end 0) (match-beginning 0)))
654 (tag (format line-number-format linenum))
656 insertion-start
657 ;; Number of lines of context to show for current match.
658 occur-marker
659 ;; Marker pointing to end of match in source buffer.
660 (text-beg
661 ;; Marker pointing to start of text for one
662 ;; match in *Occur*.
663 (make-marker))
664 (text-end
665 ;; Marker pointing to end of text for one match
666 ;; in *Occur*.
667 (make-marker)))
668 (save-excursion
669 (setq occur-marker (make-marker))
670 (set-marker occur-marker (point))
671 (set-buffer standard-output)
672 (setq occur-num-matches (1+ occur-num-matches))
673 (or first (zerop nlines)
674 (insert "--------\n"))
675 (setq first nil)
676 (save-excursion
677 (set-buffer "*Occur*")
678 (setq tab-width current-tab-width))
680 ;; Insert matching text including context lines from
681 ;; source buffer into *Occur*
682 (set-marker text-beg (point))
683 (setq insertion-start (point))
684 (insert-buffer-substring buffer start end)
685 (or (and (/= (+ start match-beg) end)
686 (with-current-buffer buffer
687 (eq (char-before end) ?\n)))
688 (insert "\n"))
689 (set-marker final-context-start
690 (+ (- (point) (- end (match-end 0)))
691 (if (save-excursion
692 (set-buffer buffer)
693 (save-excursion
694 (goto-char (match-end 0))
695 (end-of-line)
696 (bolp)))
697 1 0)))
698 (set-marker text-end (point))
700 ;; Highlight text that was matched.
701 (if list-matching-lines-face
702 (put-text-property
703 (+ (marker-position text-beg) match-beg)
704 (+ (marker-position text-beg) match-beg match-len)
705 'face list-matching-lines-face))
707 ;; `occur-point' property is used by occur-next and
708 ;; occur-prev to move between matching lines.
709 (put-text-property
710 (+ (marker-position text-beg) match-beg match-len)
711 (+ (marker-position text-beg) match-beg match-len 1)
712 'occur-point t)
714 ;; Now go back to the start of the matching text
715 ;; adding the space and colon to the start of each line.
716 (goto-char insertion-start)
717 ;; Insert space and colon for lines of context before match.
718 (setq tem (if (< linenum nlines)
719 (- nlines linenum)
720 nlines))
721 (while (> tem 0)
722 (insert empty ?:)
723 (forward-line 1)
724 (setq tem (1- tem)))
726 ;; Insert line number and colon for the lines of
727 ;; matching text.
728 (let ((this-linenum linenum))
729 (while (< (point) final-context-start)
730 (if (null tag)
731 (setq tag (format line-number-format this-linenum)))
732 (insert tag ?:)
733 (forward-line 1)
734 (setq tag nil)
735 (setq this-linenum (1+ this-linenum)))
736 (while (and (not (eobp)) (<= (point) final-context-start))
737 (insert empty ?:)
738 (forward-line 1)
739 (setq this-linenum (1+ this-linenum))))
741 ;; Insert space and colon for lines of context after match.
742 (while (and (< (point) (point-max)) (< tem nlines))
743 (insert empty ?:)
744 (forward-line 1)
745 (setq tem (1+ tem)))
747 ;; Add text properties. The `occur' prop is used to
748 ;; store the marker of the matching text in the
749 ;; source buffer.
750 (put-text-property (marker-position text-beg)
751 (- (marker-position text-end) 1)
752 'mouse-face 'highlight)
753 (put-text-property (marker-position text-beg)
754 (marker-position text-end)
755 'occur occur-marker)
756 (goto-char (point-max)))
757 (forward-line 1)))
758 (set-buffer standard-output)
759 ;; Go back to top of *Occur* and finish off by printing the
760 ;; number of matching lines.
761 (goto-char (point-min))
762 (let ((message-string
763 (if (= occur-num-matches 1)
764 "1 line"
765 (format "%d lines" occur-num-matches))))
766 (insert message-string)
767 (if (interactive-p)
768 (message "%s matched" message-string)))
769 (setq buffer-read-only t)))))))
771 ;; It would be nice to use \\[...], but there is no reasonable way
772 ;; to make that display both SPC and Y.
773 (defconst query-replace-help
774 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
775 RET or `q' to exit, Period to replace one match and exit,
776 Comma to replace but not move point immediately,
777 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
778 C-w to delete match and recursive edit,
779 C-l to clear the screen, redisplay, and offer same replacement again,
780 ! to replace all remaining matches with no more questions,
781 ^ to move point back to previous match,
782 E to edit the replacement string"
783 "Help message while in query-replace")
785 (defvar query-replace-map (make-sparse-keymap)
786 "Keymap that defines the responses to questions in `query-replace'.
787 The \"bindings\" in this map are not commands; they are answers.
788 The valid answers include `act', `skip', `act-and-show',
789 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
790 `automatic', `backup', `exit-prefix', and `help'.")
792 (define-key query-replace-map " " 'act)
793 (define-key query-replace-map "\d" 'skip)
794 (define-key query-replace-map [delete] 'skip)
795 (define-key query-replace-map [backspace] 'skip)
796 (define-key query-replace-map "y" 'act)
797 (define-key query-replace-map "n" 'skip)
798 (define-key query-replace-map "Y" 'act)
799 (define-key query-replace-map "N" 'skip)
800 (define-key query-replace-map "e" 'edit-replacement)
801 (define-key query-replace-map "E" 'edit-replacement)
802 (define-key query-replace-map "," 'act-and-show)
803 (define-key query-replace-map "q" 'exit)
804 (define-key query-replace-map "\r" 'exit)
805 (define-key query-replace-map [return] 'exit)
806 (define-key query-replace-map "." 'act-and-exit)
807 (define-key query-replace-map "\C-r" 'edit)
808 (define-key query-replace-map "\C-w" 'delete-and-edit)
809 (define-key query-replace-map "\C-l" 'recenter)
810 (define-key query-replace-map "!" 'automatic)
811 (define-key query-replace-map "^" 'backup)
812 (define-key query-replace-map "\C-h" 'help)
813 (define-key query-replace-map [f1] 'help)
814 (define-key query-replace-map [help] 'help)
815 (define-key query-replace-map "?" 'help)
816 (define-key query-replace-map "\C-g" 'quit)
817 (define-key query-replace-map "\C-]" 'quit)
818 (define-key query-replace-map "\e" 'exit-prefix)
819 (define-key query-replace-map [escape] 'exit-prefix)
821 (defun replace-match-string-symbols (n)
822 "Process a list (and any sub-lists), expanding certain symbols.
823 Symbol Expands To
824 N (match-string N) (where N is a string of digits)
825 #N (string-to-number (match-string N))
826 & (match-string 0)
827 #& (string-to-number (match-string 0))
829 Note that these symbols must be preceeded by a backslash in order to
830 type them."
831 (while n
832 (cond
833 ((consp (car n))
834 (replace-match-string-symbols (car n))) ;Process sub-list
835 ((symbolp (car n))
836 (let ((name (symbol-name (car n))))
837 (cond
838 ((string-match "^[0-9]+$" name)
839 (setcar n (list 'match-string (string-to-number name))))
840 ((string-match "^#[0-9]+$" name)
841 (setcar n (list 'string-to-number
842 (list 'match-string
843 (string-to-number (substring name 1))))))
844 ((string= "&" name)
845 (setcar n '(match-string 0)))
846 ((string= "#&" name)
847 (setcar n '(string-to-number (match-string 0))))))))
848 (setq n (cdr n))))
850 (defun replace-eval-replacement (expression replace-count)
851 (let ((replacement (eval expression)))
852 (if (stringp replacement)
853 replacement
854 (prin1-to-string replacement t))))
856 (defun replace-loop-through-replacements (data replace-count)
857 ;; DATA is a vector contaning the following values:
858 ;; 0 next-rotate-count
859 ;; 1 repeat-count
860 ;; 2 next-replacement
861 ;; 3 replacements
862 (if (= (aref data 0) replace-count)
863 (progn
864 (aset data 0 (+ replace-count (aref data 1)))
865 (let ((next (cdr (aref data 2))))
866 (aset data 2 (if (consp next) next (aref data 3))))))
867 (car (aref data 2)))
869 (defun perform-replace (from-string replacements start end
870 query-flag regexp-flag delimited-flag
871 &optional repeat-count map)
872 "Subroutine of `query-replace'. Its complexity handles interactive queries.
873 Don't use this in your own program unless you want to query and set the mark
874 just as `query-replace' does. Instead, write a simple loop like this:
875 (while (re-search-forward \"foo[ \t]+bar\" nil t)
876 (replace-match \"foobar\" nil nil))
877 which will run faster and probably do exactly what you want."
878 (or map (setq map query-replace-map))
879 (and query-flag minibuffer-auto-raise
880 (raise-frame (window-frame (minibuffer-window))))
881 (let ((nocasify (not (and case-fold-search case-replace
882 (string-equal from-string
883 (downcase from-string)))))
884 (case-fold-search (and case-fold-search
885 (string-equal from-string
886 (downcase from-string))))
887 (literal (not regexp-flag))
888 (search-function (if regexp-flag 're-search-forward 'search-forward))
889 (search-string from-string)
890 (real-match-data nil) ; the match data for the current match
891 (next-replacement nil)
892 (keep-going t)
893 (stack nil)
894 (replace-count 0)
895 (nonempty-match nil)
897 ;; If non-nil, it is marker saying where in the buffer to stop.
898 (limit nil)
900 ;; Data for the next match. If a cons, it has the same format as
901 ;; (match-data); otherwise it is t if a match is possible at point.
902 (match-again t)
904 (message
905 (if query-flag
906 (substitute-command-keys
907 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
909 ;; If region is active, in Transient Mark mode, operate on region.
910 (when start
911 (setq limit (copy-marker (max start end)))
912 (goto-char (min start end))
913 (deactivate-mark))
915 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
916 ;; containing a function and its first argument. The function is
917 ;; called to generate each replacement like this:
918 ;; (funcall (car replacements) (cdr replacements) replace-count)
919 ;; It must return a string.
920 (cond
921 ((stringp replacements)
922 (setq next-replacement replacements
923 replacements nil))
924 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
925 (or repeat-count (setq repeat-count 1))
926 (setq replacements (cons 'replace-loop-through-replacements
927 (vector repeat-count repeat-count
928 replacements replacements)))))
930 (if delimited-flag
931 (setq search-function 're-search-forward
932 search-string (concat "\\b"
933 (if regexp-flag from-string
934 (regexp-quote from-string))
935 "\\b")))
936 (push-mark)
937 (undo-boundary)
938 (unwind-protect
939 ;; Loop finding occurrences that perhaps should be replaced.
940 (while (and keep-going
941 (not (eobp))
942 ;; Use the next match if it is already known;
943 ;; otherwise, search for a match after moving forward
944 ;; one char if progress is required.
945 (setq real-match-data
946 (if (consp match-again)
947 (progn (goto-char (nth 1 match-again))
948 match-again)
949 (and (or match-again
950 ;; MATCH-AGAIN non-nil means we
951 ;; accept an adjacent match. If
952 ;; we don't, move one char to the
953 ;; right. This takes us a
954 ;; character too far at the end,
955 ;; but this is undone after the
956 ;; while-loop.
957 (progn (forward-char 1) (not (eobp))))
958 (funcall search-function search-string limit t)
959 ;; For speed, use only integers and
960 ;; reuse the list used last time.
961 (match-data t real-match-data)))))
963 ;; Record whether the match is nonempty, to avoid an infinite loop
964 ;; repeatedly matching the same empty string.
965 (setq nonempty-match
966 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
968 ;; If the match is empty, record that the next one can't be adjacent.
969 ;; Otherwise, if matching a regular expression, do the next
970 ;; match now, since the replacement for this match may
971 ;; affect whether the next match is adjacent to this one.
972 (setq match-again
973 (and nonempty-match
974 (or (not regexp-flag)
975 (and (looking-at search-string)
976 (match-data)))))
978 ;; Calculate the replacement string, if necessary.
979 (when replacements
980 (set-match-data real-match-data)
981 (setq next-replacement
982 (funcall (car replacements) (cdr replacements)
983 replace-count)))
984 (if (not query-flag)
985 (progn
986 (set-match-data real-match-data)
987 (replace-match next-replacement nocasify literal)
988 (setq replace-count (1+ replace-count)))
989 (undo-boundary)
990 (let (done replaced key def)
991 ;; Loop reading commands until one of them sets done,
992 ;; which means it has finished handling this occurrence.
993 (while (not done)
994 (set-match-data real-match-data)
995 (replace-highlight (match-beginning 0) (match-end 0))
996 ;; Bind message-log-max so we don't fill up the message log
997 ;; with a bunch of identical messages.
998 (let ((message-log-max nil))
999 (message message from-string next-replacement))
1000 (setq key (read-event))
1001 ;; Necessary in case something happens during read-event
1002 ;; that clobbers the match data.
1003 (set-match-data real-match-data)
1004 (setq key (vector key))
1005 (setq def (lookup-key map key))
1006 ;; Restore the match data while we process the command.
1007 (cond ((eq def 'help)
1008 (with-output-to-temp-buffer "*Help*"
1009 (princ
1010 (concat "Query replacing "
1011 (if regexp-flag "regexp " "")
1012 from-string " with "
1013 next-replacement ".\n\n"
1014 (substitute-command-keys
1015 query-replace-help)))
1016 (save-excursion
1017 (set-buffer standard-output)
1018 (help-mode))))
1019 ((eq def 'exit)
1020 (setq keep-going nil)
1021 (setq done t))
1022 ((eq def 'backup)
1023 (if stack
1024 (let ((elt (car stack)))
1025 (goto-char (car elt))
1026 (setq replaced (eq t (cdr elt)))
1027 (or replaced
1028 (set-match-data (cdr elt)))
1029 (setq stack (cdr stack)))
1030 (message "No previous match")
1031 (ding 'no-terminate)
1032 (sit-for 1)))
1033 ((eq def 'act)
1034 (or replaced
1035 (progn
1036 (replace-match next-replacement nocasify literal)
1037 (setq replace-count (1+ replace-count))))
1038 (setq done t replaced t))
1039 ((eq def 'act-and-exit)
1040 (or replaced
1041 (progn
1042 (replace-match next-replacement nocasify literal)
1043 (setq replace-count (1+ replace-count))))
1044 (setq keep-going nil)
1045 (setq done t replaced t))
1046 ((eq def 'act-and-show)
1047 (if (not replaced)
1048 (progn
1049 (replace-match next-replacement nocasify literal)
1050 (setq replace-count (1+ replace-count))
1051 (setq replaced t))))
1052 ((eq def 'automatic)
1053 (or replaced
1054 (progn
1055 (replace-match next-replacement nocasify literal)
1056 (setq replace-count (1+ replace-count))))
1057 (setq done t query-flag nil replaced t))
1058 ((eq def 'skip)
1059 (setq done t))
1060 ((eq def 'recenter)
1061 (recenter nil))
1062 ((eq def 'edit)
1063 (let ((opos (point-marker)))
1064 (goto-char (match-beginning 0))
1065 (save-excursion
1066 (funcall search-function search-string limit t)
1067 (setq real-match-data (match-data)))
1068 (save-excursion (recursive-edit))
1069 (goto-char opos))
1070 (set-match-data real-match-data)
1071 ;; Before we make the replacement,
1072 ;; decide whether the search string
1073 ;; can match again just after this match.
1074 (if (and regexp-flag nonempty-match)
1075 (setq match-again (and (looking-at search-string)
1076 (match-data)))))
1078 ;; Edit replacement.
1079 ((eq def 'edit-replacement)
1080 (setq next-replacement
1081 (read-input "Edit replacement string: "
1082 next-replacement))
1083 (or replaced
1084 (replace-match next-replacement nocasify literal))
1085 (setq done t))
1087 ((eq def 'delete-and-edit)
1088 (delete-region (match-beginning 0) (match-end 0))
1089 (set-match-data
1090 (prog1 (match-data)
1091 (save-excursion (recursive-edit))))
1092 (setq replaced t))
1093 ;; Note: we do not need to treat `exit-prefix'
1094 ;; specially here, since we reread
1095 ;; any unrecognized character.
1097 (setq this-command 'mode-exited)
1098 (setq keep-going nil)
1099 (setq unread-command-events
1100 (append (listify-key-sequence key)
1101 unread-command-events))
1102 (setq done t))))
1103 ;; Record previous position for ^ when we move on.
1104 ;; Change markers to numbers in the match data
1105 ;; since lots of markers slow down editing.
1106 (setq stack
1107 (cons (cons (point)
1108 (or replaced (match-data t)))
1109 stack)))))
1111 ;; The code preventing adjacent regexp matches in the condition
1112 ;; of the while-loop above will haven taken us one character
1113 ;; beyond the last replacement. Undo that.
1114 (when (and regexp-flag (not match-again) (> replace-count 0))
1115 (backward-char 1))
1117 (replace-dehighlight))
1118 (or unread-command-events
1119 (message "Replaced %d occurrence%s"
1120 replace-count
1121 (if (= replace-count 1) "" "s")))
1122 (and keep-going stack)))
1124 (defcustom query-replace-highlight t
1125 "*Non-nil means to highlight words during query replacement."
1126 :type 'boolean
1127 :group 'matching)
1129 (defvar replace-overlay nil)
1131 (defun replace-dehighlight ()
1132 (and replace-overlay
1133 (progn
1134 (delete-overlay replace-overlay)
1135 (setq replace-overlay nil))))
1137 (defun replace-highlight (start end)
1138 (and query-replace-highlight
1139 (progn
1140 (or replace-overlay
1141 (progn
1142 (setq replace-overlay (make-overlay start end))
1143 (overlay-put replace-overlay 'face
1144 (if (facep 'query-replace)
1145 'query-replace 'region))))
1146 (move-overlay replace-overlay start end (current-buffer)))))
1148 ;;; replace.el ends here