1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985, 86, 87, 92, 94, 96, 1997, 2000, 2001, 2002,
4 ;; 2003, 2004 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 (defcustom query-replace-interactive nil
40 "Non-nil means `query-replace' uses the last search string.
41 That becomes the \"string to replace\"."
45 (defcustom query-replace-from-history-variable
'query-replace-history
46 "History list to use for the FROM argument of `query-replace' commands.
47 The value of this variable should be a symbol; that symbol
48 is used as a variable to hold a history list for the strings
49 or patterns to be replaced."
54 (defcustom query-replace-to-history-variable
'query-replace-history
55 "History list to use for the TO argument of `query-replace' commands.
56 The value of this variable should be a symbol; that symbol
57 is used as a variable to hold a history list for replacement
63 (defcustom query-replace-skip-read-only nil
64 "*Non-nil means `query-replace' and friends ignore read-only matches."
69 (defun query-replace-read-args (string regexp-flag
&optional noerror
)
71 (barf-if-buffer-read-only))
73 (if query-replace-interactive
74 (setq from
(car (if regexp-flag regexp-search-ring search-ring
)))
75 ;; The save-excursion here is in case the user marks and copies
76 ;; a region in order to specify the minibuffer input.
77 ;; That should not clobber the region for the query-replace itself.
79 (setq from
(read-from-minibuffer (format "%s: " string
)
81 query-replace-from-history-variable
83 ;; Warn if user types \n or \t, but don't reject the input.
85 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
86 (let ((match (match-string 3 from
)))
88 ((string= match
"\\n")
89 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
90 ((string= match
"\\t")
91 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
95 (setq to
(read-from-minibuffer (format "%s %s with: " string from
)
97 query-replace-to-history-variable from t
)))
98 (list from to current-prefix-arg
)))
100 (defun query-replace (from-string to-string
&optional delimited start end
)
101 "Replace some occurrences of FROM-STRING with TO-STRING.
102 As each match is found, the user must type a character saying
103 what to do with it. For directions, type \\[help-command] at that time.
105 In Transient Mark mode, if the mark is active, operate on the contents
106 of the region. Otherwise, operate from point to the end of the buffer.
108 If `query-replace-interactive' is non-nil, the last incremental search
109 string is used as FROM-STRING--you don't have to specify it with the
112 Matching is independent of case if `case-fold-search' is non-nil and
113 FROM-STRING has no uppercase letters. Replacement transfers the case
114 pattern of the old text to the new text, if `case-replace' and
115 `case-fold-search' are non-nil and FROM-STRING has no uppercase
116 letters. \(Transferring the case pattern means that if the old text
117 matched is all caps, or capitalized, then its replacement is upcased
120 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
121 only matches surrounded by word boundaries.
122 Fourth and fifth arg START and END specify the region to operate on.
124 To customize possible responses, change the \"bindings\" in `query-replace-map'."
125 (interactive (let ((common
126 (query-replace-read-args "Query replace" nil
)))
127 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
128 ;; These are done separately here
129 ;; so that command-history will record these expressions
130 ;; rather than the values they had this time.
131 (if (and transient-mark-mode mark-active
)
133 (if (and transient-mark-mode mark-active
)
135 (perform-replace from-string to-string t nil delimited nil nil start end
))
137 (define-key esc-map
"%" 'query-replace
)
139 (defun query-replace-regexp (regexp to-string
&optional delimited start end
)
140 "Replace some things after point matching REGEXP with TO-STRING.
141 As each match is found, the user must type a character saying
142 what to do with it. For directions, type \\[help-command] at that time.
144 In Transient Mark mode, if the mark is active, operate on the contents
145 of the region. Otherwise, operate from point to the end of the buffer.
147 If `query-replace-interactive' is non-nil, the last incremental search
148 regexp is used as REGEXP--you don't have to specify it with the
151 Matching is independent of case if `case-fold-search' is non-nil and
152 REGEXP has no uppercase letters. Replacement transfers the case
153 pattern of the old text to the new text, if `case-replace' and
154 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
155 \(Transferring the case pattern means that if the old text matched is
156 all caps, or capitalized, then its replacement is upcased or
159 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
160 only matches surrounded by word boundaries.
161 Fourth and fifth arg START and END specify the region to operate on.
163 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
164 and `\\=\\N' (where N is a digit) stands for
165 whatever what matched the Nth `\\(...\\)' in REGEXP.
167 When this function is called interactively, the replacement text
168 can also contain `\\,' followed by a Lisp expression. The escaped
169 shorthands for `query-replace-regexp-eval' are also valid
170 here: within the Lisp expression, you can use `\\&' for the whole
171 match string, `\\N' for partial matches, `\\#&' and `\\#N' for
172 the respective numeric values, and `\\#' for `replace-count'.
174 If your Lisp expression is an identifier and the next
175 letter in the replacement string would be interpreted as part of it,
176 you can wrap it with an expression like `\\,(or \\#)'. Incidentally,
177 for this particular case you may also enter `\\#' in the replacement
180 When you use `\\,' or `\\#' in the replacement, TO-STRING actually
181 becomes a list with expanded shorthands.
182 Use \\[repeat-complex-command] after this command to see details."
185 (query-replace-read-args "Query replace regexp" t
)))
188 (if (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]"
190 (let ((to-string (nth 1 common
)) pos to-expr char prompt
)
192 "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]"
194 (setq pos
(match-end 0))
195 (push (substring to-string
0 (- pos
2)) to-expr
)
196 (setq char
(aref to-string
(1- pos
))
197 to-string
(substring to-string pos
))
199 (push '(number-to-string replace-count
) to-expr
))
201 (setq pos
(read-from-string to-string
))
202 (push `(replace-quote ,(car pos
)) to-expr
)
203 (setq to-string
(substring to-string
(cdr pos
))))))
204 (setq to-expr
(nreverse (delete "" (cons to-string to-expr
))))
205 (replace-match-string-symbols to-expr
)
206 (cons 'replace-eval-replacement
207 (if (> (length to-expr
) 1)
208 (cons 'concat to-expr
)
212 ;; These are done separately here
213 ;; so that command-history will record these expressions
214 ;; rather than the values they had this time.
215 (if (and transient-mark-mode mark-active
)
217 (if (and transient-mark-mode mark-active
)
219 (perform-replace regexp to-string t t delimited nil nil start end
))
221 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
223 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
224 "Replace some things after point matching REGEXP with the result of TO-EXPR.
225 As each match is found, the user must type a character saying
226 what to do with it. For directions, type \\[help-command] at that time.
228 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
229 reference `replace-count' to get the number of replacements already made.
230 If the result of TO-EXPR is not a string, it is converted to one using
231 `prin1-to-string' with the NOESCAPE argument (which see).
233 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
234 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
235 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
236 Use `\\#&' or `\\#N' if you want a number instead of a string.
237 In interactive use, `\\#' in itself stands for `replace-count'.
239 In Transient Mark mode, if the mark is active, operate on the contents
240 of the region. Otherwise, operate from point to the end of the buffer.
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
246 Preserves case in each replacement if `case-replace' and `case-fold-search'
247 are non-nil and REGEXP has no uppercase letters.
249 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
250 only matches that are surrounded by word boundaries.
251 Fourth and fifth arg START and END specify the region to operate on."
254 (if query-replace-interactive
255 (setq from
(car regexp-search-ring
))
256 (setq from
(read-from-minibuffer "Query replace regexp: "
258 query-replace-from-history-variable
260 (setq to
(list (read-from-minibuffer
261 (format "Query replace regexp %s with eval: " from
)
262 nil nil t query-replace-to-history-variable from t
)))
263 ;; We make TO a list because replace-match-string-symbols requires one,
264 ;; and the user might enter a single token.
265 (replace-match-string-symbols to
)
266 (list from
(car to
) current-prefix-arg
267 (if (and transient-mark-mode mark-active
)
269 (if (and transient-mark-mode mark-active
)
271 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
272 t
'literal delimited nil nil start end
))
274 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
275 "Replace some matches for REGEXP with various strings, in rotation.
276 The second argument TO-STRINGS contains the replacement strings,
277 separated by spaces. Third arg DELIMITED (prefix arg if interactive),
278 if non-nil, means replace only matches surrounded by word boundaries.
279 This command works like `query-replace-regexp' except that each
280 successive replacement uses the next successive replacement string,
281 wrapping around from the last such string to the first.
283 In Transient Mark mode, if the mark is active, operate on the contents
284 of the region. Otherwise, operate from point to the end of the buffer.
286 Non-interactively, TO-STRINGS may be a list of replacement strings.
288 If `query-replace-interactive' is non-nil, the last incremental search
289 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
291 A prefix argument N says to use each replacement string N times
292 before rotating to the next.
293 Fourth and fifth arg START and END specify the region to operate on."
296 (setq from
(if query-replace-interactive
297 (car regexp-search-ring
)
298 (read-from-minibuffer "Map query replace (regexp): "
300 'query-replace-history nil t
)))
301 (setq to
(read-from-minibuffer
302 (format "Query replace %s with (space-separated strings): "
305 'query-replace-history from t
))
307 (and current-prefix-arg
308 (prefix-numeric-value current-prefix-arg
))
309 (if (and transient-mark-mode mark-active
)
311 (if (and transient-mark-mode mark-active
)
314 (if (listp to-strings
)
315 (setq replacements to-strings
)
316 (while (/= (length to-strings
) 0)
317 (if (string-match " " to-strings
)
320 (list (substring to-strings
0
321 (string-match " " to-strings
))))
322 to-strings
(substring to-strings
323 (1+ (string-match " " to-strings
))))
324 (setq replacements
(append replacements
(list to-strings
))
326 (perform-replace regexp replacements t t nil n nil start end
)))
328 (defun replace-string (from-string to-string
&optional delimited start end
)
329 "Replace occurrences of FROM-STRING with TO-STRING.
330 Preserve case in each match if `case-replace' and `case-fold-search'
331 are non-nil and FROM-STRING has no uppercase letters.
332 \(Preserving case means that if the string matched is all caps, or capitalized,
333 then its replacement is upcased or capitalized.)
335 In Transient Mark mode, if the mark is active, operate on the contents
336 of the region. Otherwise, operate from point to the end of the buffer.
338 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
339 only matches surrounded by word boundaries.
340 Fourth and fifth arg START and END specify the region to operate on.
342 If `query-replace-interactive' is non-nil, the last incremental search
343 string is used as FROM-STRING--you don't have to specify it with the
346 This function is usually the wrong thing to use in a Lisp program.
347 What you probably want is a loop like this:
348 (while (search-forward FROM-STRING nil t)
349 (replace-match TO-STRING nil t))
350 which will run faster and will not set the mark or print anything.
351 \(You may need a more complex loop if FROM-STRING can match the null string
352 and TO-STRING is also null.)"
355 (query-replace-read-args "Replace string" nil
)))
356 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
357 (if (and transient-mark-mode mark-active
)
359 (if (and transient-mark-mode mark-active
)
361 (perform-replace from-string to-string nil nil delimited nil nil start end
))
363 (defun replace-regexp (regexp to-string
&optional delimited start end
)
364 "Replace things after point matching REGEXP with TO-STRING.
365 Preserve case in each match if `case-replace' and `case-fold-search'
366 are non-nil and REGEXP has no uppercase letters.
368 In Transient Mark mode, if the mark is active, operate on the contents
369 of the region. Otherwise, operate from point to the end of the buffer.
371 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
372 only matches surrounded by word boundaries.
373 Fourth and fifth arg START and END specify the region to operate on.
375 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
376 and `\\=\\N' (where N is a digit) stands for
377 whatever what matched the Nth `\\(...\\)' in REGEXP.
379 If `query-replace-interactive' is non-nil, the last incremental search
380 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
382 This function is usually the wrong thing to use in a Lisp program.
383 What you probably want is a loop like this:
384 (while (re-search-forward REGEXP nil t)
385 (replace-match TO-STRING nil nil))
386 which will run faster and will not set the mark or print anything."
389 (query-replace-read-args "Replace regexp" t
)))
390 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
391 (if (and transient-mark-mode mark-active
)
393 (if (and transient-mark-mode mark-active
)
395 (perform-replace regexp to-string nil t delimited nil nil start end
))
398 (defvar regexp-history nil
399 "History list for some commands that read regular expressions.")
402 (defalias 'delete-non-matching-lines
'keep-lines
)
403 (defalias 'delete-matching-lines
'flush-lines
)
404 (defalias 'count-matches
'how-many
)
407 (defun keep-lines-read-args (prompt)
408 "Read arguments for `keep-lines' and friends.
409 Prompt for a regexp with PROMPT.
410 Value is a list, (REGEXP)."
411 (list (read-from-minibuffer prompt nil nil nil
412 'regexp-history nil t
)))
414 (defun keep-lines (regexp &optional rstart rend
)
415 "Delete all lines except those containing matches for REGEXP.
416 A match split across lines preserves all the lines it lies in.
417 Applies to all lines after point.
419 If REGEXP contains upper case characters (excluding those preceded by `\\'),
420 the matching is case-sensitive.
422 Second and third arg RSTART and REND specify the region to operate on.
424 Interactively, in Transient Mark mode when the mark is active, operate
425 on the contents of the region. Otherwise, operate from point to the
430 (barf-if-buffer-read-only)
431 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
434 (goto-char (min rstart rend
))
435 (setq rend
(copy-marker (max rstart rend
))))
436 (if (and transient-mark-mode mark-active
)
437 (setq rstart
(region-beginning)
438 rend
(copy-marker (region-end)))
440 rend
(point-max-marker)))
443 (or (bolp) (forward-line 1))
444 (let ((start (point))
445 (case-fold-search (and case-fold-search
446 (isearch-no-upper-case-p regexp t
))))
447 (while (< (point) rend
)
448 ;; Start is first char not preserved by previous match.
449 (if (not (re-search-forward regexp rend
'move
))
450 (delete-region start rend
)
451 (let ((end (save-excursion (goto-char (match-beginning 0))
454 ;; Now end is first char preserved by the new match.
456 (delete-region start end
))))
458 (setq start
(save-excursion (forward-line 1) (point)))
459 ;; If the match was empty, avoid matching again at same place.
460 (and (< (point) rend
)
461 (= (match-beginning 0) (match-end 0))
462 (forward-char 1))))))
465 (defun flush-lines (regexp &optional rstart rend
)
466 "Delete lines containing matches for REGEXP.
467 If a match is split across lines, all the lines it lies in are deleted.
468 Applies to lines after point.
470 If REGEXP contains upper case characters (excluding those preceded by `\\'),
471 the matching is case-sensitive.
473 Second and third arg RSTART and REND specify the region to operate on.
475 Interactively, in Transient Mark mode when the mark is active, operate
476 on the contents of the region. Otherwise, operate from point to the
481 (barf-if-buffer-read-only)
482 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
485 (goto-char (min rstart rend
))
486 (setq rend
(copy-marker (max rstart rend
))))
487 (if (and transient-mark-mode mark-active
)
488 (setq rstart
(region-beginning)
489 rend
(copy-marker (region-end)))
491 rend
(point-max-marker)))
493 (let ((case-fold-search (and case-fold-search
494 (isearch-no-upper-case-p regexp t
))))
496 (while (and (< (point) rend
)
497 (re-search-forward regexp rend t
))
498 (delete-region (save-excursion (goto-char (match-beginning 0))
501 (progn (forward-line 1) (point)))))))
504 (defun how-many (regexp &optional rstart rend
)
505 "Print number of matches for REGEXP following point.
507 If REGEXP contains upper case characters (excluding those preceded by `\\'),
508 the matching is case-sensitive.
510 Second and third arg RSTART and REND specify the region to operate on.
512 Interactively, in Transient Mark mode when the mark is active, operate
513 on the contents of the region. Otherwise, operate from point to the
517 (keep-lines-read-args "How many matches for (regexp): "))
520 (goto-char (min rstart rend
))
521 (if (and transient-mark-mode mark-active
)
522 (setq rstart
(region-beginning)
523 rend
(copy-marker (region-end)))
525 rend
(point-max-marker)))
529 (case-fold-search (and case-fold-search
530 (isearch-no-upper-case-p regexp t
))))
531 (while (and (< (point) rend
)
532 (progn (setq opoint
(point))
533 (re-search-forward regexp rend t
)))
534 (if (= opoint
(point))
536 (setq count
(1+ count
))))
537 (message "%d occurrences" count
))))
540 (defvar occur-mode-map
541 (let ((map (make-sparse-keymap)))
542 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
543 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
544 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
545 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
546 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
547 (define-key map
"\M-n" 'occur-next
)
548 (define-key map
"\M-p" 'occur-prev
)
549 (define-key map
"r" 'occur-rename-buffer
)
550 (define-key map
"c" 'clone-buffer
)
551 (define-key map
"g" 'revert-buffer
)
552 (define-key map
"q" 'quit-window
)
553 (define-key map
"z" 'kill-this-buffer
)
555 "Keymap for `occur-mode'.")
557 (defvar occur-revert-arguments nil
558 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
559 See `occur-revert-function'.")
561 (defcustom occur-mode-hook
'(turn-on-font-lock)
562 "Hook run when entering Occur mode."
566 (defcustom occur-hook nil
567 "Hook run when `occur' is called."
571 (put 'occur-mode
'mode-class
'special
)
573 "Major mode for output from \\[occur].
574 \\<occur-mode-map>Move point to one of the items in this buffer, then use
575 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
576 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
580 (kill-all-local-variables)
581 (use-local-map occur-mode-map
)
582 (setq major-mode
'occur-mode
)
583 (setq mode-name
"Occur")
584 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
585 (make-local-variable 'occur-revert-arguments
)
586 (add-hook 'change-major-mode-hook
'font-lock-defontify nil t
)
587 (setq next-error-function
'occur-next-error
)
588 (run-hooks 'occur-mode-hook
))
590 (defun occur-revert-function (ignore1 ignore2
)
591 "Handle `revert-buffer' for Occur mode buffers."
592 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
594 (defun occur-mode-mouse-goto (event)
595 "In Occur mode, go to the occurrence whose line you click on."
599 (set-buffer (window-buffer (posn-window (event-end event
))))
601 (goto-char (posn-point (event-end event
)))
602 (setq pos
(occur-mode-find-occurrence))))
603 (pop-to-buffer (marker-buffer pos
))
606 (defun occur-mode-find-occurrence ()
607 (let ((pos (get-text-property (point) 'occur-target
)))
609 (error "No occurrence on this line"))
610 (unless (buffer-live-p (marker-buffer pos
))
611 (error "Buffer for this occurrence was killed"))
614 (defun occur-mode-goto-occurrence ()
615 "Go to the occurrence the current line describes."
617 (let ((pos (occur-mode-find-occurrence)))
618 (pop-to-buffer (marker-buffer pos
))
621 (defun occur-mode-goto-occurrence-other-window ()
622 "Go to the occurrence the current line describes, in another window."
624 (let ((pos (occur-mode-find-occurrence)))
625 (switch-to-buffer-other-window (marker-buffer pos
))
628 (defun occur-mode-display-occurrence ()
629 "Display in another window the occurrence the current line describes."
631 (let ((pos (occur-mode-find-occurrence))
633 ;; Bind these to ensure `display-buffer' puts it in another window.
634 same-window-buffer-names
636 (setq window
(display-buffer (marker-buffer pos
)))
637 ;; This is the way to set point in the proper window.
638 (save-selected-window
639 (select-window window
)
642 (defun occur-find-match (n search message
)
643 (if (not n
) (setq n
1))
646 (setq r
(funcall search
(point) 'occur-match
))
648 (get-text-property r
'occur-match
)
649 (setq r
(funcall search r
'occur-match
)))
655 (defun occur-next (&optional n
)
656 "Move to the Nth (default 1) next match in an Occur mode buffer."
658 (occur-find-match n
#'next-single-property-change
"No more matches"))
660 (defun occur-prev (&optional n
)
661 "Move to the Nth (default 1) previous match in an Occur mode buffer."
663 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
665 (defun occur-next-error (&optional argp reset
)
666 "Move to the Nth (default 1) next match in an Occur mode buffer.
667 Compatibility function for \\[next-error] invocations."
670 (occur-find-match 0 #'next-single-property-change
"No first match"))
672 (prefix-numeric-value argp
)
673 (if (> 0 (prefix-numeric-value argp
))
674 #'previous-single-property-change
675 #'next-single-property-change
)
677 (occur-mode-goto-occurrence))
680 (defcustom list-matching-lines-default-context-lines
0
681 "*Default number of context lines included around `list-matching-lines' matches.
682 A negative number means to include that many lines before the match.
683 A positive number means to include that many lines both before and after."
687 (defalias 'list-matching-lines
'occur
)
689 (defcustom list-matching-lines-face
'bold
690 "*Face used by \\[list-matching-lines] to show the text that matches.
691 If the value is nil, don't highlight the matching portions specially."
695 (defcustom list-matching-lines-buffer-name-face
'underline
696 "*Face used by \\[list-matching-lines] to show the names of buffers.
697 If the value is nil, don't highlight the buffer names specially."
701 (defun occur-accumulate-lines (count &optional no-props
)
703 (let ((forwardp (> count
0))
705 (while (not (or (zerop count
)
709 (setq count
(+ count
(if forwardp -
1 1)))
711 (funcall (if no-props
712 #'buffer-substring-no-properties
714 (line-beginning-position)
717 (forward-line (if forwardp
1 -
1)))
720 (defun occur-read-primary-args ()
721 (list (let* ((default (car regexp-history
))
723 (read-from-minibuffer
725 (format "List lines matching regexp (default `%s'): "
727 "List lines matching regexp: ")
735 (when current-prefix-arg
736 (prefix-numeric-value current-prefix-arg
))))
738 (defun occur-rename-buffer (&optional unique-p
)
739 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
740 Here `original-buffer-name' is the buffer name were occur was originally run.
741 When given the prefix argument, the renaming will not clobber the existing
742 buffer(s) of that name, but use `generate-new-buffer-name' instead.
743 You can add this to `occur-hook' if you always want a separate *Occur*
744 buffer for each buffer where you invoke `occur'."
747 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
748 (rename-buffer (concat "*Occur: "
749 (mapconcat #'buffer-name
750 (car (cddr occur-revert-arguments
)) "/")
754 (defun occur (regexp &optional nlines
)
755 "Show all lines in the current buffer containing a match for REGEXP.
757 If a match spreads across multiple lines, all those lines are shown.
759 Each line is displayed with NLINES lines before and after, or -NLINES
760 before if NLINES is negative.
761 NLINES defaults to `list-matching-lines-default-context-lines'.
762 Interactively it is the prefix arg.
764 The lines are shown in a buffer named `*Occur*'.
765 It serves as a menu to find any of the occurrences in this buffer.
766 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
768 If REGEXP contains upper case characters (excluding those preceded by `\\'),
769 the matching is case-sensitive."
770 (interactive (occur-read-primary-args))
771 (occur-1 regexp nlines
(list (current-buffer))))
773 (defun multi-occur (bufs regexp
&optional nlines
)
774 "Show all lines in buffers BUFS containing a match for REGEXP.
775 This function acts on multiple buffers; otherwise, it is exactly like
779 (let* ((bufs (list (read-buffer "First buffer to search: "
780 (current-buffer) t
)))
782 (ido-ignore-item-temp-list bufs
))
783 (while (not (string-equal
784 (setq buf
(read-buffer
785 (if (eq read-buffer-function
'ido-read-buffer
)
786 "Next buffer to search (C-j to end): "
787 "Next buffer to search (RET to end): ")
790 (add-to-list 'bufs buf
)
791 (setq ido-ignore-item-temp-list bufs
))
792 (nreverse (mapcar #'get-buffer bufs
)))
793 (occur-read-primary-args)))
794 (occur-1 regexp nlines bufs
))
796 (defun multi-occur-by-filename-regexp (bufregexp regexp
&optional nlines
)
797 "Show all lines matching REGEXP in buffers named by BUFREGEXP.
798 See also `multi-occur'."
801 (let* ((default (car regexp-history
))
803 (read-from-minibuffer
804 "List lines in buffers whose filename matches regexp: "
812 (occur-read-primary-args)))
814 (occur-1 regexp nlines
816 (mapcar (lambda (buf)
817 (when (and (buffer-file-name buf
)
818 (string-match bufregexp
819 (buffer-file-name buf
)))
823 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
825 (setq buf-name
"*Occur*"))
826 (let ((occur-buf (get-buffer-create buf-name
))
828 (active-bufs (delq nil
(mapcar #'(lambda (buf)
829 (when (buffer-live-p buf
) buf
))
831 ;; Handle the case where one of the buffers we're searching is the
832 ;; *Occur* buffer itself.
833 (when (memq occur-buf bufs
)
834 (setq occur-buf
(with-current-buffer occur-buf
835 (clone-buffer "*Occur-temp*"))
837 (with-current-buffer occur-buf
838 (setq buffer-read-only nil
)
841 (let ((count (occur-engine
842 regexp active-bufs occur-buf
843 (or nlines list-matching-lines-default-context-lines
)
844 (and case-fold-search
845 (isearch-no-upper-case-p regexp t
))
846 list-matching-lines-buffer-name-face
847 nil list-matching-lines-face nil
)))
848 (let* ((bufcount (length active-bufs
))
849 (diff (- (length bufs
) bufcount
)))
850 (message "Searched %d buffer%s%s; %s match%s for `%s'"
851 bufcount
(if (= bufcount
1) "" "s")
852 (if (zerop diff
) "" (format " (%d killed)" diff
))
853 (if (zerop count
) "no" (format "%d" count
))
854 (if (= count
1) "" "es")
856 ;; If we had to make a temporary buffer, make it the *Occur*
859 (with-current-buffer (get-buffer buf-name
)
860 (kill-buffer (current-buffer)))
861 (rename-buffer buf-name
))
862 (setq occur-revert-arguments
(list regexp nlines bufs
)
866 (display-buffer occur-buf
)
867 (setq next-error-last-buffer occur-buf
))
868 (kill-buffer occur-buf
)))
869 (run-hooks 'occur-hook
))))
871 (defun occur-engine-add-prefix (lines)
874 (concat " :" line
"\n"))
877 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
878 title-face prefix-face match-face keep-props
)
879 (with-current-buffer out-buf
880 (setq buffer-read-only nil
)
881 (let ((globalcount 0)
883 ;; Map over all the buffers
884 (dolist (buf buffers
)
885 (when (buffer-live-p buf
)
886 (let ((matches 0) ;; count of matched lines
887 (lines 1) ;; line count
895 (headerpt (with-current-buffer out-buf
(point))))
899 ;; Set CODING only if the current buffer locally
900 ;; binds buffer-file-coding-system.
901 (not (local-variable-p 'buffer-file-coding-system
))
902 (setq coding buffer-file-coding-system
))
904 (goto-char (point-min)) ;; begin searching in the buffer
906 (setq origpt
(point))
907 (when (setq endpt
(re-search-forward regexp nil t
))
908 (setq matches
(1+ matches
)) ;; increment match count
909 (setq matchbeg
(match-beginning 0)
910 matchend
(match-end 0))
911 (setq begpt
(save-excursion
913 (line-beginning-position)))
914 (setq lines
(+ lines
(1- (count-lines origpt endpt
))))
915 (setq marker
(make-marker))
916 (set-marker marker matchbeg
)
917 (setq curstring
(buffer-substring begpt
918 (line-end-position)))
919 ;; Depropertize the string, and maybe
920 ;; highlight the matches
921 (let ((len (length curstring
))
924 (set-text-properties 0 len nil curstring
))
925 (while (and (< start len
)
926 (string-match regexp curstring start
))
927 (add-text-properties (match-beginning 0)
932 `(font-lock-face ,match-face
)))
934 (setq start
(match-end 0))))
935 ;; Generate the string to insert for this match
938 ;; Using 7 digits aligns tabs properly.
939 (apply #'propertize
(format "%7d:" lines
)
942 `(font-lock-face prefix-face
))
948 ;; The simple display style
950 ;; The complex multi-line display
951 ;; style. Generate a list of lines,
952 ;; concatenate them all together.
955 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ nlines
)) keep-props
))))
957 (occur-engine-add-prefix (cdr (occur-accumulate-lines (1+ nlines
) keep-props
))))))))
958 ;; Actually insert the match display data
959 (with-current-buffer out-buf
961 (end (progn (insert data
) (point))))
963 (insert "-------\n"))
966 `(occur-target ,marker help-echo
"mouse-2: go to this occurrence"))
967 ;; We don't put `mouse-face' on the newline,
968 ;; because that loses.
969 (add-text-properties beg
(1- end
) '(mouse-face highlight
)))))
973 (setq lines
(1+ lines
))
974 ;; On to the next match...
976 (goto-char (point-max))))))
977 (when (not (zerop matches
)) ;; is the count zero?
978 (setq globalcount
(+ globalcount matches
))
979 (with-current-buffer out-buf
983 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
984 matches
(if (= matches
1) "" "es")
985 regexp
(buffer-name buf
)))
987 (add-text-properties beg end
990 `(font-lock-face ,title-face
))
991 `(occur-title ,buf
))))
992 (goto-char (point-min)))))))
994 ;; CODING is buffer-file-coding-system of the first buffer
995 ;; that locally binds it. Let's use it also for the output
997 (set-buffer-file-coding-system coding
))
998 ;; Return the number of matches
1002 ;; It would be nice to use \\[...], but there is no reasonable way
1003 ;; to make that display both SPC and Y.
1004 (defconst query-replace-help
1005 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1006 RET or `q' to exit, Period to replace one match and exit,
1007 Comma to replace but not move point immediately,
1008 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1009 C-w to delete match and recursive edit,
1010 C-l to clear the screen, redisplay, and offer same replacement again,
1011 ! to replace all remaining matches with no more questions,
1012 ^ to move point back to previous match,
1013 E to edit the replacement string"
1014 "Help message while in `query-replace'.")
1016 (defvar query-replace-map
(make-sparse-keymap)
1017 "Keymap that defines the responses to questions in `query-replace'.
1018 The \"bindings\" in this map are not commands; they are answers.
1019 The valid answers include `act', `skip', `act-and-show',
1020 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1021 `automatic', `backup', `exit-prefix', and `help'.")
1023 (define-key query-replace-map
" " 'act
)
1024 (define-key query-replace-map
"\d" 'skip
)
1025 (define-key query-replace-map
[delete] 'skip)
1026 (define-key query-replace-map [backspace] 'skip)
1027 (define-key query-replace-map "y" 'act)
1028 (define-key query-replace-map "n" 'skip)
1029 (define-key query-replace-map "Y" 'act)
1030 (define-key query-replace-map "N" 'skip)
1031 (define-key query-replace-map "e" 'edit-replacement)
1032 (define-key query-replace-map "E" 'edit-replacement)
1033 (define-key query-replace-map "," 'act-and-show)
1034 (define-key query-replace-map "q" 'exit)
1035 (define-key query-replace-map "\r" 'exit)
1036 (define-key query-replace-map [return] 'exit)
1037 (define-key query-replace-map "." 'act-and-exit)
1038 (define-key query-replace-map "\C-r" 'edit)
1039 (define-key query-replace-map "\C-w" 'delete-and-edit)
1040 (define-key query-replace-map "\C-l" 'recenter)
1041 (define-key query-replace-map "!" 'automatic)
1042 (define-key query-replace-map "^" 'backup)
1043 (define-key query-replace-map "\C-h" 'help)
1044 (define-key query-replace-map [f1] 'help)
1045 (define-key query-replace-map [help] 'help)
1046 (define-key query-replace-map "?" 'help)
1047 (define-key query-replace-map "\C-g" 'quit)
1048 (define-key query-replace-map "\C-]" 'quit)
1049 (define-key query-replace-map "\e" 'exit-prefix)
1050 (define-key query-replace-map [escape] 'exit-prefix)
1052 (defun replace-match-string-symbols (n)
1053 "Process a list (and any sub-lists), expanding certain symbols.
1055 N (match-string N) (where N is a string of digits)
1056 #N (string-to-number (match-string N))
1058 #& (string-to-number (match-string 0))
1061 Note that these symbols must be preceeded by a backslash in order to
1066 (replace-match-string-symbols (car n))) ;Process sub-list
1068 (let ((name (symbol-name (car n))))
1070 ((string-match "^[0-9]+$" name)
1071 (setcar n (list 'match-string (string-to-number name))))
1072 ((string-match "^#[0-9]+$" name)
1073 (setcar n (list 'string-to-number
1075 (string-to-number (substring name 1))))))
1077 (setcar n '(match-string 0)))
1078 ((string= "#&" name)
1079 (setcar n '(string-to-number (match-string 0))))
1081 (setcar n 'replace-count))))))
1084 (defun replace-eval-replacement (expression replace-count)
1085 (let ((replacement (eval expression)))
1086 (if (stringp replacement)
1088 (prin1-to-string replacement t))))
1090 (defun replace-quote (replacement)
1091 "Quote a replacement string.
1092 This just doubles all backslashes in REPLACEMENT and
1093 returns the resulting string. If REPLACEMENT is not
1094 a string, it is first passed through `prin1-to-string'
1095 with the `noescape' argument set.
1097 `match-data' is preserved across the call."
1099 (replace-regexp-in-string "\\\\" "\\\\"
1100 (if (stringp replacement)
1102 (prin1-to-string replacement t))
1105 (defun replace-loop-through-replacements (data replace-count)
1106 ;; DATA is a vector contaning the following values:
1107 ;; 0 next-rotate-count
1109 ;; 2 next-replacement
1111 (if (= (aref data 0) replace-count)
1113 (aset data 0 (+ replace-count (aref data 1)))
1114 (let ((next (cdr (aref data 2))))
1115 (aset data 2 (if (consp next) next (aref data 3))))))
1116 (car (aref data 2)))
1118 (defun perform-replace (from-string replacements
1119 query-flag regexp-flag delimited-flag
1120 &optional repeat-count map start end)
1121 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1122 Don't use this in your own program unless you want to query and set the mark
1123 just as `query-replace' does. Instead, write a simple loop like this:
1125 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1126 (replace-match \"foobar\" nil nil))
1128 which will run faster and probably do exactly what you want. Please
1129 see the documentation of `replace-match' to find out how to simulate
1132 This function returns nil if and only if there were no matches to
1133 make, or the user didn't cancel the call."
1134 (or map (setq map query-replace-map))
1135 (and query-flag minibuffer-auto-raise
1136 (raise-frame (window-frame (minibuffer-window))))
1137 (let ((nocasify (not (and case-fold-search case-replace
1138 (string-equal from-string
1139 (downcase from-string)))))
1140 (case-fold-search (and case-fold-search
1141 (string-equal from-string
1142 (downcase from-string))))
1143 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1144 (search-function (if regexp-flag 're-search-forward 'search-forward))
1145 (search-string from-string)
1146 (real-match-data nil) ; the match data for the current match
1147 (next-replacement nil)
1151 (nonempty-match nil)
1153 ;; If non-nil, it is marker saying where in the buffer to stop.
1156 ;; Data for the next match. If a cons, it has the same format as
1157 ;; (match-data); otherwise it is t if a match is possible at point.
1162 (substitute-command-keys
1163 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
1165 ;; If region is active, in Transient Mark mode, operate on region.
1167 (setq limit (copy-marker (max start end)))
1168 (goto-char (min start end))
1171 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1172 ;; containing a function and its first argument. The function is
1173 ;; called to generate each replacement like this:
1174 ;; (funcall (car replacements) (cdr replacements) replace-count)
1175 ;; It must return a string.
1177 ((stringp replacements)
1178 (setq next-replacement replacements
1180 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1181 (or repeat-count (setq repeat-count 1))
1182 (setq replacements (cons 'replace-loop-through-replacements
1183 (vector repeat-count repeat-count
1184 replacements replacements)))))
1187 (setq search-function 're-search-forward
1188 search-string (concat "\\b"
1189 (if regexp-flag from-string
1190 (regexp-quote from-string))
1195 ;; Loop finding occurrences that perhaps should be replaced.
1196 (while (and keep-going
1197 (not (or (eobp) (and limit (>= (point) limit))))
1198 ;; Use the next match if it is already known;
1199 ;; otherwise, search for a match after moving forward
1200 ;; one char if progress is required.
1201 (setq real-match-data
1202 (if (consp match-again)
1203 (progn (goto-char (nth 1 match-again))
1205 (and (or match-again
1206 ;; MATCH-AGAIN non-nil means we
1207 ;; accept an adjacent match. If
1208 ;; we don't, move one char to the
1209 ;; right. This takes us a
1210 ;; character too far at the end,
1211 ;; but this is undone after the
1216 (and limit (>= (point) limit))))))
1217 (funcall search-function search-string limit t)
1218 ;; For speed, use only integers and
1219 ;; reuse the list used last time.
1220 (match-data t real-match-data)))))
1221 ;; Optionally ignore matches that have a read-only property.
1222 (unless (and query-replace-skip-read-only
1223 (text-property-not-all
1224 (match-beginning 0) (match-end 0)
1227 ;; Record whether the match is nonempty, to avoid an infinite loop
1228 ;; repeatedly matching the same empty string.
1229 (setq nonempty-match
1230 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1232 ;; If the match is empty, record that the next one can't be
1235 ;; Otherwise, if matching a regular expression, do the next
1236 ;; match now, since the replacement for this match may
1237 ;; affect whether the next match is adjacent to this one.
1238 ;; If that match is empty, don't use it.
1241 (or (not regexp-flag)
1242 (and (looking-at search-string)
1243 (let ((match (match-data)))
1244 (and (/= (nth 0 match) (nth 1 match))
1247 ;; Calculate the replacement string, if necessary.
1249 (set-match-data real-match-data)
1250 (setq next-replacement
1251 (funcall (car replacements) (cdr replacements)
1253 (if (not query-flag)
1254 (let ((inhibit-read-only query-replace-skip-read-only))
1255 (set-match-data real-match-data)
1256 (replace-match next-replacement nocasify literal)
1257 (setq replace-count (1+ replace-count)))
1259 (let (done replaced key def)
1260 ;; Loop reading commands until one of them sets done,
1261 ;; which means it has finished handling this occurrence.
1263 (set-match-data real-match-data)
1264 (replace-highlight (match-beginning 0) (match-end 0))
1265 ;; Bind message-log-max so we don't fill up the message log
1266 ;; with a bunch of identical messages.
1267 (let ((message-log-max nil))
1268 (message message from-string next-replacement))
1269 (setq key (read-event))
1270 ;; Necessary in case something happens during read-event
1271 ;; that clobbers the match data.
1272 (set-match-data real-match-data)
1273 (setq key (vector key))
1274 (setq def (lookup-key map key))
1275 ;; Restore the match data while we process the command.
1276 (cond ((eq def 'help)
1277 (with-output-to-temp-buffer "*Help*"
1279 (concat "Query replacing "
1280 (if regexp-flag "regexp " "")
1281 from-string " with "
1282 next-replacement ".\n\n"
1283 (substitute-command-keys
1284 query-replace-help)))
1285 (with-current-buffer standard-output
1288 (setq keep-going nil)
1292 (let ((elt (pop stack)))
1293 (goto-char (car elt))
1294 (setq replaced (eq t (cdr elt)))
1296 (set-match-data (cdr elt))))
1297 (message "No previous match")
1298 (ding 'no-terminate)
1303 (replace-match next-replacement nocasify literal)
1304 (setq replace-count (1+ replace-count))))
1305 (setq done t replaced t))
1306 ((eq def 'act-and-exit)
1309 (replace-match next-replacement nocasify literal)
1310 (setq replace-count (1+ replace-count))))
1311 (setq keep-going nil)
1312 (setq done t replaced t))
1313 ((eq def 'act-and-show)
1316 (replace-match next-replacement nocasify literal)
1317 (setq replace-count (1+ replace-count))
1318 (setq replaced t))))
1319 ((eq def 'automatic)
1322 (replace-match next-replacement nocasify literal)
1323 (setq replace-count (1+ replace-count))))
1324 (setq done t query-flag nil replaced t))
1330 (let ((opos (point-marker)))
1331 (goto-char (match-beginning 0))
1333 (funcall search-function search-string limit t)
1334 (setq real-match-data (match-data)))
1336 (save-window-excursion
1339 (set-match-data real-match-data)
1340 ;; Before we make the replacement,
1341 ;; decide whether the search string
1342 ;; can match again just after this match.
1343 (if (and regexp-flag nonempty-match)
1344 (setq match-again (and (looking-at search-string)
1347 ;; Edit replacement.
1348 ((eq def 'edit-replacement)
1349 (setq next-replacement
1350 (read-input "Edit replacement string: "
1353 (replace-match next-replacement nocasify literal))
1356 ((eq def 'delete-and-edit)
1357 (delete-region (match-beginning 0) (match-end 0))
1360 (save-excursion (recursive-edit))))
1362 ;; Note: we do not need to treat `exit-prefix'
1363 ;; specially here, since we reread
1364 ;; any unrecognized character.
1366 (setq this-command 'mode-exited)
1367 (setq keep-going nil)
1368 (setq unread-command-events
1369 (append (listify-key-sequence key)
1370 unread-command-events))
1372 ;; Record previous position for ^ when we move on.
1373 ;; Change markers to numbers in the match data
1374 ;; since lots of markers slow down editing.
1377 (or replaced (match-data t)))
1380 ;; The code preventing adjacent regexp matches in the condition
1381 ;; of the while-loop above will haven taken us one character
1382 ;; beyond the last replacement. Undo that.
1383 (when (and regexp-flag (not match-again) (> replace-count 0))
1386 (replace-dehighlight))
1387 (or unread-command-events
1388 (message "Replaced %d occurrence%s"
1390 (if (= replace-count 1) "" "s")))
1391 (and keep-going stack)))
1393 (defcustom query-replace-highlight t
1394 "*Non-nil means to highlight words during query replacement."
1398 (defvar replace-overlay nil)
1400 (defun replace-dehighlight ()
1401 (and replace-overlay
1403 (delete-overlay replace-overlay)
1404 (setq replace-overlay nil))))
1406 (defun replace-highlight (start end)
1407 (and query-replace-highlight
1411 (setq replace-overlay (make-overlay start end))
1412 (overlay-put replace-overlay 'face
1413 (if (facep 'query-replace)
1414 'query-replace 'region))))
1415 (move-overlay replace-overlay start end (current-buffer)))))
1417 ;;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1418 ;;; replace.el ends here