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