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