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 (setq from
(read-from-minibuffer (format "%s: " string
)
75 query-replace-from-history-variable
77 ;; Warn if user types \n or \t, but don't reject the input.
78 (if (string-match "\\\\[nt]" from
)
79 (let ((match (match-string 0 from
)))
81 ((string= match
"\\n")
82 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
83 ((string= match
"\\t")
84 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
87 (setq to
(read-from-minibuffer (format "%s %s with: " string from
)
89 query-replace-to-history-variable from t
))
90 (if (and transient-mark-mode mark-active
)
91 (list from to current-prefix-arg
(region-beginning) (region-end))
92 (list from to current-prefix-arg nil nil
))))
94 (defun query-replace (from-string to-string
&optional delimited start end
)
95 "Replace some occurrences of FROM-STRING with TO-STRING.
96 As each match is found, the user must type a character saying
97 what to do with it. For directions, type \\[help-command] at that time.
99 In Transient Mark mode, if the mark is active, operate on the contents
100 of the region. Otherwise, operate from point to the end of the buffer.
102 If `query-replace-interactive' is non-nil, the last incremental search
103 string is used as FROM-STRING--you don't have to specify it with the
106 Replacement transfers the case of the old text to the new text,
107 if `case-replace' and `case-fold-search'
108 are non-nil and FROM-STRING has no uppercase letters.
109 \(Preserving case means that if the string matched is all caps, or capitalized,
110 then its replacement is upcased or capitalized.)
112 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
113 only matches surrounded by word boundaries.
114 Fourth and fifth arg START and END specify the region to operate on.
116 To customize possible responses, change the \"bindings\" in `query-replace-map'."
117 (interactive (query-replace-read-args "Query replace" nil
))
118 (perform-replace from-string to-string t nil delimited nil nil start end
))
120 (define-key esc-map
"%" 'query-replace
)
122 (defun query-replace-regexp (regexp to-string
&optional delimited start end
)
123 "Replace some things after point matching REGEXP with TO-STRING.
124 As each match is found, the user must type a character saying
125 what to do with it. For directions, type \\[help-command] at that time.
127 In Transient Mark mode, if the mark is active, operate on the contents
128 of the region. Otherwise, operate from point to the end of the buffer.
130 If `query-replace-interactive' is non-nil, the last incremental search
131 regexp is used as REGEXP--you don't have to specify it with the
134 Preserves case in each replacement if `case-replace' and `case-fold-search'
135 are non-nil and REGEXP has no uppercase letters.
137 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
138 only matches surrounded by word boundaries.
139 Fourth and fifth arg START and END specify the region to operate on.
141 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
142 and `\\=\\N' (where N is a digit) stands for
143 whatever what matched the Nth `\\(...\\)' in REGEXP."
144 (interactive (query-replace-read-args "Query replace regexp" t
))
145 (perform-replace regexp to-string t t delimited nil nil start end
))
146 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
148 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
149 "Replace some things after point matching REGEXP with the result of TO-EXPR.
150 As each match is found, the user must type a character saying
151 what to do with it. For directions, type \\[help-command] at that time.
153 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
154 reference `replace-count' to get the number of replacements already made.
155 If the result of TO-EXPR is not a string, it is converted to one using
156 `prin1-to-string' with the NOESCAPE argument (which see).
158 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
159 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
160 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
161 Use `\\#&' or `\\#N' if you want a number instead of a string.
163 In Transient Mark mode, if the mark is active, operate on the contents
164 of the region. Otherwise, operate from point to the end of the buffer.
166 If `query-replace-interactive' is non-nil, the last incremental search
167 regexp is used as REGEXP--you don't have to specify it with the
170 Preserves case in each replacement if `case-replace' and `case-fold-search'
171 are non-nil and REGEXP has no uppercase letters.
173 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
174 only matches that are surrounded by word boundaries.
175 Fourth and fifth arg START and END specify the region to operate on."
177 (let (from to start end
)
178 (when (and transient-mark-mode mark-active
)
179 (setq start
(region-beginning)
181 (if query-replace-interactive
182 (setq from
(car regexp-search-ring
))
183 (setq from
(read-from-minibuffer "Query replace regexp: "
185 query-replace-from-history-variable
187 (setq to
(list (read-from-minibuffer
188 (format "Query replace regexp %s with eval: " from
)
189 nil nil t query-replace-to-history-variable from t
)))
190 ;; We make TO a list because replace-match-string-symbols requires one,
191 ;; and the user might enter a single token.
192 (replace-match-string-symbols to
)
193 (list from
(car to
) current-prefix-arg start end
)))
194 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
195 t t delimited nil nil start end
))
197 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
198 "Replace some matches for REGEXP with various strings, in rotation.
199 The second argument TO-STRINGS contains the replacement strings,
200 separated by spaces. Third arg DELIMITED (prefix arg if interactive),
201 if non-nil, means replace only matches surrounded by word boundaries.
202 This command works like `query-replace-regexp' except that each
203 successive replacement uses the next successive replacement string,
204 wrapping around from the last such string to the first.
206 In Transient Mark mode, if the mark is active, operate on the contents
207 of the region. Otherwise, operate from point to the end of the buffer.
209 Non-interactively, TO-STRINGS may be a list of replacement strings.
211 If `query-replace-interactive' is non-nil, the last incremental search
212 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
214 A prefix argument N says to use each replacement string N times
215 before rotating to the next.
216 Fourth and fifth arg START and END specify the region to operate on."
218 (let (from to start end
)
219 (when (and transient-mark-mode mark-active
)
220 (setq start
(region-beginning)
222 (setq from
(if query-replace-interactive
223 (car regexp-search-ring
)
224 (read-from-minibuffer "Map query replace (regexp): "
226 'query-replace-history nil t
)))
227 (setq to
(read-from-minibuffer
228 (format "Query replace %s with (space-separated strings): "
231 'query-replace-history from t
))
232 (list from to start end current-prefix-arg
)))
234 (if (listp to-strings
)
235 (setq replacements to-strings
)
236 (while (/= (length to-strings
) 0)
237 (if (string-match " " to-strings
)
240 (list (substring to-strings
0
241 (string-match " " to-strings
))))
242 to-strings
(substring to-strings
243 (1+ (string-match " " to-strings
))))
244 (setq replacements
(append replacements
(list to-strings
))
246 (perform-replace regexp replacements t t nil n nil start end
)))
248 (defun replace-string (from-string to-string
&optional delimited start end
)
249 "Replace occurrences of FROM-STRING with TO-STRING.
250 Preserve case in each match if `case-replace' and `case-fold-search'
251 are non-nil and FROM-STRING has no uppercase letters.
252 \(Preserving case means that if the string matched is all caps, or capitalized,
253 then its replacement is upcased or capitalized.)
255 In Transient Mark mode, if the mark is active, operate on the contents
256 of the region. Otherwise, operate from point to the end of the buffer.
258 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
259 only matches surrounded by word boundaries.
260 Fourth and fifth arg START and END specify the region to operate on.
262 If `query-replace-interactive' is non-nil, the last incremental search
263 string is used as FROM-STRING--you don't have to specify it with the
266 This function is usually the wrong thing to use in a Lisp program.
267 What you probably want is a loop like this:
268 (while (search-forward FROM-STRING nil t)
269 (replace-match TO-STRING nil t))
270 which will run faster and will not set the mark or print anything.
271 \(You may need a more complex loop if FROM-STRING can match the null string
272 and TO-STRING is also null.)"
273 (interactive (query-replace-read-args "Replace string" nil
))
274 (perform-replace from-string to-string nil nil delimited nil nil start end
))
276 (defun replace-regexp (regexp to-string
&optional delimited start end
)
277 "Replace things after point matching REGEXP with TO-STRING.
278 Preserve case in each match if `case-replace' and `case-fold-search'
279 are non-nil and REGEXP has no uppercase letters.
281 In Transient Mark mode, if the mark is active, operate on the contents
282 of the region. Otherwise, operate from point to the end of the buffer.
284 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
285 only matches surrounded by word boundaries.
286 Fourth and fifth arg START and END specify the region to operate on.
288 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
289 and `\\=\\N' (where N is a digit) stands for
290 whatever what matched the Nth `\\(...\\)' in REGEXP.
292 If `query-replace-interactive' is non-nil, the last incremental search
293 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
295 This function is usually the wrong thing to use in a Lisp program.
296 What you probably want is a loop like this:
297 (while (re-search-forward REGEXP nil t)
298 (replace-match TO-STRING nil nil))
299 which will run faster and will not set the mark or print anything."
300 (interactive (query-replace-read-args "Replace regexp" t
))
301 (perform-replace regexp to-string nil t delimited nil nil start end
))
304 (defvar regexp-history nil
305 "History list for some commands that read regular expressions.")
308 (defalias 'delete-non-matching-lines
'keep-lines
)
309 (defalias 'delete-matching-lines
'flush-lines
)
310 (defalias 'count-matches
'how-many
)
313 (defun keep-lines-read-args (prompt)
314 "Read arguments for `keep-lines' and friends.
315 Prompt for a regexp with PROMPT.
316 Value is a list, (REGEXP)."
317 (list (read-from-minibuffer prompt nil nil nil
318 'regexp-history nil t
)))
320 (defun keep-lines (regexp &optional rstart rend
)
321 "Delete all lines except those containing matches for REGEXP.
322 A match split across lines preserves all the lines it lies in.
323 Applies to all lines after point.
325 If REGEXP contains upper case characters (excluding those preceded by `\\'),
326 the matching is case-sensitive.
328 Second and third arg RSTART and REND specify the region to operate on.
330 Interactively, in Transient Mark mode when the mark is active, operate
331 on the contents of the region. Otherwise, operate from point to the
336 (barf-if-buffer-read-only)
337 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
340 (goto-char (min rstart rend
))
341 (setq rend
(copy-marker (max rstart rend
))))
342 (if (and transient-mark-mode mark-active
)
343 (setq rstart
(region-beginning)
344 rend
(copy-marker (region-end)))
346 rend
(point-max-marker)))
349 (or (bolp) (forward-line 1))
350 (let ((start (point))
351 (case-fold-search (and case-fold-search
352 (isearch-no-upper-case-p regexp t
))))
353 (while (< (point) rend
)
354 ;; Start is first char not preserved by previous match.
355 (if (not (re-search-forward regexp rend
'move
))
356 (delete-region start rend
)
357 (let ((end (save-excursion (goto-char (match-beginning 0))
360 ;; Now end is first char preserved by the new match.
362 (delete-region start end
))))
364 (setq start
(save-excursion (forward-line 1) (point)))
365 ;; If the match was empty, avoid matching again at same place.
366 (and (< (point) rend
)
367 (= (match-beginning 0) (match-end 0))
368 (forward-char 1))))))
371 (defun flush-lines (regexp &optional rstart rend
)
372 "Delete lines containing matches for REGEXP.
373 If a match is split across lines, all the lines it lies in are deleted.
374 Applies to lines after point.
376 If REGEXP contains upper case characters (excluding those preceded by `\\'),
377 the matching is case-sensitive.
379 Second and third arg RSTART and REND specify the region to operate on.
381 Interactively, in Transient Mark mode when the mark is active, operate
382 on the contents of the region. Otherwise, operate from point to the
387 (barf-if-buffer-read-only)
388 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
391 (goto-char (min rstart rend
))
392 (setq rend
(copy-marker (max rstart rend
))))
393 (if (and transient-mark-mode mark-active
)
394 (setq rstart
(region-beginning)
395 rend
(copy-marker (region-end)))
397 rend
(point-max-marker)))
399 (let ((case-fold-search (and case-fold-search
400 (isearch-no-upper-case-p regexp t
))))
402 (while (and (< (point) rend
)
403 (re-search-forward regexp rend t
))
404 (delete-region (save-excursion (goto-char (match-beginning 0))
407 (progn (forward-line 1) (point)))))))
410 (defun how-many (regexp &optional rstart rend
)
411 "Print number of matches for REGEXP following point.
413 If REGEXP contains upper case characters (excluding those preceded by `\\'),
414 the matching is case-sensitive.
416 Second and third arg RSTART and REND specify the region to operate on.
418 Interactively, in Transient Mark mode when the mark is active, operate
419 on the contents of the region. Otherwise, operate from point to the
423 (keep-lines-read-args "How many matches for (regexp): "))
426 (goto-char (min rstart rend
))
427 (if (and transient-mark-mode mark-active
)
428 (setq rstart
(region-beginning)
429 rend
(copy-marker (region-end)))
431 rend
(point-max-marker)))
435 (case-fold-search (and case-fold-search
436 (isearch-no-upper-case-p regexp t
))))
437 (while (and (< (point) rend
)
438 (progn (setq opoint
(point))
439 (re-search-forward regexp rend t
)))
440 (if (= opoint
(point))
442 (setq count
(1+ count
))))
443 (message "%d occurrences" count
))))
446 (defvar occur-mode-map
447 (let ((map (make-sparse-keymap)))
448 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
449 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
450 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
451 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
452 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
453 (define-key map
"\M-n" 'occur-next
)
454 (define-key map
"\M-p" 'occur-prev
)
455 (define-key map
"r" 'occur-rename-buffer
)
456 (define-key map
"c" 'clone-buffer
)
457 (define-key map
"g" 'revert-buffer
)
458 (define-key map
"q" 'quit-window
)
459 (define-key map
"z" 'kill-this-buffer
)
461 "Keymap for `occur-mode'.")
463 (defvar occur-revert-arguments nil
464 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
465 See `occur-revert-function'.")
467 (defcustom occur-mode-hook
'(turn-on-font-lock)
468 "Hook run when entering Occur mode."
472 (defcustom occur-hook nil
473 "Hook run when `occur' is called."
477 (put 'occur-mode
'mode-class
'special
)
479 "Major mode for output from \\[occur].
480 \\<occur-mode-map>Move point to one of the items in this buffer, then use
481 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
482 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
486 (kill-all-local-variables)
487 (use-local-map occur-mode-map
)
488 (setq major-mode
'occur-mode
)
489 (setq mode-name
"Occur")
490 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
491 (make-local-variable 'occur-revert-arguments
)
492 (add-hook 'change-major-mode-hook
'font-lock-defontify nil t
)
493 (run-hooks 'occur-mode-hook
))
495 (defun occur-revert-function (ignore1 ignore2
)
496 "Handle `revert-buffer' for Occur mode buffers."
497 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
499 (defun occur-mode-mouse-goto (event)
500 "In Occur mode, go to the occurrence whose line you click on."
504 (set-buffer (window-buffer (posn-window (event-end event
))))
506 (goto-char (posn-point (event-end event
)))
507 (setq pos
(occur-mode-find-occurrence))))
508 (pop-to-buffer (marker-buffer pos
))
511 (defun occur-mode-find-occurrence ()
512 (let ((pos (get-text-property (point) 'occur-target
)))
514 (error "No occurrence on this line"))
515 (unless (buffer-live-p (marker-buffer pos
))
516 (error "Buffer for this occurrence was killed"))
519 (defun occur-mode-goto-occurrence ()
520 "Go to the occurrence the current line describes."
522 (let ((pos (occur-mode-find-occurrence)))
523 (pop-to-buffer (marker-buffer pos
))
526 (defun occur-mode-goto-occurrence-other-window ()
527 "Go to the occurrence the current line describes, in another window."
529 (let ((pos (occur-mode-find-occurrence)))
530 (switch-to-buffer-other-window (marker-buffer pos
))
533 (defun occur-mode-display-occurrence ()
534 "Display in another window the occurrence the current line describes."
536 (let ((pos (occur-mode-find-occurrence))
538 ;; Bind these to ensure `display-buffer' puts it in another window.
539 same-window-buffer-names
541 (setq window
(display-buffer (marker-buffer pos
)))
542 ;; This is the way to set point in the proper window.
543 (save-selected-window
544 (select-window window
)
547 (defun occur-find-match (n search message
)
548 (if (not n
) (setq n
1))
551 (setq r
(funcall search
(point) 'occur-match
))
553 (get-text-property r
'occur-match
)
554 (setq r
(funcall search r
'occur-match
)))
560 (defun occur-next (&optional n
)
561 "Move to the Nth (default 1) next match in an Occur mode buffer."
563 (occur-find-match n
#'next-single-property-change
"No more matches"))
565 (defun occur-prev (&optional n
)
566 "Move to the Nth (default 1) previous match in an Occur mode buffer."
568 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
570 (defcustom list-matching-lines-default-context-lines
0
571 "*Default number of context lines included around `list-matching-lines' matches.
572 A negative number means to include that many lines before the match.
573 A positive number means to include that many lines both before and after."
577 (defalias 'list-matching-lines
'occur
)
579 (defcustom list-matching-lines-face
'bold
580 "*Face used by \\[list-matching-lines] to show the text that matches.
581 If the value is nil, don't highlight the matching portions specially."
585 (defcustom list-matching-lines-buffer-name-face
'underline
586 "*Face used by \\[list-matching-lines] to show the names of buffers.
587 If the value is nil, don't highlight the buffer names specially."
591 (defun occur-accumulate-lines (count &optional no-props
)
593 (let ((forwardp (> count
0))
595 (while (not (or (zerop count
)
599 (setq count
(+ count
(if forwardp -
1 1)))
601 (funcall (if no-props
602 #'buffer-substring-no-properties
604 (line-beginning-position)
607 (forward-line (if forwardp
1 -
1)))
610 (defun occur-read-primary-args ()
611 (list (let* ((default (car regexp-history
))
613 (read-from-minibuffer
615 (format "List lines matching regexp (default `%s'): "
617 "List lines matching regexp: ")
625 (when current-prefix-arg
626 (prefix-numeric-value current-prefix-arg
))))
628 (defun occur-rename-buffer (&optional unique-p
)
629 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
630 Here `original-buffer-name' is the buffer name were occur was originally run.
631 When given the prefix argument, the renaming will not clobber the existing
632 buffer(s) of that name, but use `generate-new-buffer-name' instead.
633 You can add this to `occur-hook' if you always want a separate *Occur*
634 buffer for each buffer where you invoke `occur'."
637 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
638 (rename-buffer (concat "*Occur: "
639 (mapconcat #'buffer-name
640 (car (cddr occur-revert-arguments
)) "/")
644 (defun occur (regexp &optional nlines
)
645 "Show all lines in the current buffer containing a match for REGEXP.
647 If a match spreads across multiple lines, all those lines are shown.
649 Each line is displayed with NLINES lines before and after, or -NLINES
650 before if NLINES is negative.
651 NLINES defaults to `list-matching-lines-default-context-lines'.
652 Interactively it is the prefix arg.
654 The lines are shown in a buffer named `*Occur*'.
655 It serves as a menu to find any of the occurrences in this buffer.
656 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
658 If REGEXP contains upper case characters (excluding those preceded by `\\'),
659 the matching is case-sensitive."
660 (interactive (occur-read-primary-args))
661 (occur-1 regexp nlines
(list (current-buffer))))
663 (defun multi-occur (bufs regexp
&optional nlines
)
664 "Show all lines in buffers BUFS containing a match for REGEXP.
665 This function acts on multiple buffers; otherwise, it is exactly like
669 (let* ((bufs (list (read-buffer "First buffer to search: "
670 (current-buffer) t
)))
672 (ido-ignore-item-temp-list bufs
))
673 (while (not (string-equal
674 (setq buf
(read-buffer
675 (if (eq read-buffer-function
'ido-read-buffer
)
676 "Next buffer to search (C-j to end): "
677 "Next buffer to search (RET to end): ")
680 (add-to-list 'bufs buf
)
681 (setq ido-ignore-item-temp-list bufs
))
682 (nreverse (mapcar #'get-buffer bufs
)))
683 (occur-read-primary-args)))
684 (occur-1 regexp nlines bufs
))
686 (defun multi-occur-by-filename-regexp (bufregexp regexp
&optional nlines
)
687 "Show all lines matching REGEXP in buffers named by BUFREGEXP.
688 See also `multi-occur'."
691 (let* ((default (car regexp-history
))
693 (read-from-minibuffer
694 "List lines in buffers whose filename matches regexp: "
702 (occur-read-primary-args)))
704 (occur-1 regexp nlines
706 (mapcar (lambda (buf)
707 (when (and (buffer-file-name buf
)
708 (string-match bufregexp
709 (buffer-file-name buf
)))
713 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
715 (setq buf-name
"*Occur*"))
716 (let ((occur-buf (get-buffer-create buf-name
))
718 (active-bufs (delq nil
(mapcar #'(lambda (buf)
719 (when (buffer-live-p buf
) buf
))
721 ;; Handle the case where one of the buffers we're searching is the
722 ;; *Occur* buffer itself.
723 (when (memq occur-buf bufs
)
724 (setq occur-buf
(with-current-buffer occur-buf
725 (clone-buffer "*Occur-temp*"))
727 (with-current-buffer occur-buf
728 (setq buffer-read-only nil
)
731 (let ((count (occur-engine
732 regexp active-bufs occur-buf
733 (or nlines list-matching-lines-default-context-lines
)
734 (and case-fold-search
735 (isearch-no-upper-case-p regexp t
))
736 list-matching-lines-buffer-name-face
737 nil list-matching-lines-face nil
)))
738 (let* ((bufcount (length active-bufs
))
739 (diff (- (length bufs
) bufcount
)))
740 (message "Searched %d buffer%s%s; %s match%s for `%s'"
741 bufcount
(if (= bufcount
1) "" "s")
742 (if (zerop diff
) "" (format " (%d killed)" diff
))
743 (if (zerop count
) "no" (format "%d" count
))
744 (if (= count
1) "" "es")
746 ;; If we had to make a temporary buffer, make it the *Occur*
749 (with-current-buffer (get-buffer buf-name
)
750 (kill-buffer (current-buffer)))
751 (rename-buffer buf-name
))
752 (setq occur-revert-arguments
(list regexp nlines bufs
)
755 (display-buffer occur-buf
)
756 (kill-buffer occur-buf
)))
757 (run-hooks 'occur-hook
))))
759 (defun occur-engine-add-prefix (lines)
762 (concat " :" line
"\n"))
765 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
766 title-face prefix-face match-face keep-props
)
767 (with-current-buffer out-buf
768 (setq buffer-read-only nil
)
769 (let ((globalcount 0))
770 ;; Map over all the buffers
771 (dolist (buf buffers
)
772 (when (buffer-live-p buf
)
773 (let ((matches 0) ;; count of matched lines
774 (lines 1) ;; line count
782 (headerpt (with-current-buffer out-buf
(point))))
786 (goto-char (point-min)) ;; begin searching in the buffer
788 (setq origpt
(point))
789 (when (setq endpt
(re-search-forward regexp nil t
))
790 (setq matches
(1+ matches
)) ;; increment match count
791 (setq matchbeg
(match-beginning 0)
792 matchend
(match-end 0))
793 (setq begpt
(save-excursion
795 (line-beginning-position)))
796 (setq lines
(+ lines
(1- (count-lines origpt endpt
))))
797 (setq marker
(make-marker))
798 (set-marker marker matchbeg
)
799 (setq curstring
(buffer-substring begpt
800 (line-end-position)))
801 ;; Depropertize the string, and maybe
802 ;; highlight the matches
803 (let ((len (length curstring
))
806 (set-text-properties 0 len nil curstring
))
807 (while (and (< start len
)
808 (string-match regexp curstring start
))
809 (add-text-properties (match-beginning 0)
814 `(font-lock-face ,match-face
)))
816 (setq start
(match-end 0))))
817 ;; Generate the string to insert for this match
820 ;; Using 7 digits aligns tabs properly.
821 (apply #'propertize
(format "%7d:" lines
)
824 `(font-lock-face prefix-face
))
830 ;; The simple display style
832 ;; The complex multi-line display
833 ;; style. Generate a list of lines,
834 ;; concatenate them all together.
837 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ nlines
)) keep-props
))))
839 (occur-engine-add-prefix (cdr (occur-accumulate-lines (1+ nlines
) keep-props
))))))))
840 ;; Actually insert the match display data
841 (with-current-buffer out-buf
843 (end (progn (insert data
) (point))))
845 (insert "-------\n"))
848 `(occur-target ,marker help-echo
"mouse-2: go to this occurrence"))
849 ;; We don't put `mouse-face' on the newline,
850 ;; because that loses.
851 (add-text-properties beg
(1- end
) '(mouse-face highlight
)))))
855 (setq lines
(1+ lines
))
856 ;; On to the next match...
858 (goto-char (point-max))))))
859 (when (not (zerop matches
)) ;; is the count zero?
860 (setq globalcount
(+ globalcount matches
))
861 (with-current-buffer out-buf
865 (insert (format "%d lines matching \"%s\" in buffer: %s\n"
866 matches regexp
(buffer-name buf
)))
868 (add-text-properties beg end
871 `(font-lock-face ,title-face
))
872 `(occur-title ,buf
))))
873 (goto-char (point-min)))))))
874 ;; Return the number of matches
878 ;; It would be nice to use \\[...], but there is no reasonable way
879 ;; to make that display both SPC and Y.
880 (defconst query-replace-help
881 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
882 RET or `q' to exit, Period to replace one match and exit,
883 Comma to replace but not move point immediately,
884 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
885 C-w to delete match and recursive edit,
886 C-l to clear the screen, redisplay, and offer same replacement again,
887 ! to replace all remaining matches with no more questions,
888 ^ to move point back to previous match,
889 E to edit the replacement string"
890 "Help message while in `query-replace'.")
892 (defvar query-replace-map
(make-sparse-keymap)
893 "Keymap that defines the responses to questions in `query-replace'.
894 The \"bindings\" in this map are not commands; they are answers.
895 The valid answers include `act', `skip', `act-and-show',
896 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
897 `automatic', `backup', `exit-prefix', and `help'.")
899 (define-key query-replace-map
" " 'act
)
900 (define-key query-replace-map
"\d" 'skip
)
901 (define-key query-replace-map
[delete] 'skip)
902 (define-key query-replace-map [backspace] 'skip)
903 (define-key query-replace-map "y" 'act)
904 (define-key query-replace-map "n" 'skip)
905 (define-key query-replace-map "Y" 'act)
906 (define-key query-replace-map "N" 'skip)
907 (define-key query-replace-map "e" 'edit-replacement)
908 (define-key query-replace-map "E" 'edit-replacement)
909 (define-key query-replace-map "," 'act-and-show)
910 (define-key query-replace-map "q" 'exit)
911 (define-key query-replace-map "\r" 'exit)
912 (define-key query-replace-map [return] 'exit)
913 (define-key query-replace-map "." 'act-and-exit)
914 (define-key query-replace-map "\C-r" 'edit)
915 (define-key query-replace-map "\C-w" 'delete-and-edit)
916 (define-key query-replace-map "\C-l" 'recenter)
917 (define-key query-replace-map "!" 'automatic)
918 (define-key query-replace-map "^" 'backup)
919 (define-key query-replace-map "\C-h" 'help)
920 (define-key query-replace-map [f1] 'help)
921 (define-key query-replace-map [help] 'help)
922 (define-key query-replace-map "?" 'help)
923 (define-key query-replace-map "\C-g" 'quit)
924 (define-key query-replace-map "\C-]" 'quit)
925 (define-key query-replace-map "\e" 'exit-prefix)
926 (define-key query-replace-map [escape] 'exit-prefix)
928 (defun replace-match-string-symbols (n)
929 "Process a list (and any sub-lists), expanding certain symbols.
931 N (match-string N) (where N is a string of digits)
932 #N (string-to-number (match-string N))
934 #& (string-to-number (match-string 0))
936 Note that these symbols must be preceeded by a backslash in order to
941 (replace-match-string-symbols (car n))) ;Process sub-list
943 (let ((name (symbol-name (car n))))
945 ((string-match "^[0-9]+$" name)
946 (setcar n (list 'match-string (string-to-number name))))
947 ((string-match "^#[0-9]+$" name)
948 (setcar n (list 'string-to-number
950 (string-to-number (substring name 1))))))
952 (setcar n '(match-string 0)))
954 (setcar n '(string-to-number (match-string 0))))))))
957 (defun replace-eval-replacement (expression replace-count)
958 (let ((replacement (eval expression)))
959 (if (stringp replacement)
961 (prin1-to-string replacement t))))
963 (defun replace-loop-through-replacements (data replace-count)
964 ;; DATA is a vector contaning the following values:
965 ;; 0 next-rotate-count
967 ;; 2 next-replacement
969 (if (= (aref data 0) replace-count)
971 (aset data 0 (+ replace-count (aref data 1)))
972 (let ((next (cdr (aref data 2))))
973 (aset data 2 (if (consp next) next (aref data 3))))))
976 (defun perform-replace (from-string replacements
977 query-flag regexp-flag delimited-flag
978 &optional repeat-count map start end)
979 "Subroutine of `query-replace'. Its complexity handles interactive queries.
980 Don't use this in your own program unless you want to query and set the mark
981 just as `query-replace' does. Instead, write a simple loop like this:
983 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
984 (replace-match \"foobar\" nil nil))
986 which will run faster and probably do exactly what you want. Please
987 see the documentation of `replace-match' to find out how to simulate
990 This function returns nil if and only if there were no matches to
991 make, or the user didn't cancel the call."
992 (or map (setq map query-replace-map))
993 (and query-flag minibuffer-auto-raise
994 (raise-frame (window-frame (minibuffer-window))))
995 (let ((nocasify (not (and case-fold-search case-replace
996 (string-equal from-string
997 (downcase from-string)))))
998 (case-fold-search (and case-fold-search
999 (string-equal from-string
1000 (downcase from-string))))
1001 (literal (not regexp-flag))
1002 (search-function (if regexp-flag 're-search-forward 'search-forward))
1003 (search-string from-string)
1004 (real-match-data nil) ; the match data for the current match
1005 (next-replacement nil)
1009 (nonempty-match nil)
1011 ;; If non-nil, it is marker saying where in the buffer to stop.
1014 ;; Data for the next match. If a cons, it has the same format as
1015 ;; (match-data); otherwise it is t if a match is possible at point.
1020 (substitute-command-keys
1021 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
1023 ;; If region is active, in Transient Mark mode, operate on region.
1025 (setq limit (copy-marker (max start end)))
1026 (goto-char (min start end))
1029 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1030 ;; containing a function and its first argument. The function is
1031 ;; called to generate each replacement like this:
1032 ;; (funcall (car replacements) (cdr replacements) replace-count)
1033 ;; It must return a string.
1035 ((stringp replacements)
1036 (setq next-replacement replacements
1038 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1039 (or repeat-count (setq repeat-count 1))
1040 (setq replacements (cons 'replace-loop-through-replacements
1041 (vector repeat-count repeat-count
1042 replacements replacements)))))
1045 (setq search-function 're-search-forward
1046 search-string (concat "\\b"
1047 (if regexp-flag from-string
1048 (regexp-quote from-string))
1053 ;; Loop finding occurrences that perhaps should be replaced.
1054 (while (and keep-going
1056 ;; Use the next match if it is already known;
1057 ;; otherwise, search for a match after moving forward
1058 ;; one char if progress is required.
1059 (setq real-match-data
1060 (if (consp match-again)
1061 (progn (goto-char (nth 1 match-again))
1063 (and (or match-again
1064 ;; MATCH-AGAIN non-nil means we
1065 ;; accept an adjacent match. If
1066 ;; we don't, move one char to the
1067 ;; right. This takes us a
1068 ;; character too far at the end,
1069 ;; but this is undone after the
1071 (progn (forward-char 1) (not (eobp))))
1072 (funcall search-function search-string limit t)
1073 ;; For speed, use only integers and
1074 ;; reuse the list used last time.
1075 (match-data t real-match-data)))))
1076 ;; Optionally ignore matches that have a read-only property.
1077 (unless (and query-replace-skip-read-only
1078 (text-property-not-all
1079 (match-beginning 0) (match-end 0)
1082 ;; Record whether the match is nonempty, to avoid an infinite loop
1083 ;; repeatedly matching the same empty string.
1084 (setq nonempty-match
1085 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1087 ;; If the match is empty, record that the next one can't be
1090 ;; Otherwise, if matching a regular expression, do the next
1091 ;; match now, since the replacement for this match may
1092 ;; affect whether the next match is adjacent to this one.
1093 ;; If that match is empty, don't use it.
1096 (or (not regexp-flag)
1097 (and (looking-at search-string)
1098 (let ((match (match-data)))
1099 (and (/= (nth 0 match) (nth 1 match))
1102 ;; Calculate the replacement string, if necessary.
1104 (set-match-data real-match-data)
1105 (setq next-replacement
1106 (funcall (car replacements) (cdr replacements)
1108 (if (not query-flag)
1109 (let ((inhibit-read-only query-replace-skip-read-only))
1110 (set-match-data real-match-data)
1111 (replace-match next-replacement nocasify literal)
1112 (setq replace-count (1+ replace-count)))
1114 (let (done replaced key def)
1115 ;; Loop reading commands until one of them sets done,
1116 ;; which means it has finished handling this occurrence.
1118 (set-match-data real-match-data)
1119 (replace-highlight (match-beginning 0) (match-end 0))
1120 ;; Bind message-log-max so we don't fill up the message log
1121 ;; with a bunch of identical messages.
1122 (let ((message-log-max nil))
1123 (message message from-string next-replacement))
1124 (setq key (read-event))
1125 ;; Necessary in case something happens during read-event
1126 ;; that clobbers the match data.
1127 (set-match-data real-match-data)
1128 (setq key (vector key))
1129 (setq def (lookup-key map key))
1130 ;; Restore the match data while we process the command.
1131 (cond ((eq def 'help)
1132 (with-output-to-temp-buffer "*Help*"
1134 (concat "Query replacing "
1135 (if regexp-flag "regexp " "")
1136 from-string " with "
1137 next-replacement ".\n\n"
1138 (substitute-command-keys
1139 query-replace-help)))
1140 (with-current-buffer standard-output
1143 (setq keep-going nil)
1147 (let ((elt (pop stack)))
1148 (goto-char (car elt))
1149 (setq replaced (eq t (cdr elt)))
1151 (set-match-data (cdr elt))))
1152 (message "No previous match")
1153 (ding 'no-terminate)
1158 (replace-match next-replacement nocasify literal)
1159 (setq replace-count (1+ replace-count))))
1160 (setq done t replaced t))
1161 ((eq def 'act-and-exit)
1164 (replace-match next-replacement nocasify literal)
1165 (setq replace-count (1+ replace-count))))
1166 (setq keep-going nil)
1167 (setq done t replaced t))
1168 ((eq def 'act-and-show)
1171 (replace-match next-replacement nocasify literal)
1172 (setq replace-count (1+ replace-count))
1173 (setq replaced t))))
1174 ((eq def 'automatic)
1177 (replace-match next-replacement nocasify literal)
1178 (setq replace-count (1+ replace-count))))
1179 (setq done t query-flag nil replaced t))
1185 (let ((opos (point-marker)))
1186 (goto-char (match-beginning 0))
1188 (funcall search-function search-string limit t)
1189 (setq real-match-data (match-data)))
1191 (save-window-excursion
1194 (set-match-data real-match-data)
1195 ;; Before we make the replacement,
1196 ;; decide whether the search string
1197 ;; can match again just after this match.
1198 (if (and regexp-flag nonempty-match)
1199 (setq match-again (and (looking-at search-string)
1202 ;; Edit replacement.
1203 ((eq def 'edit-replacement)
1204 (setq next-replacement
1205 (read-input "Edit replacement string: "
1208 (replace-match next-replacement nocasify literal))
1211 ((eq def 'delete-and-edit)
1212 (delete-region (match-beginning 0) (match-end 0))
1215 (save-excursion (recursive-edit))))
1217 ;; Note: we do not need to treat `exit-prefix'
1218 ;; specially here, since we reread
1219 ;; any unrecognized character.
1221 (setq this-command 'mode-exited)
1222 (setq keep-going nil)
1223 (setq unread-command-events
1224 (append (listify-key-sequence key)
1225 unread-command-events))
1227 ;; Record previous position for ^ when we move on.
1228 ;; Change markers to numbers in the match data
1229 ;; since lots of markers slow down editing.
1232 (or replaced (match-data t)))
1235 ;; The code preventing adjacent regexp matches in the condition
1236 ;; of the while-loop above will haven taken us one character
1237 ;; beyond the last replacement. Undo that.
1238 (when (and regexp-flag (not match-again) (> replace-count 0))
1241 (replace-dehighlight))
1242 (or unread-command-events
1243 (message "Replaced %d occurrence%s"
1245 (if (= replace-count 1) "" "s")))
1246 (and keep-going stack)))
1248 (defcustom query-replace-highlight t
1249 "*Non-nil means to highlight words during query replacement."
1253 (defvar replace-overlay nil)
1255 (defun replace-dehighlight ()
1256 (and replace-overlay
1258 (delete-overlay replace-overlay)
1259 (setq replace-overlay nil))))
1261 (defun replace-highlight (start end)
1262 (and query-replace-highlight
1266 (setq replace-overlay (make-overlay start end))
1267 (overlay-put replace-overlay 'face
1268 (if (facep 'query-replace)
1269 'query-replace 'region))))
1270 (move-overlay replace-overlay start end (current-buffer)))))
1272 ;;; replace.el ends here