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