(texinfo-font-lock-keywords): Disable the automatic environment name update.
[emacs.git] / lisp / replace.el
bloba182df02ca4e78fe08d102a76d35d7ae09030479
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 ;; Maintainer: FSF
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)
13 ;; any later version.
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.
25 ;;; Commentary:
27 ;; This package supplies the string and regular-expression replace functions
28 ;; documented in the Emacs user's manual.
30 ;;; Code:
32 (defcustom case-replace t
33 "*Non-nil means `query-replace' should preserve case in replacements."
34 :type 'boolean
35 :group 'matching)
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."
48 :group 'matching
49 :type 'symbol
50 :version "20.3")
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
56 strings or patterns."
57 :group 'matching
58 :type 'symbol
59 :version "20.3")
61 (defcustom query-replace-skip-read-only nil
62 "*Non-nil means `query-replace' and friends ignore read-only matches."
63 :type 'boolean
64 :group 'matching
65 :version "21.4")
67 (defun query-replace-read-args (string regexp-flag &optional noerror)
68 (unless noerror
69 (barf-if-buffer-read-only))
70 (let (from to)
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)
74 nil nil nil
75 query-replace-from-history-variable
76 nil t))
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)))
80 (cond
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")))
85 (sit-for 2))))
87 (setq to (read-from-minibuffer (format "%s %s with: " string from)
88 nil nil nil
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
104 minibuffer.
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
132 minibuffer.
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
168 minibuffer.
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."
176 (interactive
177 (let (from to start end)
178 (when (and transient-mark-mode mark-active)
179 (setq start (region-beginning)
180 end (region-end)))
181 (if query-replace-interactive
182 (setq from (car regexp-search-ring))
183 (setq from (read-from-minibuffer "Query replace regexp: "
184 nil nil nil
185 query-replace-from-history-variable
186 nil t)))
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."
217 (interactive
218 (let (from to start end)
219 (when (and transient-mark-mode mark-active)
220 (setq start (region-beginning)
221 end (region-end)))
222 (setq from (if query-replace-interactive
223 (car regexp-search-ring)
224 (read-from-minibuffer "Map query replace (regexp): "
225 nil nil nil
226 'query-replace-history nil t)))
227 (setq to (read-from-minibuffer
228 (format "Query replace %s with (space-separated strings): "
229 from)
230 nil nil nil
231 'query-replace-history from t))
232 (list from to start end current-prefix-arg)))
233 (let (replacements)
234 (if (listp to-strings)
235 (setq replacements to-strings)
236 (while (/= (length to-strings) 0)
237 (if (string-match " " to-strings)
238 (setq replacements
239 (append replacements
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))
245 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
264 minibuffer.
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
332 end of the buffer."
334 (interactive
335 (keep-lines-read-args "Keep lines (containing match for regexp): "))
336 (if rstart
337 (goto-char (min rstart rend))
338 (if (and transient-mark-mode mark-active)
339 (setq rstart (region-beginning)
340 rend (copy-marker (region-end)))
341 (setq rstart (point)
342 rend (point-max-marker)))
343 (goto-char rstart))
344 (save-excursion
345 (or (bolp) (forward-line 1))
346 (let ((start (point))
347 (case-fold-search (and case-fold-search
348 (isearch-no-upper-case-p regexp t))))
349 (while (< (point) rend)
350 ;; Start is first char not preserved by previous match.
351 (if (not (re-search-forward regexp rend 'move))
352 (delete-region start rend)
353 (let ((end (save-excursion (goto-char (match-beginning 0))
354 (beginning-of-line)
355 (point))))
356 ;; Now end is first char preserved by the new match.
357 (if (< start end)
358 (delete-region start end))))
360 (setq start (save-excursion (forward-line 1) (point)))
361 ;; If the match was empty, avoid matching again at same place.
362 (and (< (point) rend)
363 (= (match-beginning 0) (match-end 0))
364 (forward-char 1))))))
367 (defun flush-lines (regexp &optional rstart rend)
368 "Delete lines containing matches for REGEXP.
369 If a match is split across lines, all the lines it lies in are deleted.
370 Applies to lines after point.
372 If REGEXP contains upper case characters (excluding those preceded by `\\'),
373 the matching is case-sensitive.
375 Second and third arg RSTART and REND specify the region to operate on.
377 Interactively, in Transient Mark mode when the mark is active, operate
378 on the contents of the region. Otherwise, operate from point to the
379 end of the buffer."
381 (interactive
382 (keep-lines-read-args "Flush lines (containing match for regexp): "))
383 (if rstart
384 (goto-char (min rstart rend))
385 (if (and transient-mark-mode mark-active)
386 (setq rstart (region-beginning)
387 rend (copy-marker (region-end)))
388 (setq rstart (point)
389 rend (point-max-marker)))
390 (goto-char rstart))
391 (let ((case-fold-search (and case-fold-search
392 (isearch-no-upper-case-p regexp t))))
393 (save-excursion
394 (while (and (< (point) rend)
395 (re-search-forward regexp rend t))
396 (delete-region (save-excursion (goto-char (match-beginning 0))
397 (beginning-of-line)
398 (point))
399 (progn (forward-line 1) (point)))))))
402 (defun how-many (regexp &optional rstart rend)
403 "Print number of matches for REGEXP following point.
405 If REGEXP contains upper case characters (excluding those preceded by `\\'),
406 the matching is case-sensitive.
408 Second and third arg RSTART and REND specify the region to operate on.
410 Interactively, in Transient Mark mode when the mark is active, operate
411 on the contents of the region. Otherwise, operate from point to the
412 end of the buffer."
414 (interactive
415 (keep-lines-read-args "How many matches for (regexp): "))
416 (save-excursion
417 (if rstart
418 (goto-char (min rstart rend))
419 (if (and transient-mark-mode mark-active)
420 (setq rstart (region-beginning)
421 rend (copy-marker (region-end)))
422 (setq rstart (point)
423 rend (point-max-marker)))
424 (goto-char rstart))
425 (let ((count 0)
426 opoint
427 (case-fold-search (and case-fold-search
428 (isearch-no-upper-case-p regexp t))))
429 (while (and (< (point) rend)
430 (progn (setq opoint (point))
431 (re-search-forward regexp rend t)))
432 (if (= opoint (point))
433 (forward-char 1)
434 (setq count (1+ count))))
435 (message "%d occurrences" count))))
438 (defvar occur-mode-map
439 (let ((map (make-sparse-keymap)))
440 (define-key map [mouse-2] 'occur-mode-mouse-goto)
441 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
442 (define-key map "\C-m" 'occur-mode-goto-occurrence)
443 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
444 (define-key map "\C-o" 'occur-mode-display-occurrence)
445 (define-key map "\M-n" 'occur-next)
446 (define-key map "\M-p" 'occur-prev)
447 (define-key map "g" 'revert-buffer)
448 (define-key map "q" 'delete-window)
449 map)
450 "Keymap for `occur-mode'.")
452 (defvar occur-revert-arguments nil
453 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
454 See `occur-revert-function'.")
456 (defcustom occur-mode-hook '(turn-on-font-lock)
457 "Hooks run when `occur' is called."
458 :type 'hook
459 :group 'matching)
461 (put 'occur-mode 'mode-class 'special)
462 (defun occur-mode ()
463 "Major mode for output from \\[occur].
464 \\<occur-mode-map>Move point to one of the items in this buffer, then use
465 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
466 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
468 \\{occur-mode-map}"
469 (kill-all-local-variables)
470 (use-local-map occur-mode-map)
471 (setq major-mode 'occur-mode)
472 (setq mode-name "Occur")
473 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
474 (make-local-variable 'occur-revert-arguments)
475 (run-hooks 'occur-mode-hook))
477 (defun occur-revert-function (ignore1 ignore2)
478 "Handle `revert-buffer' for Occur mode buffers."
479 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
481 (defun occur-mode-mouse-goto (event)
482 "In Occur mode, go to the occurrence whose line you click on."
483 (interactive "e")
484 (let (pos)
485 (save-excursion
486 (set-buffer (window-buffer (posn-window (event-end event))))
487 (save-excursion
488 (goto-char (posn-point (event-end event)))
489 (setq pos (occur-mode-find-occurrence))))
490 (pop-to-buffer (marker-buffer pos))
491 (goto-char pos)))
493 (defun occur-mode-find-occurrence ()
494 (let ((pos (get-text-property (point) 'occur-target)))
495 (unless pos
496 (error "No occurrence on this line"))
497 (unless (buffer-live-p (marker-buffer pos))
498 (error "Buffer for this occurrence was killed"))
499 pos))
501 (defun occur-mode-goto-occurrence ()
502 "Go to the occurrence the current line describes."
503 (interactive)
504 (let ((pos (occur-mode-find-occurrence)))
505 (pop-to-buffer (marker-buffer pos))
506 (goto-char pos)))
508 (defun occur-mode-goto-occurrence-other-window ()
509 "Go to the occurrence the current line describes, in another window."
510 (interactive)
511 (let ((pos (occur-mode-find-occurrence)))
512 (switch-to-buffer-other-window (marker-buffer pos))
513 (goto-char pos)))
515 (defun occur-mode-display-occurrence ()
516 "Display in another window the occurrence the current line describes."
517 (interactive)
518 (let ((pos (occur-mode-find-occurrence))
519 window
520 ;; Bind these to ensure `display-buffer' puts it in another window.
521 same-window-buffer-names
522 same-window-regexps)
523 (setq window (display-buffer (marker-buffer pos)))
524 ;; This is the way to set point in the proper window.
525 (save-selected-window
526 (select-window window)
527 (goto-char pos))))
529 (defun occur-next (&optional n)
530 "Move to the Nth (default 1) next match in an Occur mode buffer."
531 (interactive "p")
532 (if (not n) (setq n 1))
533 (let ((r))
534 (while (> n 0)
535 (if (get-text-property (point) 'occur-point)
536 (forward-char 1))
537 (setq r (next-single-property-change (point) 'occur-point))
538 (if r
539 (goto-char r)
540 (error "No more matches"))
541 (setq n (1- n)))))
543 (defun occur-prev (&optional n)
544 "Move to the Nth (default 1) previous match in an Occur mode buffer."
545 (interactive "p")
546 (if (not n) (setq n 1))
547 (let ((r))
548 (while (> n 0)
550 (setq r (get-text-property (point) 'occur-point))
551 (if r (forward-char -1))
553 (setq r (previous-single-property-change (point) 'occur-point))
554 (if r
555 (goto-char (- r 1))
556 (error "No earlier matches"))
558 (setq n (1- n)))))
560 (defcustom list-matching-lines-default-context-lines 0
561 "*Default number of context lines included around `list-matching-lines' matches.
562 A negative number means to include that many lines before the match.
563 A positive number means to include that many lines both before and after."
564 :type 'integer
565 :group 'matching)
567 (defalias 'list-matching-lines 'occur)
569 (defcustom list-matching-lines-face 'bold
570 "*Face used by \\[list-matching-lines] to show the text that matches.
571 If the value is nil, don't highlight the matching portions specially."
572 :type 'face
573 :group 'matching)
575 (defcustom list-matching-lines-buffer-name-face 'underline
576 "*Face used by \\[list-matching-lines] to show the names of buffers.
577 If the value is nil, don't highlight the buffer names specially."
578 :type 'face
579 :group 'matching)
581 (defun occur-accumulate-lines (count &optional no-props)
582 (save-excursion
583 (let ((forwardp (> count 0))
584 (result nil))
585 (while (not (or (zerop count)
586 (if forwardp
587 (eobp)
588 (bobp))))
589 (setq count (+ count (if forwardp -1 1)))
590 (push
591 (funcall (if no-props
592 #'buffer-substring-no-properties
593 #'buffer-substring)
594 (line-beginning-position)
595 (line-end-position))
596 result)
597 (forward-line (if forwardp 1 -1)))
598 (nreverse result))))
600 (defun occur-read-primary-args ()
601 (list (let* ((default (car regexp-history))
602 (input
603 (read-from-minibuffer
604 (if default
605 (format "List lines matching regexp (default `%s'): "
606 default)
607 "List lines matching regexp: ")
611 'regexp-history)))
612 (if (equal input "")
613 default
614 input))
615 (when current-prefix-arg
616 (prefix-numeric-value current-prefix-arg))))
618 (defun occur (regexp &optional nlines)
619 "Show all lines in the current buffer containing a match for REGEXP.
621 If a match spreads across multiple lines, all those lines are shown.
623 Each line is displayed with NLINES lines before and after, or -NLINES
624 before if NLINES is negative.
625 NLINES defaults to `list-matching-lines-default-context-lines'.
626 Interactively it is the prefix arg.
628 The lines are shown in a buffer named `*Occur*'.
629 It serves as a menu to find any of the occurrences in this buffer.
630 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
632 If REGEXP contains upper case characters (excluding those preceded by `\\'),
633 the matching is case-sensitive."
634 (interactive (occur-read-primary-args))
635 (occur-1 regexp nlines (list (current-buffer))))
637 (defun multi-occur (bufs regexp &optional nlines)
638 "Show all lines in buffers BUFS containing a match for REGEXP.
639 This function acts on multiple buffers; otherwise, it is exactly like
640 `occur'."
641 (interactive
642 (cons
643 (let ((bufs (list (read-buffer "First buffer to search: "
644 (current-buffer) t)))
645 (buf nil))
646 (while (not (string-equal
647 (setq buf (read-buffer "Next buffer to search (RET to end): "
648 nil t))
649 ""))
650 (push buf bufs))
651 (nreverse (mapcar #'get-buffer bufs)))
652 (occur-read-primary-args)))
653 (occur-1 regexp nlines bufs))
655 (defun multi-occur-by-filename-regexp (bufregexp regexp &optional nlines)
656 "Show all lines matching REGEXP in buffers named by BUFREGEXP.
657 See also `multi-occur'."
658 (interactive
659 (cons
660 (let* ((default (car regexp-history))
661 (input
662 (read-from-minibuffer
663 "List lines in buffers whose filename matches regexp: "
667 'regexp-history)))
668 (if (equal input "")
669 default
670 input))
671 (occur-read-primary-args)))
672 (when bufregexp
673 (occur-1 regexp nlines
674 (delq nil
675 (mapcar (lambda (buf)
676 (when (and (buffer-file-name buf)
677 (string-match bufregexp
678 (buffer-file-name buf)))
679 buf))
680 (buffer-list))))))
682 (defun occur-1 (regexp nlines bufs &optional buf-name)
683 (unless buf-name
684 (setq buf-name "*Occur*"))
685 (let ((occur-buf (get-buffer-create buf-name))
686 (made-temp-buf nil)
687 (active-bufs (delq nil (mapcar #'(lambda (buf)
688 (when (buffer-live-p buf) buf))
689 bufs))))
690 ;; Handle the case where one of the buffers we're searching is the
691 ;; *Occur* buffer itself.
692 (when (memq occur-buf bufs)
693 (setq occur-buf (with-current-buffer occur-buf
694 (clone-buffer "*Occur-temp*"))
695 made-temp-buf t))
696 (with-current-buffer occur-buf
697 (setq buffer-read-only nil)
698 (occur-mode)
699 (erase-buffer)
700 (let ((count (occur-engine
701 regexp active-bufs occur-buf
702 (or nlines list-matching-lines-default-context-lines)
703 (and case-fold-search
704 (isearch-no-upper-case-p regexp t))
705 list-matching-lines-buffer-name-face
706 nil list-matching-lines-face nil)))
707 (let* ((bufcount (length active-bufs))
708 (diff (- (length bufs) bufcount)))
709 (message "Searched %d buffer%s%s; %s match%s for `%s'"
710 bufcount (if (= bufcount 1) "" "s")
711 (if (zerop diff) "" (format " (%d killed)" diff))
712 (if (zerop count) "no" (format "%d" count))
713 (if (= count 1) "" "es")
714 regexp))
715 ;; If we had to make a temporary buffer, make it the *Occur*
716 ;; buffer now.
717 (when made-temp-buf
718 (with-current-buffer (get-buffer buf-name)
719 (kill-buffer (current-buffer)))
720 (rename-buffer buf-name))
721 (setq occur-revert-arguments (list regexp nlines bufs)
722 buffer-read-only t)
723 (if (> count 0)
724 (display-buffer occur-buf)
725 (kill-buffer occur-buf))))))
727 (defun occur-engine-add-prefix (lines)
728 (mapcar
729 #'(lambda (line)
730 (concat " :" line "\n"))
731 lines))
733 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
734 title-face prefix-face match-face keep-props)
735 (with-current-buffer out-buf
736 (setq buffer-read-only nil)
737 (let ((globalcount 0))
738 ;; Map over all the buffers
739 (dolist (buf buffers)
740 (when (buffer-live-p buf)
741 (let ((matches 0) ;; count of matched lines
742 (lines 1) ;; line count
743 (matchbeg 0)
744 (matchend 0)
745 (origpt nil)
746 (begpt nil)
747 (endpt nil)
748 (marker nil)
749 (curstring "")
750 (headerpt (with-current-buffer out-buf (point))))
751 (save-excursion
752 (set-buffer buf)
753 (save-excursion
754 (goto-char (point-min)) ;; begin searching in the buffer
755 (while (not (eobp))
756 (setq origpt (point))
757 (when (setq endpt (re-search-forward regexp nil t))
758 (setq matches (1+ matches)) ;; increment match count
759 (setq matchbeg (match-beginning 0)
760 matchend (match-end 0))
761 (setq begpt (save-excursion
762 (goto-char matchbeg)
763 (line-beginning-position)))
764 (setq lines (+ lines (1- (count-lines origpt endpt))))
765 (setq marker (make-marker))
766 (set-marker marker matchbeg)
767 (setq curstring (buffer-substring begpt
768 (line-end-position)))
769 ;; Depropertize the string, and maybe
770 ;; highlight the matches
771 (let ((len (length curstring))
772 (start 0))
773 (unless keep-props
774 (set-text-properties 0 len nil curstring))
775 (while (and (< start len)
776 (string-match regexp curstring start))
777 (add-text-properties (match-beginning 0)
778 (match-end 0)
779 (append
780 `(occur-match t)
781 (when match-face
782 `(font-lock-face ,match-face)))
783 curstring)
784 (setq start (match-end 0))))
785 ;; Generate the string to insert for this match
786 (let* ((out-line
787 (concat
788 (apply #'propertize (format "%6d:" lines)
789 (append
790 (when prefix-face
791 `(font-lock-face prefix-face))
792 '(occur-prefix t)))
793 curstring
794 "\n"))
795 (data
796 (if (= nlines 0)
797 ;; The simple display style
798 out-line
799 ;; The complex multi-line display
800 ;; style. Generate a list of lines,
801 ;; concatenate them all together.
802 (apply #'concat
803 (nconc
804 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ nlines)) keep-props))))
805 (list out-line)
806 (occur-engine-add-prefix (cdr (occur-accumulate-lines (1+ nlines) keep-props))))))))
807 ;; Actually insert the match display data
808 (with-current-buffer out-buf
809 (let ((beg (point))
810 (end (progn (insert data) (point))))
811 (unless (= nlines 0)
812 (insert "-------\n"))
813 (add-text-properties
814 beg end
815 `(occur-target ,marker help-echo "mouse-2: go to this occurrence"))
816 ;; We don't put `mouse-face' on the newline,
817 ;; because that loses.
818 (add-text-properties beg (1- end) '(mouse-face highlight)))))
819 (goto-char endpt))
820 (if endpt
821 (progn
822 (setq lines (1+ lines))
823 ;; On to the next match...
824 (forward-line 1))
825 (goto-char (point-max))))))
826 (when (not (zerop matches)) ;; is the count zero?
827 (setq globalcount (+ globalcount matches))
828 (with-current-buffer out-buf
829 (goto-char headerpt)
830 (let ((beg (point))
831 end)
832 (insert (format "%d lines matching \"%s\" in buffer: %s\n"
833 matches regexp (buffer-name buf)))
834 (setq end (point))
835 (add-text-properties beg end
836 (append
837 (when title-face
838 `(font-lock-face ,title-face))
839 `(occur-title ,buf))))
840 (goto-char (point-min)))))))
841 ;; Return the number of matches
842 globalcount)))
845 ;; It would be nice to use \\[...], but there is no reasonable way
846 ;; to make that display both SPC and Y.
847 (defconst query-replace-help
848 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
849 RET or `q' to exit, Period to replace one match and exit,
850 Comma to replace but not move point immediately,
851 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
852 C-w to delete match and recursive edit,
853 C-l to clear the screen, redisplay, and offer same replacement again,
854 ! to replace all remaining matches with no more questions,
855 ^ to move point back to previous match,
856 E to edit the replacement string"
857 "Help message while in `query-replace'.")
859 (defvar query-replace-map (make-sparse-keymap)
860 "Keymap that defines the responses to questions in `query-replace'.
861 The \"bindings\" in this map are not commands; they are answers.
862 The valid answers include `act', `skip', `act-and-show',
863 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
864 `automatic', `backup', `exit-prefix', and `help'.")
866 (define-key query-replace-map " " 'act)
867 (define-key query-replace-map "\d" 'skip)
868 (define-key query-replace-map [delete] 'skip)
869 (define-key query-replace-map [backspace] 'skip)
870 (define-key query-replace-map "y" 'act)
871 (define-key query-replace-map "n" 'skip)
872 (define-key query-replace-map "Y" 'act)
873 (define-key query-replace-map "N" 'skip)
874 (define-key query-replace-map "e" 'edit-replacement)
875 (define-key query-replace-map "E" 'edit-replacement)
876 (define-key query-replace-map "," 'act-and-show)
877 (define-key query-replace-map "q" 'exit)
878 (define-key query-replace-map "\r" 'exit)
879 (define-key query-replace-map [return] 'exit)
880 (define-key query-replace-map "." 'act-and-exit)
881 (define-key query-replace-map "\C-r" 'edit)
882 (define-key query-replace-map "\C-w" 'delete-and-edit)
883 (define-key query-replace-map "\C-l" 'recenter)
884 (define-key query-replace-map "!" 'automatic)
885 (define-key query-replace-map "^" 'backup)
886 (define-key query-replace-map "\C-h" 'help)
887 (define-key query-replace-map [f1] 'help)
888 (define-key query-replace-map [help] 'help)
889 (define-key query-replace-map "?" 'help)
890 (define-key query-replace-map "\C-g" 'quit)
891 (define-key query-replace-map "\C-]" 'quit)
892 (define-key query-replace-map "\e" 'exit-prefix)
893 (define-key query-replace-map [escape] 'exit-prefix)
895 (defun replace-match-string-symbols (n)
896 "Process a list (and any sub-lists), expanding certain symbols.
897 Symbol Expands To
898 N (match-string N) (where N is a string of digits)
899 #N (string-to-number (match-string N))
900 & (match-string 0)
901 #& (string-to-number (match-string 0))
903 Note that these symbols must be preceeded by a backslash in order to
904 type them."
905 (while n
906 (cond
907 ((consp (car n))
908 (replace-match-string-symbols (car n))) ;Process sub-list
909 ((symbolp (car n))
910 (let ((name (symbol-name (car n))))
911 (cond
912 ((string-match "^[0-9]+$" name)
913 (setcar n (list 'match-string (string-to-number name))))
914 ((string-match "^#[0-9]+$" name)
915 (setcar n (list 'string-to-number
916 (list 'match-string
917 (string-to-number (substring name 1))))))
918 ((string= "&" name)
919 (setcar n '(match-string 0)))
920 ((string= "#&" name)
921 (setcar n '(string-to-number (match-string 0))))))))
922 (setq n (cdr n))))
924 (defun replace-eval-replacement (expression replace-count)
925 (let ((replacement (eval expression)))
926 (if (stringp replacement)
927 replacement
928 (prin1-to-string replacement t))))
930 (defun replace-loop-through-replacements (data replace-count)
931 ;; DATA is a vector contaning the following values:
932 ;; 0 next-rotate-count
933 ;; 1 repeat-count
934 ;; 2 next-replacement
935 ;; 3 replacements
936 (if (= (aref data 0) replace-count)
937 (progn
938 (aset data 0 (+ replace-count (aref data 1)))
939 (let ((next (cdr (aref data 2))))
940 (aset data 2 (if (consp next) next (aref data 3))))))
941 (car (aref data 2)))
943 (defun perform-replace (from-string replacements
944 query-flag regexp-flag delimited-flag
945 &optional repeat-count map start end)
946 "Subroutine of `query-replace'. Its complexity handles interactive queries.
947 Don't use this in your own program unless you want to query and set the mark
948 just as `query-replace' does. Instead, write a simple loop like this:
950 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
951 (replace-match \"foobar\" nil nil))
953 which will run faster and probably do exactly what you want. Please
954 see the documentation of `replace-match' to find out how to simulate
955 `case-replace'.
957 This function returns nil if and only if there were no matches to
958 make, or the user didn't cancel the call."
959 (or map (setq map query-replace-map))
960 (and query-flag minibuffer-auto-raise
961 (raise-frame (window-frame (minibuffer-window))))
962 (let ((nocasify (not (and case-fold-search case-replace
963 (string-equal from-string
964 (downcase from-string)))))
965 (case-fold-search (and case-fold-search
966 (string-equal from-string
967 (downcase from-string))))
968 (literal (not regexp-flag))
969 (search-function (if regexp-flag 're-search-forward 'search-forward))
970 (search-string from-string)
971 (real-match-data nil) ; the match data for the current match
972 (next-replacement nil)
973 (keep-going t)
974 (stack nil)
975 (replace-count 0)
976 (nonempty-match nil)
978 ;; If non-nil, it is marker saying where in the buffer to stop.
979 (limit nil)
981 ;; Data for the next match. If a cons, it has the same format as
982 ;; (match-data); otherwise it is t if a match is possible at point.
983 (match-again t)
985 (message
986 (if query-flag
987 (substitute-command-keys
988 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
990 ;; If region is active, in Transient Mark mode, operate on region.
991 (when start
992 (setq limit (copy-marker (max start end)))
993 (goto-char (min start end))
994 (deactivate-mark))
996 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
997 ;; containing a function and its first argument. The function is
998 ;; called to generate each replacement like this:
999 ;; (funcall (car replacements) (cdr replacements) replace-count)
1000 ;; It must return a string.
1001 (cond
1002 ((stringp replacements)
1003 (setq next-replacement replacements
1004 replacements nil))
1005 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1006 (or repeat-count (setq repeat-count 1))
1007 (setq replacements (cons 'replace-loop-through-replacements
1008 (vector repeat-count repeat-count
1009 replacements replacements)))))
1011 (if delimited-flag
1012 (setq search-function 're-search-forward
1013 search-string (concat "\\b"
1014 (if regexp-flag from-string
1015 (regexp-quote from-string))
1016 "\\b")))
1017 (push-mark)
1018 (undo-boundary)
1019 (unwind-protect
1020 ;; Loop finding occurrences that perhaps should be replaced.
1021 (while (and keep-going
1022 (not (eobp))
1023 ;; Use the next match if it is already known;
1024 ;; otherwise, search for a match after moving forward
1025 ;; one char if progress is required.
1026 (setq real-match-data
1027 (if (consp match-again)
1028 (progn (goto-char (nth 1 match-again))
1029 match-again)
1030 (and (or match-again
1031 ;; MATCH-AGAIN non-nil means we
1032 ;; accept an adjacent match. If
1033 ;; we don't, move one char to the
1034 ;; right. This takes us a
1035 ;; character too far at the end,
1036 ;; but this is undone after the
1037 ;; while-loop.
1038 (progn (forward-char 1) (not (eobp))))
1039 (funcall search-function search-string limit t)
1040 ;; For speed, use only integers and
1041 ;; reuse the list used last time.
1042 (match-data t real-match-data)))))
1043 ;; Optionally ignore matches that have a read-only property.
1044 (unless (and query-replace-skip-read-only
1045 (text-property-not-all
1046 (match-beginning 0) (match-end 0)
1047 'read-only nil))
1049 ;; Record whether the match is nonempty, to avoid an infinite loop
1050 ;; repeatedly matching the same empty string.
1051 (setq nonempty-match
1052 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1054 ;; If the match is empty, record that the next one can't be
1055 ;; adjacent.
1057 ;; Otherwise, if matching a regular expression, do the next
1058 ;; match now, since the replacement for this match may
1059 ;; affect whether the next match is adjacent to this one.
1060 ;; If that match is empty, don't use it.
1061 (setq match-again
1062 (and nonempty-match
1063 (or (not regexp-flag)
1064 (and (looking-at search-string)
1065 (let ((match (match-data)))
1066 (and (/= (nth 0 match) (nth 1 match))
1067 match))))))
1069 ;; Calculate the replacement string, if necessary.
1070 (when replacements
1071 (set-match-data real-match-data)
1072 (setq next-replacement
1073 (funcall (car replacements) (cdr replacements)
1074 replace-count)))
1075 (if (not query-flag)
1076 (let ((inhibit-read-only query-replace-skip-read-only))
1077 (set-match-data real-match-data)
1078 (replace-match next-replacement nocasify literal)
1079 (setq replace-count (1+ replace-count)))
1080 (undo-boundary)
1081 (let (done replaced key def)
1082 ;; Loop reading commands until one of them sets done,
1083 ;; which means it has finished handling this occurrence.
1084 (while (not done)
1085 (set-match-data real-match-data)
1086 (replace-highlight (match-beginning 0) (match-end 0))
1087 ;; Bind message-log-max so we don't fill up the message log
1088 ;; with a bunch of identical messages.
1089 (let ((message-log-max nil))
1090 (message message from-string next-replacement))
1091 (setq key (read-event))
1092 ;; Necessary in case something happens during read-event
1093 ;; that clobbers the match data.
1094 (set-match-data real-match-data)
1095 (setq key (vector key))
1096 (setq def (lookup-key map key))
1097 ;; Restore the match data while we process the command.
1098 (cond ((eq def 'help)
1099 (with-output-to-temp-buffer "*Help*"
1100 (princ
1101 (concat "Query replacing "
1102 (if regexp-flag "regexp " "")
1103 from-string " with "
1104 next-replacement ".\n\n"
1105 (substitute-command-keys
1106 query-replace-help)))
1107 (with-current-buffer standard-output
1108 (help-mode))))
1109 ((eq def 'exit)
1110 (setq keep-going nil)
1111 (setq done t))
1112 ((eq def 'backup)
1113 (if stack
1114 (let ((elt (pop stack)))
1115 (goto-char (car elt))
1116 (setq replaced (eq t (cdr elt)))
1117 (or replaced
1118 (set-match-data (cdr elt))))
1119 (message "No previous match")
1120 (ding 'no-terminate)
1121 (sit-for 1)))
1122 ((eq def 'act)
1123 (or replaced
1124 (progn
1125 (replace-match next-replacement nocasify literal)
1126 (setq replace-count (1+ replace-count))))
1127 (setq done t replaced t))
1128 ((eq def 'act-and-exit)
1129 (or replaced
1130 (progn
1131 (replace-match next-replacement nocasify literal)
1132 (setq replace-count (1+ replace-count))))
1133 (setq keep-going nil)
1134 (setq done t replaced t))
1135 ((eq def 'act-and-show)
1136 (if (not replaced)
1137 (progn
1138 (replace-match next-replacement nocasify literal)
1139 (setq replace-count (1+ replace-count))
1140 (setq replaced t))))
1141 ((eq def 'automatic)
1142 (or replaced
1143 (progn
1144 (replace-match next-replacement nocasify literal)
1145 (setq replace-count (1+ replace-count))))
1146 (setq done t query-flag nil replaced t))
1147 ((eq def 'skip)
1148 (setq done t))
1149 ((eq def 'recenter)
1150 (recenter nil))
1151 ((eq def 'edit)
1152 (let ((opos (point-marker)))
1153 (goto-char (match-beginning 0))
1154 (save-excursion
1155 (funcall search-function search-string limit t)
1156 (setq real-match-data (match-data)))
1157 (save-excursion
1158 (save-window-excursion
1159 (recursive-edit)))
1160 (goto-char opos))
1161 (set-match-data real-match-data)
1162 ;; Before we make the replacement,
1163 ;; decide whether the search string
1164 ;; can match again just after this match.
1165 (if (and regexp-flag nonempty-match)
1166 (setq match-again (and (looking-at search-string)
1167 (match-data)))))
1169 ;; Edit replacement.
1170 ((eq def 'edit-replacement)
1171 (setq next-replacement
1172 (read-input "Edit replacement string: "
1173 next-replacement))
1174 (or replaced
1175 (replace-match next-replacement nocasify literal))
1176 (setq done t))
1178 ((eq def 'delete-and-edit)
1179 (delete-region (match-beginning 0) (match-end 0))
1180 (set-match-data
1181 (prog1 (match-data)
1182 (save-excursion (recursive-edit))))
1183 (setq replaced t))
1184 ;; Note: we do not need to treat `exit-prefix'
1185 ;; specially here, since we reread
1186 ;; any unrecognized character.
1188 (setq this-command 'mode-exited)
1189 (setq keep-going nil)
1190 (setq unread-command-events
1191 (append (listify-key-sequence key)
1192 unread-command-events))
1193 (setq done t))))
1194 ;; Record previous position for ^ when we move on.
1195 ;; Change markers to numbers in the match data
1196 ;; since lots of markers slow down editing.
1197 (setq stack
1198 (cons (cons (point)
1199 (or replaced (match-data t)))
1200 stack))))))
1202 ;; The code preventing adjacent regexp matches in the condition
1203 ;; of the while-loop above will haven taken us one character
1204 ;; beyond the last replacement. Undo that.
1205 (when (and regexp-flag (not match-again) (> replace-count 0))
1206 (backward-char 1))
1208 (replace-dehighlight))
1209 (or unread-command-events
1210 (message "Replaced %d occurrence%s"
1211 replace-count
1212 (if (= replace-count 1) "" "s")))
1213 (and keep-going stack)))
1215 (defcustom query-replace-highlight t
1216 "*Non-nil means to highlight words during query replacement."
1217 :type 'boolean
1218 :group 'matching)
1220 (defvar replace-overlay nil)
1222 (defun replace-dehighlight ()
1223 (and replace-overlay
1224 (progn
1225 (delete-overlay replace-overlay)
1226 (setq replace-overlay nil))))
1228 (defun replace-highlight (start end)
1229 (and query-replace-highlight
1230 (progn
1231 (or replace-overlay
1232 (progn
1233 (setq replace-overlay (make-overlay start end))
1234 (overlay-put replace-overlay 'face
1235 (if (facep 'query-replace)
1236 'query-replace 'region))))
1237 (move-overlay replace-overlay start end (current-buffer)))))
1239 ;;; replace.el ends here