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