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.
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
27 ;; This package supplies the string and regular-expression replace functions
28 ;; documented in the Emacs user's manual.
32 (defcustom case-replace t
33 "*Non-nil means `query-replace' should preserve case in replacements."
37 (defvar query-replace-history nil
)
39 (defvar query-replace-interactive nil
40 "Non-nil means `query-replace' uses the last search string.
41 That becomes the \"string to replace\".")
43 (defcustom query-replace-from-history-variable
'query-replace-history
44 "History list to use for the FROM argument of `query-replace' commands.
45 The value of this variable should be a symbol; that symbol
46 is used as a variable to hold a history list for the strings
47 or patterns to be replaced."
52 (defcustom query-replace-to-history-variable
'query-replace-history
53 "History list to use for the TO argument of `query-replace' commands.
54 The value of this variable should be a symbol; that symbol
55 is used as a variable to hold a history list for replacement
61 (defcustom query-replace-skip-read-only nil
62 "*Non-nil means `query-replace' and friends ignore read-only matches."
67 (defun query-replace-read-args (string regexp-flag
&optional noerror
)
69 (barf-if-buffer-read-only))
71 (if query-replace-interactive
72 (setq from
(car (if regexp-flag regexp-search-ring search-ring
)))
73 ;; The save-excursion here is in case the user marks and copies
74 ;; a region in order to specify the minibuffer input.
75 ;; That should not clobber the region for the query-replace itself.
77 (setq from
(read-from-minibuffer (format "%s: " string
)
79 query-replace-from-history-variable
81 ;; Warn if user types \n or \t, but don't reject the input.
82 (if (string-match "\\\\[nt]" from
)
83 (let ((match (match-string 0 from
)))
85 ((string= match
"\\n")
86 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
87 ((string= match
"\\t")
88 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
92 (setq to
(read-from-minibuffer (format "%s %s with: " string from
)
94 query-replace-to-history-variable from t
)))
95 (list from to current-prefix-arg
)))
97 (defun query-replace (from-string to-string
&optional delimited start end
)
98 "Replace some occurrences of FROM-STRING with TO-STRING.
99 As each match is found, the user must type a character saying
100 what to do with it. For directions, type \\[help-command] at that time.
102 In Transient Mark mode, if the mark is active, operate on the contents
103 of the region. Otherwise, operate from point to the end of the buffer.
105 If `query-replace-interactive' is non-nil, the last incremental search
106 string is used as FROM-STRING--you don't have to specify it with the
109 Matching is independent of case if `case-fold-search' is non-nil and
110 FROM-STRING has no uppercase letters. Replacement transfers the case
111 pattern of the old text to the new text, if `case-replace' and
112 `case-fold-search' are non-nil and FROM-STRING has no uppercase
113 letters. \(Transferring the case pattern means that if the old text
114 matched is all caps, or capitalized, then its replacement is upcased
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 To customize possible responses, change the \"bindings\" in `query-replace-map'."
122 (interactive (let ((common
123 (query-replace-read-args "Query replace" nil
)))
124 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
125 ;; These are done separately here
126 ;; so that command-history will record these expressions
127 ;; rather than the values they had this time.
128 (if (and transient-mark-mode mark-active
)
130 (if (and transient-mark-mode mark-active
)
132 (perform-replace from-string to-string t nil delimited nil nil start end
))
134 (define-key esc-map
"%" 'query-replace
)
136 (defun query-replace-regexp (regexp to-string
&optional delimited start end
)
137 "Replace some things after point matching REGEXP with TO-STRING.
138 As each match is found, the user must type a character saying
139 what to do with it. For directions, type \\[help-command] at that time.
141 In Transient Mark mode, if the mark is active, operate on the contents
142 of the region. Otherwise, operate from point to the end of the buffer.
144 If `query-replace-interactive' is non-nil, the last incremental search
145 regexp is used as REGEXP--you don't have to specify it with the
148 Matching is independent of case if `case-fold-search' is non-nil and
149 REGEXP has no uppercase letters. Replacement transfers the case
150 pattern of the old text to the new text, if `case-replace' and
151 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
152 \(Transferring the case pattern means that if the old text matched is
153 all caps, or capitalized, then its replacement is upcased or
156 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
157 only matches surrounded by word boundaries.
158 Fourth and fifth arg START and END specify the region to operate on.
160 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
161 and `\\=\\N' (where N is a digit) stands for
162 whatever what matched the Nth `\\(...\\)' in REGEXP."
165 (query-replace-read-args "Query replace regexp" t
)))
166 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
167 ;; These are done separately here
168 ;; so that command-history will record these expressions
169 ;; rather than the values they had this time.
170 (if (and transient-mark-mode mark-active
)
172 (if (and transient-mark-mode mark-active
)
175 (perform-replace regexp to-string t t delimited nil nil start end
))
176 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
178 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
179 "Replace some things after point matching REGEXP with the result of TO-EXPR.
180 As each match is found, the user must type a character saying
181 what to do with it. For directions, type \\[help-command] at that time.
183 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
184 reference `replace-count' to get the number of replacements already made.
185 If the result of TO-EXPR is not a string, it is converted to one using
186 `prin1-to-string' with the NOESCAPE argument (which see).
188 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
189 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
190 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
191 Use `\\#&' or `\\#N' if you want a number instead of a string.
193 In Transient Mark mode, if the mark is active, operate on the contents
194 of the region. Otherwise, operate from point to the end of the buffer.
196 If `query-replace-interactive' is non-nil, the last incremental search
197 regexp is used as REGEXP--you don't have to specify it with the
200 Preserves case in each replacement if `case-replace' and `case-fold-search'
201 are non-nil and REGEXP has no uppercase letters.
203 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
204 only matches that are surrounded by word boundaries.
205 Fourth and fifth arg START and END specify the region to operate on."
208 (if query-replace-interactive
209 (setq from
(car regexp-search-ring
))
210 (setq from
(read-from-minibuffer "Query replace regexp: "
212 query-replace-from-history-variable
214 (setq to
(list (read-from-minibuffer
215 (format "Query replace regexp %s with eval: " from
)
216 nil nil t query-replace-to-history-variable from t
)))
217 ;; We make TO a list because replace-match-string-symbols requires one,
218 ;; and the user might enter a single token.
219 (replace-match-string-symbols to
)
220 (list from
(car to
) current-prefix-arg
221 (if (and transient-mark-mode mark-active
)
223 (if (and transient-mark-mode mark-active
)
225 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
226 t t delimited nil nil start end
))
228 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
229 "Replace some matches for REGEXP with various strings, in rotation.
230 The second argument TO-STRINGS contains the replacement strings,
231 separated by spaces. Third arg DELIMITED (prefix arg if interactive),
232 if non-nil, means replace only matches surrounded by word boundaries.
233 This command works like `query-replace-regexp' except that each
234 successive replacement uses the next successive replacement string,
235 wrapping around from the last such string to the first.
237 In Transient Mark mode, if the mark is active, operate on the contents
238 of the region. Otherwise, operate from point to the end of the buffer.
240 Non-interactively, TO-STRINGS may be a list of replacement strings.
242 If `query-replace-interactive' is non-nil, the last incremental search
243 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
245 A prefix argument N says to use each replacement string N times
246 before rotating to the next.
247 Fourth and fifth arg START and END specify the region to operate on."
250 (setq from
(if query-replace-interactive
251 (car regexp-search-ring
)
252 (read-from-minibuffer "Map query replace (regexp): "
254 'query-replace-history nil t
)))
255 (setq to
(read-from-minibuffer
256 (format "Query replace %s with (space-separated strings): "
259 'query-replace-history from t
))
261 (and current-prefix-arg
262 (prefix-numeric-value current-prefix-arg
))
263 (if (and transient-mark-mode mark-active
)
265 (if (and transient-mark-mode mark-active
)
268 (if (listp to-strings
)
269 (setq replacements to-strings
)
270 (while (/= (length to-strings
) 0)
271 (if (string-match " " to-strings
)
274 (list (substring to-strings
0
275 (string-match " " to-strings
))))
276 to-strings
(substring to-strings
277 (1+ (string-match " " to-strings
))))
278 (setq replacements
(append replacements
(list to-strings
))
280 (perform-replace regexp replacements t t nil n nil start end
)))
282 (defun replace-string (from-string to-string
&optional delimited start end
)
283 "Replace occurrences of FROM-STRING with TO-STRING.
284 Preserve case in each match if `case-replace' and `case-fold-search'
285 are non-nil and FROM-STRING has no uppercase letters.
286 \(Preserving case means that if the string matched is all caps, or capitalized,
287 then its replacement is upcased or capitalized.)
289 In Transient Mark mode, if the mark is active, operate on the contents
290 of the region. Otherwise, operate from point to the end of the buffer.
292 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
293 only matches surrounded by word boundaries.
294 Fourth and fifth arg START and END specify the region to operate on.
296 If `query-replace-interactive' is non-nil, the last incremental search
297 string is used as FROM-STRING--you don't have to specify it with the
300 This function is usually the wrong thing to use in a Lisp program.
301 What you probably want is a loop like this:
302 (while (search-forward FROM-STRING nil t)
303 (replace-match TO-STRING nil t))
304 which will run faster and will not set the mark or print anything.
305 \(You may need a more complex loop if FROM-STRING can match the null string
306 and TO-STRING is also null.)"
309 (query-replace-read-args "Replace string" nil
)))
310 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
311 (if (and transient-mark-mode mark-active
)
313 (if (and transient-mark-mode mark-active
)
315 (perform-replace from-string to-string nil nil delimited nil nil start end
))
317 (defun replace-regexp (regexp to-string
&optional delimited start end
)
318 "Replace things after point matching REGEXP with TO-STRING.
319 Preserve case in each match if `case-replace' and `case-fold-search'
320 are non-nil and REGEXP has no uppercase letters.
322 In Transient Mark mode, if the mark is active, operate on the contents
323 of the region. Otherwise, operate from point to the end of the buffer.
325 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
326 only matches surrounded by word boundaries.
327 Fourth and fifth arg START and END specify the region to operate on.
329 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
330 and `\\=\\N' (where N is a digit) stands for
331 whatever what matched the Nth `\\(...\\)' in REGEXP.
333 If `query-replace-interactive' is non-nil, the last incremental search
334 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
336 This function is usually the wrong thing to use in a Lisp program.
337 What you probably want is a loop like this:
338 (while (re-search-forward REGEXP nil t)
339 (replace-match TO-STRING nil nil))
340 which will run faster and will not set the mark or print anything."
343 (query-replace-read-args "Replace regexp" t
)))
344 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
345 (if (and transient-mark-mode mark-active
)
347 (if (and transient-mark-mode mark-active
)
349 (perform-replace regexp to-string nil t delimited nil nil start end
))
352 (defvar regexp-history nil
353 "History list for some commands that read regular expressions.")
356 (defalias 'delete-non-matching-lines
'keep-lines
)
357 (defalias 'delete-matching-lines
'flush-lines
)
358 (defalias 'count-matches
'how-many
)
361 (defun keep-lines-read-args (prompt)
362 "Read arguments for `keep-lines' and friends.
363 Prompt for a regexp with PROMPT.
364 Value is a list, (REGEXP)."
365 (list (read-from-minibuffer prompt nil nil nil
366 'regexp-history nil t
)))
368 (defun keep-lines (regexp &optional rstart rend
)
369 "Delete all lines except those containing matches for REGEXP.
370 A match split across lines preserves all the lines it lies in.
371 Applies to all lines after point.
373 If REGEXP contains upper case characters (excluding those preceded by `\\'),
374 the matching is case-sensitive.
376 Second and third arg RSTART and REND specify the region to operate on.
378 Interactively, in Transient Mark mode when the mark is active, operate
379 on the contents of the region. Otherwise, operate from point to the
384 (barf-if-buffer-read-only)
385 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
388 (goto-char (min rstart rend
))
389 (setq rend
(copy-marker (max rstart rend
))))
390 (if (and transient-mark-mode mark-active
)
391 (setq rstart
(region-beginning)
392 rend
(copy-marker (region-end)))
394 rend
(point-max-marker)))
397 (or (bolp) (forward-line 1))
398 (let ((start (point))
399 (case-fold-search (and case-fold-search
400 (isearch-no-upper-case-p regexp t
))))
401 (while (< (point) rend
)
402 ;; Start is first char not preserved by previous match.
403 (if (not (re-search-forward regexp rend
'move
))
404 (delete-region start rend
)
405 (let ((end (save-excursion (goto-char (match-beginning 0))
408 ;; Now end is first char preserved by the new match.
410 (delete-region start end
))))
412 (setq start
(save-excursion (forward-line 1) (point)))
413 ;; If the match was empty, avoid matching again at same place.
414 (and (< (point) rend
)
415 (= (match-beginning 0) (match-end 0))
416 (forward-char 1))))))
419 (defun flush-lines (regexp &optional rstart rend
)
420 "Delete lines containing matches for REGEXP.
421 If a match is split across lines, all the lines it lies in are deleted.
422 Applies to lines after point.
424 If REGEXP contains upper case characters (excluding those preceded by `\\'),
425 the matching is case-sensitive.
427 Second and third arg RSTART and REND specify the region to operate on.
429 Interactively, in Transient Mark mode when the mark is active, operate
430 on the contents of the region. Otherwise, operate from point to the
435 (barf-if-buffer-read-only)
436 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
439 (goto-char (min rstart rend
))
440 (setq rend
(copy-marker (max rstart rend
))))
441 (if (and transient-mark-mode mark-active
)
442 (setq rstart
(region-beginning)
443 rend
(copy-marker (region-end)))
445 rend
(point-max-marker)))
447 (let ((case-fold-search (and case-fold-search
448 (isearch-no-upper-case-p regexp t
))))
450 (while (and (< (point) rend
)
451 (re-search-forward regexp rend t
))
452 (delete-region (save-excursion (goto-char (match-beginning 0))
455 (progn (forward-line 1) (point)))))))
458 (defun how-many (regexp &optional rstart rend
)
459 "Print number of matches for REGEXP following point.
461 If REGEXP contains upper case characters (excluding those preceded by `\\'),
462 the matching is case-sensitive.
464 Second and third arg RSTART and REND specify the region to operate on.
466 Interactively, in Transient Mark mode when the mark is active, operate
467 on the contents of the region. Otherwise, operate from point to the
471 (keep-lines-read-args "How many matches for (regexp): "))
474 (goto-char (min rstart rend
))
475 (if (and transient-mark-mode mark-active
)
476 (setq rstart
(region-beginning)
477 rend
(copy-marker (region-end)))
479 rend
(point-max-marker)))
483 (case-fold-search (and case-fold-search
484 (isearch-no-upper-case-p regexp t
))))
485 (while (and (< (point) rend
)
486 (progn (setq opoint
(point))
487 (re-search-forward regexp rend t
)))
488 (if (= opoint
(point))
490 (setq count
(1+ count
))))
491 (message "%d occurrences" count
))))
494 (defvar occur-mode-map
495 (let ((map (make-sparse-keymap)))
496 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
497 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
498 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
499 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
500 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
501 (define-key map
"\M-n" 'occur-next
)
502 (define-key map
"\M-p" 'occur-prev
)
503 (define-key map
"r" 'occur-rename-buffer
)
504 (define-key map
"c" 'clone-buffer
)
505 (define-key map
"g" 'revert-buffer
)
506 (define-key map
"q" 'quit-window
)
507 (define-key map
"z" 'kill-this-buffer
)
509 "Keymap for `occur-mode'.")
511 (defvar occur-revert-arguments nil
512 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
513 See `occur-revert-function'.")
515 (defcustom occur-mode-hook
'(turn-on-font-lock)
516 "Hook run when entering Occur mode."
520 (defcustom occur-hook nil
521 "Hook run when `occur' is called."
525 (put 'occur-mode
'mode-class
'special
)
527 "Major mode for output from \\[occur].
528 \\<occur-mode-map>Move point to one of the items in this buffer, then use
529 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
530 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
534 (kill-all-local-variables)
535 (use-local-map occur-mode-map
)
536 (setq major-mode
'occur-mode
)
537 (setq mode-name
"Occur")
538 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
539 (make-local-variable 'occur-revert-arguments
)
540 (add-hook 'change-major-mode-hook
'font-lock-defontify nil t
)
541 (run-hooks 'occur-mode-hook
))
543 (defun occur-revert-function (ignore1 ignore2
)
544 "Handle `revert-buffer' for Occur mode buffers."
545 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
547 (defun occur-mode-mouse-goto (event)
548 "In Occur mode, go to the occurrence whose line you click on."
552 (set-buffer (window-buffer (posn-window (event-end event
))))
554 (goto-char (posn-point (event-end event
)))
555 (setq pos
(occur-mode-find-occurrence))))
556 (pop-to-buffer (marker-buffer pos
))
559 (defun occur-mode-find-occurrence ()
560 (let ((pos (get-text-property (point) 'occur-target
)))
562 (error "No occurrence on this line"))
563 (unless (buffer-live-p (marker-buffer pos
))
564 (error "Buffer for this occurrence was killed"))
567 (defun occur-mode-goto-occurrence ()
568 "Go to the occurrence the current line describes."
570 (let ((pos (occur-mode-find-occurrence)))
571 (pop-to-buffer (marker-buffer pos
))
574 (defun occur-mode-goto-occurrence-other-window ()
575 "Go to the occurrence the current line describes, in another window."
577 (let ((pos (occur-mode-find-occurrence)))
578 (switch-to-buffer-other-window (marker-buffer pos
))
581 (defun occur-mode-display-occurrence ()
582 "Display in another window the occurrence the current line describes."
584 (let ((pos (occur-mode-find-occurrence))
586 ;; Bind these to ensure `display-buffer' puts it in another window.
587 same-window-buffer-names
589 (setq window
(display-buffer (marker-buffer pos
)))
590 ;; This is the way to set point in the proper window.
591 (save-selected-window
592 (select-window window
)
595 (defun occur-find-match (n search message
)
596 (if (not n
) (setq n
1))
599 (setq r
(funcall search
(point) 'occur-match
))
601 (get-text-property r
'occur-match
)
602 (setq r
(funcall search r
'occur-match
)))
608 (defun occur-next (&optional n
)
609 "Move to the Nth (default 1) next match in an Occur mode buffer."
611 (occur-find-match n
#'next-single-property-change
"No more matches"))
613 (defun occur-prev (&optional n
)
614 "Move to the Nth (default 1) previous match in an Occur mode buffer."
616 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
618 (defcustom list-matching-lines-default-context-lines
0
619 "*Default number of context lines included around `list-matching-lines' matches.
620 A negative number means to include that many lines before the match.
621 A positive number means to include that many lines both before and after."
625 (defalias 'list-matching-lines
'occur
)
627 (defcustom list-matching-lines-face
'bold
628 "*Face used by \\[list-matching-lines] to show the text that matches.
629 If the value is nil, don't highlight the matching portions specially."
633 (defcustom list-matching-lines-buffer-name-face
'underline
634 "*Face used by \\[list-matching-lines] to show the names of buffers.
635 If the value is nil, don't highlight the buffer names specially."
639 (defun occur-accumulate-lines (count &optional no-props
)
641 (let ((forwardp (> count
0))
643 (while (not (or (zerop count
)
647 (setq count
(+ count
(if forwardp -
1 1)))
649 (funcall (if no-props
650 #'buffer-substring-no-properties
652 (line-beginning-position)
655 (forward-line (if forwardp
1 -
1)))
658 (defun occur-read-primary-args ()
659 (list (let* ((default (car regexp-history
))
661 (read-from-minibuffer
663 (format "List lines matching regexp (default `%s'): "
665 "List lines matching regexp: ")
673 (when current-prefix-arg
674 (prefix-numeric-value current-prefix-arg
))))
676 (defun occur-rename-buffer (&optional unique-p
)
677 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
678 Here `original-buffer-name' is the buffer name were occur was originally run.
679 When given the prefix argument, the renaming will not clobber the existing
680 buffer(s) of that name, but use `generate-new-buffer-name' instead.
681 You can add this to `occur-hook' if you always want a separate *Occur*
682 buffer for each buffer where you invoke `occur'."
685 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
686 (rename-buffer (concat "*Occur: "
687 (mapconcat #'buffer-name
688 (car (cddr occur-revert-arguments
)) "/")
692 (defun occur (regexp &optional nlines
)
693 "Show all lines in the current buffer containing a match for REGEXP.
695 If a match spreads across multiple lines, all those lines are shown.
697 Each line is displayed with NLINES lines before and after, or -NLINES
698 before if NLINES is negative.
699 NLINES defaults to `list-matching-lines-default-context-lines'.
700 Interactively it is the prefix arg.
702 The lines are shown in a buffer named `*Occur*'.
703 It serves as a menu to find any of the occurrences in this buffer.
704 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
706 If REGEXP contains upper case characters (excluding those preceded by `\\'),
707 the matching is case-sensitive."
708 (interactive (occur-read-primary-args))
709 (occur-1 regexp nlines
(list (current-buffer))))
711 (defun multi-occur (bufs regexp
&optional nlines
)
712 "Show all lines in buffers BUFS containing a match for REGEXP.
713 This function acts on multiple buffers; otherwise, it is exactly like
717 (let* ((bufs (list (read-buffer "First buffer to search: "
718 (current-buffer) t
)))
720 (ido-ignore-item-temp-list bufs
))
721 (while (not (string-equal
722 (setq buf
(read-buffer
723 (if (eq read-buffer-function
'ido-read-buffer
)
724 "Next buffer to search (C-j to end): "
725 "Next buffer to search (RET to end): ")
728 (add-to-list 'bufs buf
)
729 (setq ido-ignore-item-temp-list bufs
))
730 (nreverse (mapcar #'get-buffer bufs
)))
731 (occur-read-primary-args)))
732 (occur-1 regexp nlines bufs
))
734 (defun multi-occur-by-filename-regexp (bufregexp regexp
&optional nlines
)
735 "Show all lines matching REGEXP in buffers named by BUFREGEXP.
736 See also `multi-occur'."
739 (let* ((default (car regexp-history
))
741 (read-from-minibuffer
742 "List lines in buffers whose filename matches regexp: "
750 (occur-read-primary-args)))
752 (occur-1 regexp nlines
754 (mapcar (lambda (buf)
755 (when (and (buffer-file-name buf
)
756 (string-match bufregexp
757 (buffer-file-name buf
)))
761 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
763 (setq buf-name
"*Occur*"))
764 (let ((occur-buf (get-buffer-create buf-name
))
766 (active-bufs (delq nil
(mapcar #'(lambda (buf)
767 (when (buffer-live-p buf
) buf
))
769 ;; Handle the case where one of the buffers we're searching is the
770 ;; *Occur* buffer itself.
771 (when (memq occur-buf bufs
)
772 (setq occur-buf
(with-current-buffer occur-buf
773 (clone-buffer "*Occur-temp*"))
775 (with-current-buffer occur-buf
776 (setq buffer-read-only nil
)
779 (let ((count (occur-engine
780 regexp active-bufs occur-buf
781 (or nlines list-matching-lines-default-context-lines
)
782 (and case-fold-search
783 (isearch-no-upper-case-p regexp t
))
784 list-matching-lines-buffer-name-face
785 nil list-matching-lines-face nil
)))
786 (let* ((bufcount (length active-bufs
))
787 (diff (- (length bufs
) bufcount
)))
788 (message "Searched %d buffer%s%s; %s match%s for `%s'"
789 bufcount
(if (= bufcount
1) "" "s")
790 (if (zerop diff
) "" (format " (%d killed)" diff
))
791 (if (zerop count
) "no" (format "%d" count
))
792 (if (= count
1) "" "es")
794 ;; If we had to make a temporary buffer, make it the *Occur*
797 (with-current-buffer (get-buffer buf-name
)
798 (kill-buffer (current-buffer)))
799 (rename-buffer buf-name
))
800 (setq occur-revert-arguments
(list regexp nlines bufs
)
803 (display-buffer occur-buf
)
804 (kill-buffer occur-buf
)))
805 (run-hooks 'occur-hook
))))
807 (defun occur-engine-add-prefix (lines)
810 (concat " :" line
"\n"))
813 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
814 title-face prefix-face match-face keep-props
)
815 (with-current-buffer out-buf
816 (setq buffer-read-only nil
)
817 (let ((globalcount 0)
819 ;; Map over all the buffers
820 (dolist (buf buffers
)
821 (when (buffer-live-p buf
)
822 (let ((matches 0) ;; count of matched lines
823 (lines 1) ;; line count
831 (headerpt (with-current-buffer out-buf
(point))))
835 ;; Set CODING only if the current buffer locally
836 ;; binds buffer-file-coding-system.
837 (not (local-variable-p 'buffer-file-coding-system
))
838 (setq coding buffer-file-coding-system
))
840 (goto-char (point-min)) ;; begin searching in the buffer
842 (setq origpt
(point))
843 (when (setq endpt
(re-search-forward regexp nil t
))
844 (setq matches
(1+ matches
)) ;; increment match count
845 (setq matchbeg
(match-beginning 0)
846 matchend
(match-end 0))
847 (setq begpt
(save-excursion
849 (line-beginning-position)))
850 (setq lines
(+ lines
(1- (count-lines origpt endpt
))))
851 (setq marker
(make-marker))
852 (set-marker marker matchbeg
)
853 (setq curstring
(buffer-substring begpt
854 (line-end-position)))
855 ;; Depropertize the string, and maybe
856 ;; highlight the matches
857 (let ((len (length curstring
))
860 (set-text-properties 0 len nil curstring
))
861 (while (and (< start len
)
862 (string-match regexp curstring start
))
863 (add-text-properties (match-beginning 0)
868 `(font-lock-face ,match-face
)))
870 (setq start
(match-end 0))))
871 ;; Generate the string to insert for this match
874 ;; Using 7 digits aligns tabs properly.
875 (apply #'propertize
(format "%7d:" lines
)
878 `(font-lock-face prefix-face
))
884 ;; The simple display style
886 ;; The complex multi-line display
887 ;; style. Generate a list of lines,
888 ;; concatenate them all together.
891 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ nlines
)) keep-props
))))
893 (occur-engine-add-prefix (cdr (occur-accumulate-lines (1+ nlines
) keep-props
))))))))
894 ;; Actually insert the match display data
895 (with-current-buffer out-buf
897 (end (progn (insert data
) (point))))
899 (insert "-------\n"))
902 `(occur-target ,marker help-echo
"mouse-2: go to this occurrence"))
903 ;; We don't put `mouse-face' on the newline,
904 ;; because that loses.
905 (add-text-properties beg
(1- end
) '(mouse-face highlight
)))))
909 (setq lines
(1+ lines
))
910 ;; On to the next match...
912 (goto-char (point-max))))))
913 (when (not (zerop matches
)) ;; is the count zero?
914 (setq globalcount
(+ globalcount matches
))
915 (with-current-buffer out-buf
919 (insert (format "%d lines matching \"%s\" in buffer: %s\n"
920 matches regexp
(buffer-name buf
)))
922 (add-text-properties beg end
925 `(font-lock-face ,title-face
))
926 `(occur-title ,buf
))))
927 (goto-char (point-min)))))))
929 ;; CODING is buffer-file-coding-system of the first buffer
930 ;; that locally binds it. Let's use it also for the output
932 (set-buffer-file-coding-system coding
))
933 ;; Return the number of matches
937 ;; It would be nice to use \\[...], but there is no reasonable way
938 ;; to make that display both SPC and Y.
939 (defconst query-replace-help
940 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
941 RET or `q' to exit, Period to replace one match and exit,
942 Comma to replace but not move point immediately,
943 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
944 C-w to delete match and recursive edit,
945 C-l to clear the screen, redisplay, and offer same replacement again,
946 ! to replace all remaining matches with no more questions,
947 ^ to move point back to previous match,
948 E to edit the replacement string"
949 "Help message while in `query-replace'.")
951 (defvar query-replace-map
(make-sparse-keymap)
952 "Keymap that defines the responses to questions in `query-replace'.
953 The \"bindings\" in this map are not commands; they are answers.
954 The valid answers include `act', `skip', `act-and-show',
955 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
956 `automatic', `backup', `exit-prefix', and `help'.")
958 (define-key query-replace-map
" " 'act
)
959 (define-key query-replace-map
"\d" 'skip
)
960 (define-key query-replace-map
[delete] 'skip)
961 (define-key query-replace-map [backspace] 'skip)
962 (define-key query-replace-map "y" 'act)
963 (define-key query-replace-map "n" 'skip)
964 (define-key query-replace-map "Y" 'act)
965 (define-key query-replace-map "N" 'skip)
966 (define-key query-replace-map "e" 'edit-replacement)
967 (define-key query-replace-map "E" 'edit-replacement)
968 (define-key query-replace-map "," 'act-and-show)
969 (define-key query-replace-map "q" 'exit)
970 (define-key query-replace-map "\r" 'exit)
971 (define-key query-replace-map [return] 'exit)
972 (define-key query-replace-map "." 'act-and-exit)
973 (define-key query-replace-map "\C-r" 'edit)
974 (define-key query-replace-map "\C-w" 'delete-and-edit)
975 (define-key query-replace-map "\C-l" 'recenter)
976 (define-key query-replace-map "!" 'automatic)
977 (define-key query-replace-map "^" 'backup)
978 (define-key query-replace-map "\C-h" 'help)
979 (define-key query-replace-map [f1] 'help)
980 (define-key query-replace-map [help] 'help)
981 (define-key query-replace-map "?" 'help)
982 (define-key query-replace-map "\C-g" 'quit)
983 (define-key query-replace-map "\C-]" 'quit)
984 (define-key query-replace-map "\e" 'exit-prefix)
985 (define-key query-replace-map [escape] 'exit-prefix)
987 (defun replace-match-string-symbols (n)
988 "Process a list (and any sub-lists), expanding certain symbols.
990 N (match-string N) (where N is a string of digits)
991 #N (string-to-number (match-string N))
993 #& (string-to-number (match-string 0))
995 Note that these symbols must be preceeded by a backslash in order to
1000 (replace-match-string-symbols (car n))) ;Process sub-list
1002 (let ((name (symbol-name (car n))))
1004 ((string-match "^[0-9]+$" name)
1005 (setcar n (list 'match-string (string-to-number name))))
1006 ((string-match "^#[0-9]+$" name)
1007 (setcar n (list 'string-to-number
1009 (string-to-number (substring name 1))))))
1011 (setcar n '(match-string 0)))
1012 ((string= "#&" name)
1013 (setcar n '(string-to-number (match-string 0))))))))
1016 (defun replace-eval-replacement (expression replace-count)
1017 (let ((replacement (eval expression)))
1018 (if (stringp replacement)
1020 (prin1-to-string replacement t))))
1022 (defun replace-loop-through-replacements (data replace-count)
1023 ;; DATA is a vector contaning the following values:
1024 ;; 0 next-rotate-count
1026 ;; 2 next-replacement
1028 (if (= (aref data 0) replace-count)
1030 (aset data 0 (+ replace-count (aref data 1)))
1031 (let ((next (cdr (aref data 2))))
1032 (aset data 2 (if (consp next) next (aref data 3))))))
1033 (car (aref data 2)))
1035 (defun perform-replace (from-string replacements
1036 query-flag regexp-flag delimited-flag
1037 &optional repeat-count map start end)
1038 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1039 Don't use this in your own program unless you want to query and set the mark
1040 just as `query-replace' does. Instead, write a simple loop like this:
1042 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1043 (replace-match \"foobar\" nil nil))
1045 which will run faster and probably do exactly what you want. Please
1046 see the documentation of `replace-match' to find out how to simulate
1049 This function returns nil if and only if there were no matches to
1050 make, or the user didn't cancel the call."
1051 (or map (setq map query-replace-map))
1052 (and query-flag minibuffer-auto-raise
1053 (raise-frame (window-frame (minibuffer-window))))
1054 (let ((nocasify (not (and case-fold-search case-replace
1055 (string-equal from-string
1056 (downcase from-string)))))
1057 (case-fold-search (and case-fold-search
1058 (string-equal from-string
1059 (downcase from-string))))
1060 (literal (not regexp-flag))
1061 (search-function (if regexp-flag 're-search-forward 'search-forward))
1062 (search-string from-string)
1063 (real-match-data nil) ; the match data for the current match
1064 (next-replacement nil)
1068 (nonempty-match nil)
1070 ;; If non-nil, it is marker saying where in the buffer to stop.
1073 ;; Data for the next match. If a cons, it has the same format as
1074 ;; (match-data); otherwise it is t if a match is possible at point.
1079 (substitute-command-keys
1080 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
1082 ;; If region is active, in Transient Mark mode, operate on region.
1084 (setq limit (copy-marker (max start end)))
1085 (goto-char (min start end))
1088 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1089 ;; containing a function and its first argument. The function is
1090 ;; called to generate each replacement like this:
1091 ;; (funcall (car replacements) (cdr replacements) replace-count)
1092 ;; It must return a string.
1094 ((stringp replacements)
1095 (setq next-replacement replacements
1097 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1098 (or repeat-count (setq repeat-count 1))
1099 (setq replacements (cons 'replace-loop-through-replacements
1100 (vector repeat-count repeat-count
1101 replacements replacements)))))
1104 (setq search-function 're-search-forward
1105 search-string (concat "\\b"
1106 (if regexp-flag from-string
1107 (regexp-quote from-string))
1112 ;; Loop finding occurrences that perhaps should be replaced.
1113 (while (and keep-going
1115 ;; Use the next match if it is already known;
1116 ;; otherwise, search for a match after moving forward
1117 ;; one char if progress is required.
1118 (setq real-match-data
1119 (if (consp match-again)
1120 (progn (goto-char (nth 1 match-again))
1122 (and (or match-again
1123 ;; MATCH-AGAIN non-nil means we
1124 ;; accept an adjacent match. If
1125 ;; we don't, move one char to the
1126 ;; right. This takes us a
1127 ;; character too far at the end,
1128 ;; but this is undone after the
1130 (progn (forward-char 1) (not (eobp))))
1131 (funcall search-function search-string limit t)
1132 ;; For speed, use only integers and
1133 ;; reuse the list used last time.
1134 (match-data t real-match-data)))))
1135 ;; Optionally ignore matches that have a read-only property.
1136 (unless (and query-replace-skip-read-only
1137 (text-property-not-all
1138 (match-beginning 0) (match-end 0)
1141 ;; Record whether the match is nonempty, to avoid an infinite loop
1142 ;; repeatedly matching the same empty string.
1143 (setq nonempty-match
1144 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1146 ;; If the match is empty, record that the next one can't be
1149 ;; Otherwise, if matching a regular expression, do the next
1150 ;; match now, since the replacement for this match may
1151 ;; affect whether the next match is adjacent to this one.
1152 ;; If that match is empty, don't use it.
1155 (or (not regexp-flag)
1156 (and (looking-at search-string)
1157 (let ((match (match-data)))
1158 (and (/= (nth 0 match) (nth 1 match))
1161 ;; Calculate the replacement string, if necessary.
1163 (set-match-data real-match-data)
1164 (setq next-replacement
1165 (funcall (car replacements) (cdr replacements)
1167 (if (not query-flag)
1168 (let ((inhibit-read-only query-replace-skip-read-only))
1169 (set-match-data real-match-data)
1170 (replace-match next-replacement nocasify literal)
1171 (setq replace-count (1+ replace-count)))
1173 (let (done replaced key def)
1174 ;; Loop reading commands until one of them sets done,
1175 ;; which means it has finished handling this occurrence.
1177 (set-match-data real-match-data)
1178 (replace-highlight (match-beginning 0) (match-end 0))
1179 ;; Bind message-log-max so we don't fill up the message log
1180 ;; with a bunch of identical messages.
1181 (let ((message-log-max nil))
1182 (message message from-string next-replacement))
1183 (setq key (read-event))
1184 ;; Necessary in case something happens during read-event
1185 ;; that clobbers the match data.
1186 (set-match-data real-match-data)
1187 (setq key (vector key))
1188 (setq def (lookup-key map key))
1189 ;; Restore the match data while we process the command.
1190 (cond ((eq def 'help)
1191 (with-output-to-temp-buffer "*Help*"
1193 (concat "Query replacing "
1194 (if regexp-flag "regexp " "")
1195 from-string " with "
1196 next-replacement ".\n\n"
1197 (substitute-command-keys
1198 query-replace-help)))
1199 (with-current-buffer standard-output
1202 (setq keep-going nil)
1206 (let ((elt (pop stack)))
1207 (goto-char (car elt))
1208 (setq replaced (eq t (cdr elt)))
1210 (set-match-data (cdr elt))))
1211 (message "No previous match")
1212 (ding 'no-terminate)
1217 (replace-match next-replacement nocasify literal)
1218 (setq replace-count (1+ replace-count))))
1219 (setq done t replaced t))
1220 ((eq def 'act-and-exit)
1223 (replace-match next-replacement nocasify literal)
1224 (setq replace-count (1+ replace-count))))
1225 (setq keep-going nil)
1226 (setq done t replaced t))
1227 ((eq def 'act-and-show)
1230 (replace-match next-replacement nocasify literal)
1231 (setq replace-count (1+ replace-count))
1232 (setq replaced t))))
1233 ((eq def 'automatic)
1236 (replace-match next-replacement nocasify literal)
1237 (setq replace-count (1+ replace-count))))
1238 (setq done t query-flag nil replaced t))
1244 (let ((opos (point-marker)))
1245 (goto-char (match-beginning 0))
1247 (funcall search-function search-string limit t)
1248 (setq real-match-data (match-data)))
1250 (save-window-excursion
1253 (set-match-data real-match-data)
1254 ;; Before we make the replacement,
1255 ;; decide whether the search string
1256 ;; can match again just after this match.
1257 (if (and regexp-flag nonempty-match)
1258 (setq match-again (and (looking-at search-string)
1261 ;; Edit replacement.
1262 ((eq def 'edit-replacement)
1263 (setq next-replacement
1264 (read-input "Edit replacement string: "
1267 (replace-match next-replacement nocasify literal))
1270 ((eq def 'delete-and-edit)
1271 (delete-region (match-beginning 0) (match-end 0))
1274 (save-excursion (recursive-edit))))
1276 ;; Note: we do not need to treat `exit-prefix'
1277 ;; specially here, since we reread
1278 ;; any unrecognized character.
1280 (setq this-command 'mode-exited)
1281 (setq keep-going nil)
1282 (setq unread-command-events
1283 (append (listify-key-sequence key)
1284 unread-command-events))
1286 ;; Record previous position for ^ when we move on.
1287 ;; Change markers to numbers in the match data
1288 ;; since lots of markers slow down editing.
1291 (or replaced (match-data t)))
1294 ;; The code preventing adjacent regexp matches in the condition
1295 ;; of the while-loop above will haven taken us one character
1296 ;; beyond the last replacement. Undo that.
1297 (when (and regexp-flag (not match-again) (> replace-count 0))
1300 (replace-dehighlight))
1301 (or unread-command-events
1302 (message "Replaced %d occurrence%s"
1304 (if (= replace-count 1) "" "s")))
1305 (and keep-going stack)))
1307 (defcustom query-replace-highlight t
1308 "*Non-nil means to highlight words during query replacement."
1312 (defvar replace-overlay nil)
1314 (defun replace-dehighlight ()
1315 (and replace-overlay
1317 (delete-overlay replace-overlay)
1318 (setq replace-overlay nil))))
1320 (defun replace-highlight (start end)
1321 (and query-replace-highlight
1325 (setq replace-overlay (make-overlay start end))
1326 (overlay-put replace-overlay 'face
1327 (if (facep 'query-replace)
1328 'query-replace 'region))))
1329 (move-overlay replace-overlay start end (current-buffer)))))
1331 ;;; replace.el ends here