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