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)
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.
25 ;; This package supplies the string and regular-expression replace functions
26 ;; documented in the Emacs user's manual.
33 (defcustom case-replace t
34 "*Non-nil means `query-replace' should preserve case in replacements."
38 (defvar query-replace-history nil
)
40 (defvar query-replace-interactive nil
41 "Non-nil means `query-replace' uses the last search string.
42 That becomes the \"string to replace\".")
44 (defcustom query-replace-from-history-variable
'query-replace-history
45 "History list to use for the FROM argument of `query-replace' commands.
46 The value of this variable should be a symbol; that symbol
47 is used as a variable to hold a history list for the strings
48 or patterns to be replaced."
53 (defcustom query-replace-to-history-variable
'query-replace-history
54 "History list to use for the TO argument of `query-replace' commands.
55 The value of this variable should be a symbol; that symbol
56 is used as a variable to hold a history list for replacement
62 (defcustom query-replace-skip-read-only nil
63 "*Non-nil means `query-replace' and friends ignore read-only matches."
68 (defun query-replace-read-args (string regexp-flag
&optional noerror
)
70 (barf-if-buffer-read-only))
72 (if query-replace-interactive
73 (setq from
(car (if regexp-flag regexp-search-ring search-ring
)))
74 (setq from
(read-from-minibuffer (format "%s: " string
)
76 query-replace-from-history-variable
78 ;; Warn if user types \n or \t, but don't reject the input.
79 (if (string-match "\\\\[nt]" from
)
80 (let ((match (match-string 0 from
)))
82 ((string= match
"\\n")
83 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
84 ((string= match
"\\t")
85 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
88 (setq to
(read-from-minibuffer (format "%s %s with: " string from
)
90 query-replace-to-history-variable from t
))
91 (if (and transient-mark-mode mark-active
)
92 (list from to current-prefix-arg
(region-beginning) (region-end))
93 (list from to current-prefix-arg nil nil
))))
95 (defun query-replace (from-string to-string
&optional delimited start end
)
96 "Replace some occurrences of FROM-STRING with TO-STRING.
97 As each match is found, the user must type a character saying
98 what to do with it. For directions, type \\[help-command] at that time.
100 In Transient Mark mode, if the mark is active, operate on the contents
101 of the region. Otherwise, operate from point to the end of the buffer.
103 If `query-replace-interactive' is non-nil, the last incremental search
104 string is used as FROM-STRING--you don't have to specify it with the
107 Replacement transfers the case of the old text to the new text,
108 if `case-replace' and `case-fold-search'
109 are non-nil and FROM-STRING has no uppercase letters.
110 \(Preserving case means that if the string matched is all caps, or capitalized,
111 then its replacement is upcased or capitalized.)
113 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
114 only matches surrounded by word boundaries.
115 Fourth and fifth arg START and END specify the region to operate on.
117 To customize possible responses, change the \"bindings\" in `query-replace-map'."
118 (interactive (query-replace-read-args "Query replace" nil
))
119 (perform-replace from-string to-string t nil delimited nil nil start end
))
121 (define-key esc-map
"%" 'query-replace
)
123 (defun query-replace-regexp (regexp to-string
&optional delimited start end
)
124 "Replace some things after point matching REGEXP with TO-STRING.
125 As each match is found, the user must type a character saying
126 what to do with it. For directions, type \\[help-command] at that time.
128 In Transient Mark mode, if the mark is active, operate on the contents
129 of the region. Otherwise, operate from point to the end of the buffer.
131 If `query-replace-interactive' is non-nil, the last incremental search
132 regexp is used as REGEXP--you don't have to specify it with the
135 Preserves case in each replacement if `case-replace' and `case-fold-search'
136 are non-nil and REGEXP has no uppercase letters.
138 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
139 only matches surrounded by word boundaries.
140 Fourth and fifth arg START and END specify the region to operate on.
142 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
143 and `\\=\\N' (where N is a digit) stands for
144 whatever what matched the Nth `\\(...\\)' in REGEXP."
145 (interactive (query-replace-read-args "Query replace regexp" t
))
146 (perform-replace regexp to-string t t delimited nil nil start end
))
147 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
149 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
150 "Replace some things after point matching REGEXP with the result of TO-EXPR.
151 As each match is found, the user must type a character saying
152 what to do with it. For directions, type \\[help-command] at that time.
154 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
155 reference `replace-count' to get the number of replacements already made.
156 If the result of TO-EXPR is not a string, it is converted to one using
157 `prin1-to-string' with the NOESCAPE argument (which see).
159 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
160 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
161 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
162 Use `\\#&' or `\\#N' if you want a number instead of a string.
164 In Transient Mark mode, if the mark is active, operate on the contents
165 of the region. Otherwise, operate from point to the end of the buffer.
167 If `query-replace-interactive' is non-nil, the last incremental search
168 regexp is used as REGEXP--you don't have to specify it with the
171 Preserves case in each replacement if `case-replace' and `case-fold-search'
172 are non-nil and REGEXP has no uppercase letters.
174 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
175 only matches that are surrounded by word boundaries.
176 Fourth and fifth arg START and END specify the region to operate on."
178 (let (from to start end
)
179 (when (and transient-mark-mode mark-active
)
180 (setq start
(region-beginning)
182 (if query-replace-interactive
183 (setq from
(car regexp-search-ring
))
184 (setq from
(read-from-minibuffer "Query replace regexp: "
186 query-replace-from-history-variable
188 (setq to
(list (read-from-minibuffer
189 (format "Query replace regexp %s with eval: " from
)
190 nil nil t query-replace-to-history-variable from t
)))
191 ;; We make TO a list because replace-match-string-symbols requires one,
192 ;; and the user might enter a single token.
193 (replace-match-string-symbols to
)
194 (list from
(car to
) current-prefix-arg start end
)))
195 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
196 t t delimited nil nil start end
))
198 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
199 "Replace some matches for REGEXP with various strings, in rotation.
200 The second argument TO-STRINGS contains the replacement strings,
201 separated by spaces. Third arg DELIMITED (prefix arg if interactive),
202 if non-nil, means replace only matches surrounded by word boundaries.
203 This command works like `query-replace-regexp' except that each
204 successive replacement uses the next successive replacement string,
205 wrapping around from the last such string to the first.
207 In Transient Mark mode, if the mark is active, operate on the contents
208 of the region. Otherwise, operate from point to the end of the buffer.
210 Non-interactively, TO-STRINGS may be a list of replacement strings.
212 If `query-replace-interactive' is non-nil, the last incremental search
213 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
215 A prefix argument N says to use each replacement string N times
216 before rotating to the next.
217 Fourth and fifth arg START and END specify the region to operate on."
219 (let (from to start end
)
220 (when (and transient-mark-mode mark-active
)
221 (setq start
(region-beginning)
223 (setq from
(if query-replace-interactive
224 (car regexp-search-ring
)
225 (read-from-minibuffer "Map query replace (regexp): "
227 'query-replace-history nil t
)))
228 (setq to
(read-from-minibuffer
229 (format "Query replace %s with (space-separated strings): "
232 'query-replace-history from t
))
233 (list from to start end current-prefix-arg
)))
235 (if (listp to-strings
)
236 (setq replacements to-strings
)
237 (while (/= (length to-strings
) 0)
238 (if (string-match " " to-strings
)
241 (list (substring to-strings
0
242 (string-match " " to-strings
))))
243 to-strings
(substring to-strings
244 (1+ (string-match " " to-strings
))))
245 (setq replacements
(append replacements
(list to-strings
))
247 (perform-replace regexp replacements t t nil n nil start end
)))
249 (defun replace-string (from-string to-string
&optional delimited start end
)
250 "Replace occurrences of FROM-STRING with TO-STRING.
251 Preserve case in each match if `case-replace' and `case-fold-search'
252 are non-nil and FROM-STRING has no uppercase letters.
253 \(Preserving case means that if the string matched is all caps, or capitalized,
254 then its replacement is upcased or capitalized.)
256 In Transient Mark mode, if the mark is active, operate on the contents
257 of the region. Otherwise, operate from point to the end of the buffer.
259 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
260 only matches surrounded by word boundaries.
261 Fourth and fifth arg START and END specify the region to operate on.
263 If `query-replace-interactive' is non-nil, the last incremental search
264 string is used as FROM-STRING--you don't have to specify it with the
267 This function is usually the wrong thing to use in a Lisp program.
268 What you probably want is a loop like this:
269 (while (search-forward FROM-STRING nil t)
270 (replace-match TO-STRING nil t))
271 which will run faster and will not set the mark or print anything.
272 \(You may need a more complex loop if FROM-STRING can match the null string
273 and TO-STRING is also null.)"
274 (interactive (query-replace-read-args "Replace string" nil
))
275 (perform-replace from-string to-string nil nil delimited nil nil start end
))
277 (defun replace-regexp (regexp to-string
&optional delimited start end
)
278 "Replace things after point matching REGEXP with TO-STRING.
279 Preserve case in each match if `case-replace' and `case-fold-search'
280 are non-nil and REGEXP has no uppercase letters.
282 In Transient Mark mode, if the mark is active, operate on the contents
283 of the region. Otherwise, operate from point to the end of the buffer.
285 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
286 only matches surrounded by word boundaries.
287 Fourth and fifth arg START and END specify the region to operate on.
289 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
290 and `\\=\\N' (where N is a digit) stands for
291 whatever what matched the Nth `\\(...\\)' in REGEXP.
293 If `query-replace-interactive' is non-nil, the last incremental search
294 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
296 This function is usually the wrong thing to use in a Lisp program.
297 What you probably want is a loop like this:
298 (while (re-search-forward REGEXP nil t)
299 (replace-match TO-STRING nil nil))
300 which will run faster and will not set the mark or print anything."
301 (interactive (query-replace-read-args "Replace regexp" t
))
302 (perform-replace regexp to-string nil t delimited nil nil start end
))
305 (defvar regexp-history nil
306 "History list for some commands that read regular expressions.")
309 (defalias 'delete-non-matching-lines
'keep-lines
)
310 (defalias 'delete-matching-lines
'flush-lines
)
311 (defalias 'count-matches
'how-many
)
314 (defun keep-lines-read-args (prompt)
315 "Read arguments for `keep-lines' and friends.
316 Prompt for a regexp with PROMPT.
317 Value is a list, (REGEXP)."
318 (list (read-from-minibuffer prompt nil nil nil
319 'regexp-history nil t
)))
321 (defun keep-lines (regexp &optional rstart rend
)
322 "Delete all lines except those containing matches for REGEXP.
323 A match split across lines preserves all the lines it lies in.
324 Applies to all lines after point.
326 If REGEXP contains upper case characters (excluding those preceded by `\\'),
327 the matching is case-sensitive.
329 Second and third arg RSTART and REND specify the region to operate on.
331 Interactively, in Transient Mark mode when the mark is active, operate
332 on the contents of the region. Otherwise, operate from point to the
336 (keep-lines-read-args "Keep lines (containing match for regexp): "))
338 (goto-char (min rstart rend
))
339 (if (and transient-mark-mode mark-active
)
340 (setq rstart
(region-beginning)
341 rend
(copy-marker (region-end)))
343 rend
(point-max-marker)))
346 (or (bolp) (forward-line 1))
347 (let ((start (point))
348 (case-fold-search (and case-fold-search
349 (isearch-no-upper-case-p regexp t
))))
350 (while (< (point) rend
)
351 ;; Start is first char not preserved by previous match.
352 (if (not (re-search-forward regexp rend
'move
))
353 (delete-region start rend
)
354 (let ((end (save-excursion (goto-char (match-beginning 0))
357 ;; Now end is first char preserved by the new match.
359 (delete-region start end
))))
361 (setq start
(save-excursion (forward-line 1) (point)))
362 ;; If the match was empty, avoid matching again at same place.
363 (and (< (point) rend
)
364 (= (match-beginning 0) (match-end 0))
365 (forward-char 1))))))
368 (defun flush-lines (regexp &optional rstart rend
)
369 "Delete lines containing matches for REGEXP.
370 If a match is split across lines, all the lines it lies in are deleted.
371 Applies to 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
383 (keep-lines-read-args "Flush lines (containing match for regexp): "))
385 (goto-char (min rstart rend
))
386 (if (and transient-mark-mode mark-active
)
387 (setq rstart
(region-beginning)
388 rend
(copy-marker (region-end)))
390 rend
(point-max-marker)))
392 (let ((case-fold-search (and case-fold-search
393 (isearch-no-upper-case-p regexp t
))))
395 (while (and (< (point) rend
)
396 (re-search-forward regexp rend t
))
397 (delete-region (save-excursion (goto-char (match-beginning 0))
400 (progn (forward-line 1) (point)))))))
403 (defun how-many (regexp &optional rstart rend
)
404 "Print number of matches for REGEXP following point.
406 If REGEXP contains upper case characters (excluding those preceded by `\\'),
407 the matching is case-sensitive.
409 Second and third arg RSTART and REND specify the region to operate on.
411 Interactively, in Transient Mark mode when the mark is active, operate
412 on the contents of the region. Otherwise, operate from point to the
416 (keep-lines-read-args "How many matches for (regexp): "))
419 (goto-char (min rstart rend
))
420 (if (and transient-mark-mode mark-active
)
421 (setq rstart
(region-beginning)
422 rend
(copy-marker (region-end)))
424 rend
(point-max-marker)))
428 (case-fold-search (and case-fold-search
429 (isearch-no-upper-case-p regexp t
))))
430 (while (and (< (point) rend
)
431 (progn (setq opoint
(point))
432 (re-search-forward regexp rend t
)))
433 (if (= opoint
(point))
435 (setq count
(1+ count
))))
436 (message "%d occurrences" count
))))
439 (defvar occur-mode-map
440 (let ((map (make-sparse-keymap)))
441 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
442 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
443 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
444 (define-key map
"\o" 'occur-mode-goto-occurrence-other-window
)
445 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
446 (define-key map
"\M-n" 'occur-next
)
447 (define-key map
"\M-p" 'occur-prev
)
448 (define-key map
"g" 'revert-buffer
)
450 "Keymap for `occur-mode'.")
452 (defvar occur-revert-properties nil
)
454 (put 'occur-mode
'mode-class
'special
)
456 "Major mode for output from \\[occur].
457 \\<occur-mode-map>Move point to one of the items in this buffer, then use
458 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
459 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
462 (kill-all-local-variables)
463 (use-local-map occur-mode-map
)
464 (setq major-mode
'occur-mode
)
465 (setq mode-name
"Occur")
466 (make-local-variable 'revert-buffer-function
)
467 (set (make-local-variable 'font-lock-defaults
)
469 (font-lock-fontify-region-function . occur-fontify-region-function
)
470 (font-lock-unfontify-region-function . occur-unfontify-region-function
)))
471 (setq revert-buffer-function
'occur-revert-function
)
472 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
473 (make-local-variable 'occur-revert-properties
)
474 (run-hooks 'occur-mode-hook
))
476 (defun occur-revert-function (ignore1 ignore2
)
477 "Handle `revert-buffer' for *Occur* buffers."
478 (apply 'occur-1 occur-revert-properties
))
480 (defun occur-mode-mouse-goto (event)
481 "In Occur mode, go to the occurrence whose line you click on."
486 (set-buffer (window-buffer (posn-window (event-end event
))))
488 (goto-char (posn-point (event-end event
)))
489 (let ((props (occur-mode-find-occurrence)))
490 (setq buffer
(car props
))
491 (setq pos
(cdr props
)))))
492 (pop-to-buffer buffer
)
493 (goto-char (marker-position pos
))))
495 (defun occur-mode-find-occurrence ()
496 (let ((props (get-text-property (point) 'occur-target
)))
498 (error "No occurrence on this line"))
499 (unless (buffer-live-p (car props
))
500 (error "Buffer in which occurrence was found is deleted"))
503 (defun occur-mode-goto-occurrence ()
504 "Go to the occurrence the current line describes."
506 (let ((target (occur-mode-find-occurrence)))
507 (pop-to-buffer (car target
))
508 (goto-char (marker-position (cdr target
)))))
510 (defun occur-mode-goto-occurrence-other-window ()
511 "Go to the occurrence the current line describes, in another window."
513 (let ((target (occur-mode-find-occurrence)))
514 (switch-to-buffer-other-window (car target
))
515 (goto-char (marker-position (cdr target
)))))
517 (defun occur-mode-display-occurrence ()
518 "Display in another window the occurrence the current line describes."
520 (let ((target (occur-mode-find-occurrence))
521 same-window-buffer-names
524 (setq window
(display-buffer (car target
)))
525 ;; This is the way to set point in the proper window.
526 (save-selected-window
527 (select-window window
)
528 (goto-char (marker-position (cdr target
))))))
530 (defun occur-next (&optional n
)
531 "Move to the Nth (default 1) next match in the *Occur* buffer."
533 (if (not n
) (setq n
1))
536 (if (get-text-property (point) 'occur-point
)
538 (setq r
(next-single-property-change (point) 'occur-point
))
541 (error "No more matches"))
544 (defun occur-prev (&optional n
)
545 "Move to the Nth (default 1) previous match in the *Occur* buffer."
547 (if (not n
) (setq n
1))
551 (setq r
(get-text-property (point) 'occur-point
))
552 (if r
(forward-char -
1))
554 (setq r
(previous-single-property-change (point) 'occur-point
))
557 (error "No earlier matches"))
561 (defcustom list-matching-lines-default-context-lines
0
562 "*Default number of context lines included around `list-matching-lines' matches.
563 A negative number means to include that many lines before the match.
564 A positive number means to include that many lines both before and after."
568 (defalias 'list-matching-lines
'occur
)
570 (defcustom list-matching-lines-face
'bold
571 "*Face used by \\[list-matching-lines] to show the text that matches.
572 If the value is nil, don't highlight the matching portions specially."
576 (defcustom list-matching-lines-buffer-name-face
'underline
577 "*Face used by \\[list-matching-lines] to show the names of buffers.
578 If the value is nil, don't highlight the buffer names specially."
582 (defun occur-accumulate-lines (count &optional no-props
)
584 (let ((forwardp (> count
0))
586 (while (not (or (zerop count
)
594 (funcall (if no-props
595 #'buffer-substring-no-properties
597 (line-beginning-position)
600 (forward-line (if forwardp
1 -
1)))
603 (defun occur-read-primary-args ()
604 (list (let* ((default (car regexp-history
))
606 (read-from-minibuffer
608 (format "List lines matching regexp (default `%s'): "
610 "List lines matching regexp: ")
620 (defun occur (regexp &optional nlines
)
621 "Show all lines in the current buffer containing a match for REGEXP.
623 If a match spreads across multiple lines, all those lines are shown.
625 Each line is displayed with NLINES lines before and after, or -NLINES
626 before if NLINES is negative.
627 NLINES defaults to `list-matching-lines-default-context-lines'.
628 Interactively it is the prefix arg.
630 The lines are shown in a buffer named `*Occur*'.
631 It serves as a menu to find any of the occurrences in this buffer.
632 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
634 If REGEXP contains upper case characters (excluding those preceded by `\\'),
635 the matching is case-sensitive."
636 (interactive (occur-read-primary-args))
637 (occur-1 regexp nlines
(list (current-buffer))))
639 (defun multi-occur (bufs regexp
&optional nlines
)
640 "Show all lines in buffers BUFS containing a match for REGEXP.
641 This function acts on multiple buffers; otherwise, it is exactly like
645 (let ((bufs (list (read-buffer "First buffer to search: "
646 (current-buffer) t
)))
648 (while (not (string-equal
649 (setq buf
(read-buffer "Next buffer to search (RET to end): "
653 (nreverse (mapcar #'get-buffer bufs
)))
654 (occur-read-primary-args)))
655 (occur-1 regexp nlines bufs
))
657 (defun multi-occur-by-filename-regexp (bufregexp regexp
&optional nlines
)
658 "Show all lines matching REGEXP in buffers named by BUFREGEXP.
659 See also `multi-occur'."
662 (let* ((default (car regexp-history
))
664 (read-from-minibuffer
665 "List lines in buffers whose filename matches regexp: "
673 (occur-read-primary-args)))
675 (occur-1 regexp nlines
677 (mapcar (lambda (buf)
678 (when (and (buffer-file-name buf
)
679 (string-match bufregexp
680 (buffer-file-name buf
)))
684 (defun occur-1 (regexp nlines bufs
)
685 (let ((occur-buf (get-buffer-create "*Occur*")))
686 (with-current-buffer occur-buf
687 (setq buffer-read-only nil
)
690 (let ((count (occur-engine
691 regexp bufs occur-buf
692 (or nlines list-matching-lines-default-context-lines
)
693 (and case-fold-search
694 (isearch-no-upper-case-p regexp t
))
696 (message "Searched %d buffers; %s matches for `%s'" (length bufs
)
702 (display-buffer occur-buf
)
703 (kill-buffer occur-buf
)))
704 (setq occur-revert-properties
(list regexp nlines bufs
)
705 buffer-read-only t
))))
707 ;; Most of these are macros becuase if we used `flet', it wouldn't
708 ;; create a closure, so things would blow up at run time. Ugh. :(
709 (macrolet ((insert-get-point (obj)
716 (concat " :" line
"\n"))
718 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
719 title-face prefix-face match-face keep-props
)
720 (with-current-buffer out-buf
721 (setq buffer-read-only nil
)
722 (let ((globalcount 0))
723 ;; Map over all the buffers
724 (dolist (buf buffers
)
725 (when (buffer-live-p buf
)
726 (let ((c 0) ;; count of matched lines
735 (headerpt (with-current-buffer out-buf
(point))))
739 (goto-char (point-min)) ;; begin searching in the buffer
741 (setq origpt
(point))
742 (when (setq endpt
(re-search-forward regexp nil t
))
743 (incf c
) ;; increment match count
745 (setq matchbeg
(match-beginning 0)
746 matchend
(match-end 0))
747 (setq begpt
(save-excursion
749 (line-beginning-position)))
750 (incf l
(1- (count-lines origpt endpt
)))
751 (setq marker
(make-marker))
752 (set-marker marker matchbeg
)
753 (setq curstring
(buffer-substring begpt
754 (line-end-position)))
755 ;; Depropertize the string, and maybe
756 ;; highlight the matches
757 (let ((len (length curstring
))
760 (set-text-properties 0 len nil curstring
))
761 (while (and (< start len
)
762 (string-match regexp curstring start
))
763 (add-text-properties (match-beginning 0)
768 `(face ,match-face
)))
770 (setq start
(match-end 0))))
771 ;; Generate the string to insert for this match
774 (apply #'propertize
(format "%6d:" l
)
783 ;; The simple display style
785 ;; The complex multi-line display
786 ;; style. Generate a list of lines,
787 ;; concatenate them all together.
790 (add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ nlines
)) t
))))
792 (add-prefix (cdr (occur-accumulate-lines (1+ nlines
) t
))))))))
793 ;; Actually insert the match display data
794 (with-current-buffer out-buf
796 (end (insert-get-point data
)))
798 (insert-get-point "-------\n"))
801 `(occur-target ,(cons buf marker
)
802 mouse-face highlight help-echo
803 "mouse-2: go to this occurrence")))))
806 ;; On to the next match...
808 (when (not (zerop c
)) ;; is the count zero?
809 (with-current-buffer out-buf
812 (end (insert-get-point
813 (format "%d lines matching \"%s\" in buffer: %s\n"
814 c regexp
(buffer-name buf
)))))
815 (add-text-properties beg end
819 `(occur-title ,buf
))))
820 (goto-char (point-min)))))))
821 ;; Return the number of matches
824 (defun occur-fontify-on-property (prop face beg end
)
825 (let ((prop-beg (or (and (get-text-property (point) prop
) (point))
826 (next-single-property-change (point) prop nil end
))))
827 (when (and prop-beg
(not (= prop-beg end
)))
828 (let ((prop-end (next-single-property-change beg prop nil end
)))
829 (when (and prop-end
(not (= prop-end end
)))
830 (put-text-property prop-beg prop-end
'face face
)
833 (defun occur-fontify-region-function (beg end
&optional verbose
)
834 (when verbose
(message "Fontifying..."))
835 (let ((inhibit-read-only t
))
837 (dolist (e `((occur-title .
,list-matching-lines-buffer-name-face
)
838 (occur-match .
,list-matching-lines-face
)))
839 ; (occur-prefix . ,list-matching-lines-prefix-face)))
841 (let ((change-end nil
))
842 (while (setq change-end
(occur-fontify-on-property (car e
)
846 (goto-char change-end
))))))
847 (when verbose
(message "Fontifying...done")))
849 (defun occur-unfontify-region-function (beg end
)
850 (let ((inhibit-read-only t
))
851 (remove-text-properties beg end
'(face nil
))))
854 ;; It would be nice to use \\[...], but there is no reasonable way
855 ;; to make that display both SPC and Y.
856 (defconst query-replace-help
857 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
858 RET or `q' to exit, Period to replace one match and exit,
859 Comma to replace but not move point immediately,
860 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
861 C-w to delete match and recursive edit,
862 C-l to clear the screen, redisplay, and offer same replacement again,
863 ! to replace all remaining matches with no more questions,
864 ^ to move point back to previous match,
865 E to edit the replacement string"
866 "Help message while in `query-replace'.")
868 (defvar query-replace-map
(make-sparse-keymap)
869 "Keymap that defines the responses to questions in `query-replace'.
870 The \"bindings\" in this map are not commands; they are answers.
871 The valid answers include `act', `skip', `act-and-show',
872 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
873 `automatic', `backup', `exit-prefix', and `help'.")
875 (define-key query-replace-map
" " 'act
)
876 (define-key query-replace-map
"\d" 'skip
)
877 (define-key query-replace-map
[delete] 'skip)
878 (define-key query-replace-map [backspace] 'skip)
879 (define-key query-replace-map "y" 'act)
880 (define-key query-replace-map "n" 'skip)
881 (define-key query-replace-map "Y" 'act)
882 (define-key query-replace-map "N" 'skip)
883 (define-key query-replace-map "e" 'edit-replacement)
884 (define-key query-replace-map "E" 'edit-replacement)
885 (define-key query-replace-map "," 'act-and-show)
886 (define-key query-replace-map "q" 'exit)
887 (define-key query-replace-map "\r" 'exit)
888 (define-key query-replace-map [return] 'exit)
889 (define-key query-replace-map "." 'act-and-exit)
890 (define-key query-replace-map "\C-r" 'edit)
891 (define-key query-replace-map "\C-w" 'delete-and-edit)
892 (define-key query-replace-map "\C-l" 'recenter)
893 (define-key query-replace-map "!" 'automatic)
894 (define-key query-replace-map "^" 'backup)
895 (define-key query-replace-map "\C-h" 'help)
896 (define-key query-replace-map [f1] 'help)
897 (define-key query-replace-map [help] 'help)
898 (define-key query-replace-map "?" 'help)
899 (define-key query-replace-map "\C-g" 'quit)
900 (define-key query-replace-map "\C-]" 'quit)
901 (define-key query-replace-map "\e" 'exit-prefix)
902 (define-key query-replace-map [escape] 'exit-prefix)
904 (defun replace-match-string-symbols (n)
905 "Process a list (and any sub-lists), expanding certain symbols.
907 N (match-string N) (where N is a string of digits)
908 #N (string-to-number (match-string N))
910 #& (string-to-number (match-string 0))
912 Note that these symbols must be preceeded by a backslash in order to
917 (replace-match-string-symbols (car n))) ;Process sub-list
919 (let ((name (symbol-name (car n))))
921 ((string-match "^[0-9]+$" name)
922 (setcar n (list 'match-string (string-to-number name))))
923 ((string-match "^#[0-9]+$" name)
924 (setcar n (list 'string-to-number
926 (string-to-number (substring name 1))))))
928 (setcar n '(match-string 0)))
930 (setcar n '(string-to-number (match-string 0))))))))
933 (defun replace-eval-replacement (expression replace-count)
934 (let ((replacement (eval expression)))
935 (if (stringp replacement)
937 (prin1-to-string replacement t))))
939 (defun replace-loop-through-replacements (data replace-count)
940 ;; DATA is a vector contaning the following values:
941 ;; 0 next-rotate-count
943 ;; 2 next-replacement
945 (if (= (aref data 0) replace-count)
947 (aset data 0 (+ replace-count (aref data 1)))
948 (let ((next (cdr (aref data 2))))
949 (aset data 2 (if (consp next) next (aref data 3))))))
952 (defun perform-replace (from-string replacements
953 query-flag regexp-flag delimited-flag
954 &optional repeat-count map start end)
955 "Subroutine of `query-replace'. Its complexity handles interactive queries.
956 Don't use this in your own program unless you want to query and set the mark
957 just as `query-replace' does. Instead, write a simple loop like this:
959 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
960 (replace-match \"foobar\" nil nil))
962 which will run faster and probably do exactly what you want. Please
963 see the documentation of `replace-match' to find out how to simulate
965 (or map (setq map query-replace-map))
966 (and query-flag minibuffer-auto-raise
967 (raise-frame (window-frame (minibuffer-window))))
968 (let ((nocasify (not (and case-fold-search case-replace
969 (string-equal from-string
970 (downcase from-string)))))
971 (case-fold-search (and case-fold-search
972 (string-equal from-string
973 (downcase from-string))))
974 (literal (not regexp-flag))
975 (search-function (if regexp-flag 're-search-forward 'search-forward))
976 (search-string from-string)
977 (real-match-data nil) ; the match data for the current match
978 (next-replacement nil)
984 ;; If non-nil, it is marker saying where in the buffer to stop.
987 ;; Data for the next match. If a cons, it has the same format as
988 ;; (match-data); otherwise it is t if a match is possible at point.
993 (substitute-command-keys
994 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
996 ;; If region is active, in Transient Mark mode, operate on region.
998 (setq limit (copy-marker (max start end)))
999 (goto-char (min start end))
1002 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1003 ;; containing a function and its first argument. The function is
1004 ;; called to generate each replacement like this:
1005 ;; (funcall (car replacements) (cdr replacements) replace-count)
1006 ;; It must return a string.
1008 ((stringp replacements)
1009 (setq next-replacement replacements
1011 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1012 (or repeat-count (setq repeat-count 1))
1013 (setq replacements (cons 'replace-loop-through-replacements
1014 (vector repeat-count repeat-count
1015 replacements replacements)))))
1018 (setq search-function 're-search-forward
1019 search-string (concat "\\b"
1020 (if regexp-flag from-string
1021 (regexp-quote from-string))
1026 ;; Loop finding occurrences that perhaps should be replaced.
1027 (while (and keep-going
1029 ;; Use the next match if it is already known;
1030 ;; otherwise, search for a match after moving forward
1031 ;; one char if progress is required.
1032 (setq real-match-data
1033 (if (consp match-again)
1034 (progn (goto-char (nth 1 match-again))
1036 (and (or match-again
1037 ;; MATCH-AGAIN non-nil means we
1038 ;; accept an adjacent match. If
1039 ;; we don't, move one char to the
1040 ;; right. This takes us a
1041 ;; character too far at the end,
1042 ;; but this is undone after the
1044 (progn (forward-char 1) (not (eobp))))
1045 (funcall search-function search-string limit t)
1046 ;; For speed, use only integers and
1047 ;; reuse the list used last time.
1048 (match-data t real-match-data)))))
1049 ;; Optionally ignore matches that have a read-only property.
1050 (unless (and query-replace-skip-read-only
1051 (text-property-not-all
1052 (match-beginning 0) (match-end 0)
1055 ;; Record whether the match is nonempty, to avoid an infinite loop
1056 ;; repeatedly matching the same empty string.
1057 (setq nonempty-match
1058 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1060 ;; If the match is empty, record that the next one can't be
1063 ;; Otherwise, if matching a regular expression, do the next
1064 ;; match now, since the replacement for this match may
1065 ;; affect whether the next match is adjacent to this one.
1066 ;; If that match is empty, don't use it.
1069 (or (not regexp-flag)
1070 (and (looking-at search-string)
1071 (let ((match (match-data)))
1072 (and (/= (nth 0 match) (nth 1 match))
1075 ;; Calculate the replacement string, if necessary.
1077 (set-match-data real-match-data)
1078 (setq next-replacement
1079 (funcall (car replacements) (cdr replacements)
1081 (if (not query-flag)
1082 (let ((inhibit-read-only query-replace-skip-read-only))
1083 (set-match-data real-match-data)
1084 (replace-match next-replacement nocasify literal)
1085 (setq replace-count (1+ replace-count)))
1087 (let (done replaced key def)
1088 ;; Loop reading commands until one of them sets done,
1089 ;; which means it has finished handling this occurrence.
1091 (set-match-data real-match-data)
1092 (replace-highlight (match-beginning 0) (match-end 0))
1093 ;; Bind message-log-max so we don't fill up the message log
1094 ;; with a bunch of identical messages.
1095 (let ((message-log-max nil))
1096 (message message from-string next-replacement))
1097 (setq key (read-event))
1098 ;; Necessary in case something happens during read-event
1099 ;; that clobbers the match data.
1100 (set-match-data real-match-data)
1101 (setq key (vector key))
1102 (setq def (lookup-key map key))
1103 ;; Restore the match data while we process the command.
1104 (cond ((eq def 'help)
1105 (with-output-to-temp-buffer "*Help*"
1107 (concat "Query replacing "
1108 (if regexp-flag "regexp " "")
1109 from-string " with "
1110 next-replacement ".\n\n"
1111 (substitute-command-keys
1112 query-replace-help)))
1113 (with-current-buffer standard-output
1116 (setq keep-going nil)
1120 (let ((elt (car stack)))
1121 (goto-char (car elt))
1122 (setq replaced (eq t (cdr elt)))
1124 (set-match-data (cdr elt)))
1125 (setq stack (cdr stack)))
1126 (message "No previous match")
1127 (ding 'no-terminate)
1132 (replace-match next-replacement nocasify literal)
1133 (setq replace-count (1+ replace-count))))
1134 (setq done t replaced t))
1135 ((eq def 'act-and-exit)
1138 (replace-match next-replacement nocasify literal)
1139 (setq replace-count (1+ replace-count))))
1140 (setq keep-going nil)
1141 (setq done t replaced t))
1142 ((eq def 'act-and-show)
1145 (replace-match next-replacement nocasify literal)
1146 (setq replace-count (1+ replace-count))
1147 (setq replaced t))))
1148 ((eq def 'automatic)
1151 (replace-match next-replacement nocasify literal)
1152 (setq replace-count (1+ replace-count))))
1153 (setq done t query-flag nil replaced t))
1159 (let ((opos (point-marker)))
1160 (goto-char (match-beginning 0))
1162 (funcall search-function search-string limit t)
1163 (setq real-match-data (match-data)))
1165 (save-window-excursion
1168 (set-match-data real-match-data)
1169 ;; Before we make the replacement,
1170 ;; decide whether the search string
1171 ;; can match again just after this match.
1172 (if (and regexp-flag nonempty-match)
1173 (setq match-again (and (looking-at search-string)
1176 ;; Edit replacement.
1177 ((eq def 'edit-replacement)
1178 (setq next-replacement
1179 (read-input "Edit replacement string: "
1182 (replace-match next-replacement nocasify literal))
1185 ((eq def 'delete-and-edit)
1186 (delete-region (match-beginning 0) (match-end 0))
1189 (save-excursion (recursive-edit))))
1191 ;; Note: we do not need to treat `exit-prefix'
1192 ;; specially here, since we reread
1193 ;; any unrecognized character.
1195 (setq this-command 'mode-exited)
1196 (setq keep-going nil)
1197 (setq unread-command-events
1198 (append (listify-key-sequence key)
1199 unread-command-events))
1201 ;; Record previous position for ^ when we move on.
1202 ;; Change markers to numbers in the match data
1203 ;; since lots of markers slow down editing.
1206 (or replaced (match-data t)))
1209 ;; The code preventing adjacent regexp matches in the condition
1210 ;; of the while-loop above will haven taken us one character
1211 ;; beyond the last replacement. Undo that.
1212 (when (and regexp-flag (not match-again) (> replace-count 0))
1215 (replace-dehighlight))
1216 (or unread-command-events
1217 (message "Replaced %d occurrence%s"
1219 (if (= replace-count 1) "" "s")))
1220 (and keep-going stack)))
1222 (defcustom query-replace-highlight t
1223 "*Non-nil means to highlight words during query replacement."
1227 (defvar replace-overlay nil)
1229 (defun replace-dehighlight ()
1230 (and replace-overlay
1232 (delete-overlay replace-overlay)
1233 (setq replace-overlay nil))))
1235 (defun replace-highlight (start end)
1236 (and query-replace-highlight
1240 (setq replace-overlay (make-overlay start end))
1241 (overlay-put replace-overlay 'face
1242 (if (facep 'query-replace)
1243 'query-replace 'region))))
1244 (move-overlay replace-overlay start end (current-buffer)))))
1246 ;;; replace.el ends here