* lisp/replace.el (replace-eval-replacement): Try to give more helpful error
[bpt/emacs.git] / lisp / replace.el
1 ;;; replace.el --- replace commands for Emacs
2
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2013
4 ;; Free Software Foundation, Inc.
5
6 ;; Maintainer: FSF
7 ;; Package: emacs
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; This package supplies the string and regular-expression replace functions
27 ;; documented in the Emacs user's manual.
28
29 ;;; Code:
30
31 (defcustom case-replace t
32 "Non-nil means `query-replace' should preserve case in replacements."
33 :type 'boolean
34 :group 'matching)
35
36 (defcustom replace-lax-whitespace nil
37 "Non-nil means `query-replace' matches a sequence of whitespace chars.
38 When you enter a space or spaces in the strings to be replaced,
39 it will match any sequence matched by the regexp `search-whitespace-regexp'."
40 :type 'boolean
41 :group 'matching
42 :version "24.3")
43
44 (defcustom replace-regexp-lax-whitespace nil
45 "Non-nil means `query-replace-regexp' matches a sequence of whitespace chars.
46 When you enter a space or spaces in the regexps to be replaced,
47 it will match any sequence matched by the regexp `search-whitespace-regexp'."
48 :type 'boolean
49 :group 'matching
50 :version "24.3")
51
52 (defvar query-replace-history nil
53 "Default history list for query-replace commands.
54 See `query-replace-from-history-variable' and
55 `query-replace-to-history-variable'.")
56
57 (defvar query-replace-defaults nil
58 "Default values of FROM-STRING and TO-STRING for `query-replace'.
59 This is a cons cell (FROM-STRING . TO-STRING), or nil if there is
60 no default value.")
61
62 (defvar query-replace-interactive nil
63 "Non-nil means `query-replace' uses the last search string.
64 That becomes the \"string to replace\".")
65 (make-obsolete-variable 'query-replace-interactive
66 "use `M-n' to pull the last incremental search string
67 to the minibuffer that reads the string to replace, or invoke replacements
68 from Isearch by using a key sequence like `C-s C-s M-%'." "24.3")
69
70 (defcustom query-replace-from-history-variable 'query-replace-history
71 "History list to use for the FROM argument of `query-replace' commands.
72 The value of this variable should be a symbol; that symbol
73 is used as a variable to hold a history list for the strings
74 or patterns to be replaced."
75 :group 'matching
76 :type 'symbol
77 :version "20.3")
78
79 (defcustom query-replace-to-history-variable 'query-replace-history
80 "History list to use for the TO argument of `query-replace' commands.
81 The value of this variable should be a symbol; that symbol
82 is used as a variable to hold a history list for replacement
83 strings or patterns."
84 :group 'matching
85 :type 'symbol
86 :version "20.3")
87
88 (defcustom query-replace-skip-read-only nil
89 "Non-nil means `query-replace' and friends ignore read-only matches."
90 :type 'boolean
91 :group 'matching
92 :version "22.1")
93
94 (defcustom query-replace-show-replacement t
95 "Non-nil means to show what actual replacement text will be."
96 :type 'boolean
97 :group 'matching
98 :version "23.1")
99
100 (defcustom query-replace-highlight t
101 "Non-nil means to highlight matches during query replacement."
102 :type 'boolean
103 :group 'matching)
104
105 (defcustom query-replace-lazy-highlight t
106 "Controls the lazy-highlighting during query replacements.
107 When non-nil, all text in the buffer matching the current match
108 is highlighted lazily using isearch lazy highlighting (see
109 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
110 :type 'boolean
111 :group 'lazy-highlight
112 :group 'matching
113 :version "22.1")
114
115 (defface query-replace
116 '((t (:inherit isearch)))
117 "Face for highlighting query replacement matches."
118 :group 'matching
119 :version "22.1")
120
121 (defvar replace-count 0
122 "Number of replacements done so far.
123 See `replace-regexp' and `query-replace-regexp-eval'.")
124
125 (defun query-replace-descr (string)
126 (mapconcat 'isearch-text-char-description string ""))
127
128 (defun query-replace-read-from (prompt regexp-flag)
129 "Query and return the `from' argument of a query-replace operation.
130 The return value can also be a pair (FROM . TO) indicating that the user
131 wants to replace FROM with TO."
132 (if query-replace-interactive
133 (car (if regexp-flag regexp-search-ring search-ring))
134 (let* ((history-add-new-input nil)
135 (prompt
136 (if query-replace-defaults
137 (format "%s (default %s -> %s): " prompt
138 (query-replace-descr (car query-replace-defaults))
139 (query-replace-descr (cdr query-replace-defaults)))
140 (format "%s: " prompt)))
141 (from
142 ;; The save-excursion here is in case the user marks and copies
143 ;; a region in order to specify the minibuffer input.
144 ;; That should not clobber the region for the query-replace itself.
145 (save-excursion
146 (if regexp-flag
147 (read-regexp prompt nil query-replace-from-history-variable)
148 (read-from-minibuffer
149 prompt nil nil nil query-replace-from-history-variable
150 (car (if regexp-flag regexp-search-ring search-ring)) t)))))
151 (if (and (zerop (length from)) query-replace-defaults)
152 (cons (car query-replace-defaults)
153 (query-replace-compile-replacement
154 (cdr query-replace-defaults) regexp-flag))
155 (add-to-history query-replace-from-history-variable from nil t)
156 ;; Warn if user types \n or \t, but don't reject the input.
157 (and regexp-flag
158 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
159 (let ((match (match-string 3 from)))
160 (cond
161 ((string= match "\\n")
162 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
163 ((string= match "\\t")
164 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
165 (sit-for 2)))
166 from))))
167
168 (defun query-replace-compile-replacement (to regexp-flag)
169 "Maybe convert a regexp replacement TO to Lisp.
170 Returns a list suitable for `perform-replace' if necessary,
171 the original string if not."
172 (if (and regexp-flag
173 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
174 (let (pos list char)
175 (while
176 (progn
177 (setq pos (match-end 0))
178 (push (substring to 0 (- pos 2)) list)
179 (setq char (aref to (1- pos))
180 to (substring to pos))
181 (cond ((eq char ?\#)
182 (push '(number-to-string replace-count) list))
183 ((eq char ?\,)
184 (setq pos (read-from-string to))
185 (push `(replace-quote ,(car pos)) list)
186 (let ((end
187 ;; Swallow a space after a symbol
188 ;; if there is a space.
189 (if (and (or (symbolp (car pos))
190 ;; Swallow a space after 'foo
191 ;; but not after (quote foo).
192 (and (eq (car-safe (car pos)) 'quote)
193 (not (= ?\( (aref to 0)))))
194 (eq (string-match " " to (cdr pos))
195 (cdr pos)))
196 (1+ (cdr pos))
197 (cdr pos))))
198 (setq to (substring to end)))))
199 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
200 (setq to (nreverse (delete "" (cons to list))))
201 (replace-match-string-symbols to)
202 (cons 'replace-eval-replacement
203 (if (cdr to)
204 (cons 'concat to)
205 (car to))))
206 to))
207
208
209 (defun query-replace-read-to (from prompt regexp-flag)
210 "Query and return the `to' argument of a query-replace operation."
211 (query-replace-compile-replacement
212 (save-excursion
213 (let* ((history-add-new-input nil)
214 (to (read-from-minibuffer
215 (format "%s %s with: " prompt (query-replace-descr from))
216 nil nil nil
217 query-replace-to-history-variable from t)))
218 (add-to-history query-replace-to-history-variable to nil t)
219 (setq query-replace-defaults (cons from to))
220 to))
221 regexp-flag))
222
223 (defun query-replace-read-args (prompt regexp-flag &optional noerror)
224 (unless noerror
225 (barf-if-buffer-read-only))
226 (let* ((from (query-replace-read-from prompt regexp-flag))
227 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
228 (query-replace-read-to from prompt regexp-flag))))
229 (list from to current-prefix-arg)))
230
231 (defun query-replace (from-string to-string &optional delimited start end)
232 "Replace some occurrences of FROM-STRING with TO-STRING.
233 As each match is found, the user must type a character saying
234 what to do with it. For directions, type \\[help-command] at that time.
235
236 In Transient Mark mode, if the mark is active, operate on the contents
237 of the region. Otherwise, operate from point to the end of the buffer.
238
239 Use \\<minibuffer-local-map>\\[next-history-element] \
240 to pull the last incremental search string to the minibuffer
241 that reads FROM-STRING, or invoke replacements from
242 incremental search with a key sequence like `C-s C-s M-%'
243 to use its current search string as the string to replace.
244
245 Matching is independent of case if `case-fold-search' is non-nil and
246 FROM-STRING has no uppercase letters. Replacement transfers the case
247 pattern of the old text to the new text, if `case-replace' and
248 `case-fold-search' are non-nil and FROM-STRING has no uppercase
249 letters. (Transferring the case pattern means that if the old text
250 matched is all caps, or capitalized, then its replacement is upcased
251 or capitalized.)
252
253 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
254 ignore hidden matches if `search-invisible' is nil, and ignore more
255 matches using `isearch-filter-predicate'.
256
257 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
258 to be replaced will match a sequence of whitespace chars defined by the
259 regexp in `search-whitespace-regexp'.
260
261 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
262 only matches surrounded by word boundaries.
263 Fourth and fifth arg START and END specify the region to operate on.
264
265 To customize possible responses, change the \"bindings\" in `query-replace-map'."
266 (interactive
267 (let ((common
268 (query-replace-read-args
269 (concat "Query replace"
270 (if current-prefix-arg " word" "")
271 (if (and transient-mark-mode mark-active) " in region" ""))
272 nil)))
273 (list (nth 0 common) (nth 1 common) (nth 2 common)
274 ;; These are done separately here
275 ;; so that command-history will record these expressions
276 ;; rather than the values they had this time.
277 (if (and transient-mark-mode mark-active)
278 (region-beginning))
279 (if (and transient-mark-mode mark-active)
280 (region-end)))))
281 (perform-replace from-string to-string t nil delimited nil nil start end))
282
283 (define-key esc-map "%" 'query-replace)
284
285 (defun query-replace-regexp (regexp to-string &optional delimited start end)
286 "Replace some things after point matching REGEXP with TO-STRING.
287 As each match is found, the user must type a character saying
288 what to do with it. For directions, type \\[help-command] at that time.
289
290 In Transient Mark mode, if the mark is active, operate on the contents
291 of the region. Otherwise, operate from point to the end of the buffer.
292
293 Use \\<minibuffer-local-map>\\[next-history-element] \
294 to pull the last incremental search regexp to the minibuffer
295 that reads REGEXP, or invoke replacements from
296 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
297 to use its current search regexp as the regexp to replace.
298
299 Matching is independent of case if `case-fold-search' is non-nil and
300 REGEXP has no uppercase letters. Replacement transfers the case
301 pattern of the old text to the new text, if `case-replace' and
302 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
303 \(Transferring the case pattern means that if the old text matched is
304 all caps, or capitalized, then its replacement is upcased or
305 capitalized.)
306
307 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
308 ignore hidden matches if `search-invisible' is nil, and ignore more
309 matches using `isearch-filter-predicate'.
310
311 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
312 to be replaced will match a sequence of whitespace chars defined by the
313 regexp in `search-whitespace-regexp'.
314
315 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
316 only matches surrounded by word boundaries.
317 Fourth and fifth arg START and END specify the region to operate on.
318
319 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
320 and `\\=\\N' (where N is a digit) stands for
321 whatever what matched the Nth `\\(...\\)' in REGEXP.
322 `\\?' lets you edit the replacement text in the minibuffer
323 at the given position for each replacement.
324
325 In interactive calls, the replacement text can contain `\\,'
326 followed by a Lisp expression. Each
327 replacement evaluates that expression to compute the replacement
328 string. Inside of that expression, `\\&' is a string denoting the
329 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
330 for the whole or a partial match converted to a number with
331 `string-to-number', and `\\#' itself for the number of replacements
332 done so far (starting with zero).
333
334 If the replacement expression is a symbol, write a space after it
335 to terminate it. One space there, if any, will be discarded.
336
337 When using those Lisp features interactively in the replacement
338 text, TO-STRING is actually made a list instead of a string.
339 Use \\[repeat-complex-command] after this command for details."
340 (interactive
341 (let ((common
342 (query-replace-read-args
343 (concat "Query replace"
344 (if current-prefix-arg " word" "")
345 " regexp"
346 (if (and transient-mark-mode mark-active) " in region" ""))
347 t)))
348 (list (nth 0 common) (nth 1 common) (nth 2 common)
349 ;; These are done separately here
350 ;; so that command-history will record these expressions
351 ;; rather than the values they had this time.
352 (if (and transient-mark-mode mark-active)
353 (region-beginning))
354 (if (and transient-mark-mode mark-active)
355 (region-end)))))
356 (perform-replace regexp to-string t t delimited nil nil start end))
357
358 (define-key esc-map [?\C-%] 'query-replace-regexp)
359
360 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
361 "Replace some things after point matching REGEXP with the result of TO-EXPR.
362
363 Interactive use of this function is deprecated in favor of the
364 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
365 using `search-forward-regexp' and `replace-match' is preferred.
366
367 As each match is found, the user must type a character saying
368 what to do with it. For directions, type \\[help-command] at that time.
369
370 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
371 reference `replace-count' to get the number of replacements already made.
372 If the result of TO-EXPR is not a string, it is converted to one using
373 `prin1-to-string' with the NOESCAPE argument (which see).
374
375 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
376 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
377 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
378 Use `\\#&' or `\\#N' if you want a number instead of a string.
379 In interactive use, `\\#' in itself stands for `replace-count'.
380
381 In Transient Mark mode, if the mark is active, operate on the contents
382 of the region. Otherwise, operate from point to the end of the buffer.
383
384 Use \\<minibuffer-local-map>\\[next-history-element] \
385 to pull the last incremental search regexp to the minibuffer
386 that reads REGEXP.
387
388 Preserves case in each replacement if `case-replace' and `case-fold-search'
389 are non-nil and REGEXP has no uppercase letters.
390
391 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
392 ignore hidden matches if `search-invisible' is nil, and ignore more
393 matches using `isearch-filter-predicate'.
394
395 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
396 to be replaced will match a sequence of whitespace chars defined by the
397 regexp in `search-whitespace-regexp'.
398
399 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
400 only matches that are surrounded by word boundaries.
401 Fourth and fifth arg START and END specify the region to operate on."
402 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
403 for interactive calls, and `search-forward-regexp'/`replace-match'
404 for Lisp calls." "22.1"))
405 (interactive
406 (progn
407 (barf-if-buffer-read-only)
408 (let* ((from
409 ;; Let-bind the history var to disable the "foo -> bar"
410 ;; default. Maybe we shouldn't disable this default, but
411 ;; for now I'll leave it off. --Stef
412 (let ((query-replace-to-history-variable nil))
413 (query-replace-read-from "Query replace regexp" t)))
414 (to (list (read-from-minibuffer
415 (format "Query replace regexp %s with eval: "
416 (query-replace-descr from))
417 nil nil t query-replace-to-history-variable from t))))
418 ;; We make TO a list because replace-match-string-symbols requires one,
419 ;; and the user might enter a single token.
420 (replace-match-string-symbols to)
421 (list from (car to) current-prefix-arg
422 (if (and transient-mark-mode mark-active)
423 (region-beginning))
424 (if (and transient-mark-mode mark-active)
425 (region-end))))))
426 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
427 t 'literal delimited nil nil start end))
428
429 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
430 "Replace some matches for REGEXP with various strings, in rotation.
431 The second argument TO-STRINGS contains the replacement strings, separated
432 by spaces. This command works like `query-replace-regexp' except that
433 each successive replacement uses the next successive replacement string,
434 wrapping around from the last such string to the first.
435
436 In Transient Mark mode, if the mark is active, operate on the contents
437 of the region. Otherwise, operate from point to the end of the buffer.
438
439 Non-interactively, TO-STRINGS may be a list of replacement strings.
440
441 Use \\<minibuffer-local-map>\\[next-history-element] \
442 to pull the last incremental search regexp to the minibuffer
443 that reads REGEXP.
444
445 A prefix argument N says to use each replacement string N times
446 before rotating to the next.
447 Fourth and fifth arg START and END specify the region to operate on."
448 (interactive
449 (let* ((from (read-regexp "Map query replace (regexp): " nil
450 query-replace-from-history-variable))
451 (to (read-from-minibuffer
452 (format "Query replace %s with (space-separated strings): "
453 (query-replace-descr from))
454 nil nil nil
455 query-replace-to-history-variable from t)))
456 (list from to
457 (and current-prefix-arg
458 (prefix-numeric-value current-prefix-arg))
459 (if (and transient-mark-mode mark-active)
460 (region-beginning))
461 (if (and transient-mark-mode mark-active)
462 (region-end)))))
463 (let (replacements)
464 (if (listp to-strings)
465 (setq replacements to-strings)
466 (while (/= (length to-strings) 0)
467 (if (string-match " " to-strings)
468 (setq replacements
469 (append replacements
470 (list (substring to-strings 0
471 (string-match " " to-strings))))
472 to-strings (substring to-strings
473 (1+ (string-match " " to-strings))))
474 (setq replacements (append replacements (list to-strings))
475 to-strings ""))))
476 (perform-replace regexp replacements t t nil n nil start end)))
477
478 (defun replace-string (from-string to-string &optional delimited start end)
479 "Replace occurrences of FROM-STRING with TO-STRING.
480 Preserve case in each match if `case-replace' and `case-fold-search'
481 are non-nil and FROM-STRING has no uppercase letters.
482 \(Preserving case means that if the string matched is all caps, or capitalized,
483 then its replacement is upcased or capitalized.)
484
485 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
486 ignore hidden matches if `search-invisible' is nil, and ignore more
487 matches using `isearch-filter-predicate'.
488
489 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
490 to be replaced will match a sequence of whitespace chars defined by the
491 regexp in `search-whitespace-regexp'.
492
493 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
494 only matches surrounded by word boundaries.
495
496 Operates on the region between START and END (if both are nil, from point
497 to the end of the buffer). Interactively, if Transient Mark mode is
498 enabled and the mark is active, operates on the contents of the region;
499 otherwise from point to the end of the buffer.
500
501 Use \\<minibuffer-local-map>\\[next-history-element] \
502 to pull the last incremental search string to the minibuffer
503 that reads FROM-STRING.
504
505 This function is usually the wrong thing to use in a Lisp program.
506 What you probably want is a loop like this:
507 (while (search-forward FROM-STRING nil t)
508 (replace-match TO-STRING nil t))
509 which will run faster and will not set the mark or print anything.
510 \(You may need a more complex loop if FROM-STRING can match the null string
511 and TO-STRING is also null.)"
512 (interactive
513 (let ((common
514 (query-replace-read-args
515 (concat "Replace"
516 (if current-prefix-arg " word" "")
517 " string"
518 (if (and transient-mark-mode mark-active) " in region" ""))
519 nil)))
520 (list (nth 0 common) (nth 1 common) (nth 2 common)
521 (if (and transient-mark-mode mark-active)
522 (region-beginning))
523 (if (and transient-mark-mode mark-active)
524 (region-end)))))
525 (perform-replace from-string to-string nil nil delimited nil nil start end))
526
527 (defun replace-regexp (regexp to-string &optional delimited start end)
528 "Replace things after point matching REGEXP with TO-STRING.
529 Preserve case in each match if `case-replace' and `case-fold-search'
530 are non-nil and REGEXP has no uppercase letters.
531
532 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
533 ignore hidden matches if `search-invisible' is nil, and ignore more
534 matches using `isearch-filter-predicate'.
535
536 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
537 to be replaced will match a sequence of whitespace chars defined by the
538 regexp in `search-whitespace-regexp'.
539
540 In Transient Mark mode, if the mark is active, operate on the contents
541 of the region. Otherwise, operate from point to the end of the buffer.
542
543 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
544 only matches surrounded by word boundaries.
545 Fourth and fifth arg START and END specify the region to operate on.
546
547 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
548 and `\\=\\N' (where N is a digit) stands for
549 whatever what matched the Nth `\\(...\\)' in REGEXP.
550 `\\?' lets you edit the replacement text in the minibuffer
551 at the given position for each replacement.
552
553 In interactive calls, the replacement text may contain `\\,'
554 followed by a Lisp expression used as part of the replacement
555 text. Inside of that expression, `\\&' is a string denoting the
556 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
557 numeric values from `string-to-number', and `\\#' itself for
558 `replace-count', the number of replacements occurred so far.
559
560 If your Lisp expression is an identifier and the next letter in
561 the replacement string would be interpreted as part of it, you
562 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
563 for this particular case you may also enter `\\#' in the
564 replacement text directly.
565
566 When using those Lisp features interactively in the replacement
567 text, TO-STRING is actually made a list instead of a string.
568 Use \\[repeat-complex-command] after this command for details.
569
570 Use \\<minibuffer-local-map>\\[next-history-element] \
571 to pull the last incremental search regexp to the minibuffer
572 that reads REGEXP.
573
574 This function is usually the wrong thing to use in a Lisp program.
575 What you probably want is a loop like this:
576 (while (re-search-forward REGEXP nil t)
577 (replace-match TO-STRING nil nil))
578 which will run faster and will not set the mark or print anything."
579 (interactive
580 (let ((common
581 (query-replace-read-args
582 (concat "Replace"
583 (if current-prefix-arg " word" "")
584 " regexp"
585 (if (and transient-mark-mode mark-active) " in region" ""))
586 t)))
587 (list (nth 0 common) (nth 1 common) (nth 2 common)
588 (if (and transient-mark-mode mark-active)
589 (region-beginning))
590 (if (and transient-mark-mode mark-active)
591 (region-end)))))
592 (perform-replace regexp to-string nil t delimited nil nil start end))
593
594 \f
595 (defvar regexp-history nil
596 "History list for some commands that read regular expressions.
597
598 Maximum length of the history list is determined by the value
599 of `history-length', which see.")
600
601 (defvar occur-collect-regexp-history '("\\1")
602 "History of regexp for occur's collect operation")
603
604 (defun read-regexp (prompt &optional defaults history)
605 "Read and return a regular expression as a string.
606 When PROMPT doesn't end with a colon and space, it adds a final \": \".
607 If the first element of DEFAULTS is non-nil, it's added to the prompt.
608
609 Optional arg DEFAULTS has the form (DEFAULT . SUGGESTIONS)
610 or simply DEFAULT where DEFAULT, if non-nil, should be a string that
611 is returned as the default value when the user enters empty input.
612 SUGGESTIONS is a list of strings that can be inserted into
613 the minibuffer using \\<minibuffer-local-map>\\[next-history-element]. \
614 The values supplied in SUGGESTIONS
615 are prepended to the list of standard suggestions that include
616 the tag at point, the last isearch regexp, the last isearch string,
617 and the last replacement regexp.
618
619 Optional arg HISTORY is a symbol to use for the history list.
620 If HISTORY is nil, `regexp-history' is used."
621 (let* ((default (if (consp defaults) (car defaults) defaults))
622 (suggestions (if (listp defaults) defaults (list defaults)))
623 (suggestions
624 (append
625 suggestions
626 (list
627 (find-tag-default-as-regexp)
628 (car regexp-search-ring)
629 (regexp-quote (or (car search-ring) ""))
630 (car (symbol-value query-replace-from-history-variable)))))
631 (suggestions (delete-dups (delq nil (delete "" suggestions))))
632 ;; Do not automatically add default to the history for empty input.
633 (history-add-new-input nil)
634 (input (read-from-minibuffer
635 (cond ((string-match-p ":[ \t]*\\'" prompt)
636 prompt)
637 (default
638 (format "%s (default %s): " prompt
639 (query-replace-descr default)))
640 (t
641 (format "%s: " prompt)))
642 nil nil nil (or history 'regexp-history) suggestions t)))
643 (if (equal input "")
644 ;; Return the default value when the user enters empty input.
645 (or default input)
646 ;; Otherwise, add non-empty input to the history and return input.
647 (prog1 input
648 (add-to-history (or history 'regexp-history) input)))))
649
650
651 (defalias 'delete-non-matching-lines 'keep-lines)
652 (defalias 'delete-matching-lines 'flush-lines)
653 (defalias 'count-matches 'how-many)
654
655
656 (defun keep-lines-read-args (prompt)
657 "Read arguments for `keep-lines' and friends.
658 Prompt for a regexp with PROMPT.
659 Value is a list, (REGEXP)."
660 (list (read-regexp prompt) nil nil t))
661
662 (defun keep-lines (regexp &optional rstart rend interactive)
663 "Delete all lines except those containing matches for REGEXP.
664 A match split across lines preserves all the lines it lies in.
665 When called from Lisp (and usually interactively as well, see below)
666 applies to all lines starting after point.
667
668 If REGEXP contains upper case characters (excluding those preceded by `\\')
669 and `search-upper-case' is non-nil, the matching is case-sensitive.
670
671 Second and third arg RSTART and REND specify the region to operate on.
672 This command operates on (the accessible part of) all lines whose
673 accessible part is entirely contained in the region determined by RSTART
674 and REND. (A newline ending a line counts as part of that line.)
675
676 Interactively, in Transient Mark mode when the mark is active, operate
677 on all lines whose accessible part is entirely contained in the region.
678 Otherwise, the command applies to all lines starting after point.
679 When calling this function from Lisp, you can pretend that it was
680 called interactively by passing a non-nil INTERACTIVE argument.
681
682 This function starts looking for the next match from the end of
683 the previous match. Hence, it ignores matches that overlap
684 a previously found match."
685
686 (interactive
687 (progn
688 (barf-if-buffer-read-only)
689 (keep-lines-read-args "Keep lines containing match for regexp")))
690 (if rstart
691 (progn
692 (goto-char (min rstart rend))
693 (setq rend
694 (progn
695 (save-excursion
696 (goto-char (max rstart rend))
697 (unless (or (bolp) (eobp))
698 (forward-line 0))
699 (point-marker)))))
700 (if (and interactive transient-mark-mode mark-active)
701 (setq rstart (region-beginning)
702 rend (progn
703 (goto-char (region-end))
704 (unless (or (bolp) (eobp))
705 (forward-line 0))
706 (point-marker)))
707 (setq rstart (point)
708 rend (point-max-marker)))
709 (goto-char rstart))
710 (save-excursion
711 (or (bolp) (forward-line 1))
712 (let ((start (point))
713 (case-fold-search
714 (if (and case-fold-search search-upper-case)
715 (isearch-no-upper-case-p regexp t)
716 case-fold-search)))
717 (while (< (point) rend)
718 ;; Start is first char not preserved by previous match.
719 (if (not (re-search-forward regexp rend 'move))
720 (delete-region start rend)
721 (let ((end (save-excursion (goto-char (match-beginning 0))
722 (forward-line 0)
723 (point))))
724 ;; Now end is first char preserved by the new match.
725 (if (< start end)
726 (delete-region start end))))
727
728 (setq start (save-excursion (forward-line 1) (point)))
729 ;; If the match was empty, avoid matching again at same place.
730 (and (< (point) rend)
731 (= (match-beginning 0) (match-end 0))
732 (forward-char 1)))))
733 (set-marker rend nil)
734 nil)
735
736
737 (defun flush-lines (regexp &optional rstart rend interactive)
738 "Delete lines containing matches for REGEXP.
739 When called from Lisp (and usually when called interactively as
740 well, see below), applies to the part of the buffer after point.
741 The line point is in is deleted if and only if it contains a
742 match for regexp starting after point.
743
744 If REGEXP contains upper case characters (excluding those preceded by `\\')
745 and `search-upper-case' is non-nil, the matching is case-sensitive.
746
747 Second and third arg RSTART and REND specify the region to operate on.
748 Lines partially contained in this region are deleted if and only if
749 they contain a match entirely contained in it.
750
751 Interactively, in Transient Mark mode when the mark is active, operate
752 on the contents of the region. Otherwise, operate from point to the
753 end of (the accessible portion of) the buffer. When calling this function
754 from Lisp, you can pretend that it was called interactively by passing
755 a non-nil INTERACTIVE argument.
756
757 If a match is split across lines, all the lines it lies in are deleted.
758 They are deleted _before_ looking for the next match. Hence, a match
759 starting on the same line at which another match ended is ignored."
760
761 (interactive
762 (progn
763 (barf-if-buffer-read-only)
764 (keep-lines-read-args "Flush lines containing match for regexp")))
765 (if rstart
766 (progn
767 (goto-char (min rstart rend))
768 (setq rend (copy-marker (max rstart rend))))
769 (if (and interactive transient-mark-mode mark-active)
770 (setq rstart (region-beginning)
771 rend (copy-marker (region-end)))
772 (setq rstart (point)
773 rend (point-max-marker)))
774 (goto-char rstart))
775 (let ((case-fold-search
776 (if (and case-fold-search search-upper-case)
777 (isearch-no-upper-case-p regexp t)
778 case-fold-search)))
779 (save-excursion
780 (while (and (< (point) rend)
781 (re-search-forward regexp rend t))
782 (delete-region (save-excursion (goto-char (match-beginning 0))
783 (forward-line 0)
784 (point))
785 (progn (forward-line 1) (point))))))
786 (set-marker rend nil)
787 nil)
788
789
790 (defun how-many (regexp &optional rstart rend interactive)
791 "Print and return number of matches for REGEXP following point.
792 When called from Lisp and INTERACTIVE is omitted or nil, just return
793 the number, do not print it; if INTERACTIVE is t, the function behaves
794 in all respects as if it had been called interactively.
795
796 If REGEXP contains upper case characters (excluding those preceded by `\\')
797 and `search-upper-case' is non-nil, the matching is case-sensitive.
798
799 Second and third arg RSTART and REND specify the region to operate on.
800
801 Interactively, in Transient Mark mode when the mark is active, operate
802 on the contents of the region. Otherwise, operate from point to the
803 end of (the accessible portion of) the buffer.
804
805 This function starts looking for the next match from the end of
806 the previous match. Hence, it ignores matches that overlap
807 a previously found match."
808
809 (interactive
810 (keep-lines-read-args "How many matches for regexp"))
811 (save-excursion
812 (if rstart
813 (if rend
814 (progn
815 (goto-char (min rstart rend))
816 (setq rend (max rstart rend)))
817 (goto-char rstart)
818 (setq rend (point-max)))
819 (if (and interactive transient-mark-mode mark-active)
820 (setq rstart (region-beginning)
821 rend (region-end))
822 (setq rstart (point)
823 rend (point-max)))
824 (goto-char rstart))
825 (let ((count 0)
826 opoint
827 (case-fold-search
828 (if (and case-fold-search search-upper-case)
829 (isearch-no-upper-case-p regexp t)
830 case-fold-search)))
831 (while (and (< (point) rend)
832 (progn (setq opoint (point))
833 (re-search-forward regexp rend t)))
834 (if (= opoint (point))
835 (forward-char 1)
836 (setq count (1+ count))))
837 (when interactive (message "%d occurrence%s"
838 count
839 (if (= count 1) "" "s")))
840 count)))
841
842 \f
843 (defvar occur-menu-map
844 (let ((map (make-sparse-keymap)))
845 (bindings--define-key map [next-error-follow-minor-mode]
846 '(menu-item "Auto Occurrence Display"
847 next-error-follow-minor-mode
848 :help "Display another occurrence when moving the cursor"
849 :button (:toggle . (and (boundp 'next-error-follow-minor-mode)
850 next-error-follow-minor-mode))))
851 (bindings--define-key map [separator-1] menu-bar-separator)
852 (bindings--define-key map [kill-this-buffer]
853 '(menu-item "Kill Occur Buffer" kill-this-buffer
854 :help "Kill the current *Occur* buffer"))
855 (bindings--define-key map [quit-window]
856 '(menu-item "Quit Occur Window" quit-window
857 :help "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
858 (bindings--define-key map [revert-buffer]
859 '(menu-item "Revert Occur Buffer" revert-buffer
860 :help "Replace the text in the *Occur* buffer with the results of rerunning occur"))
861 (bindings--define-key map [clone-buffer]
862 '(menu-item "Clone Occur Buffer" clone-buffer
863 :help "Create and return a twin copy of the current *Occur* buffer"))
864 (bindings--define-key map [occur-rename-buffer]
865 '(menu-item "Rename Occur Buffer" occur-rename-buffer
866 :help "Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
867 (bindings--define-key map [occur-edit-buffer]
868 '(menu-item "Edit Occur Buffer" occur-edit-mode
869 :help "Edit the *Occur* buffer and apply changes to the original buffers."))
870 (bindings--define-key map [separator-2] menu-bar-separator)
871 (bindings--define-key map [occur-mode-goto-occurrence-other-window]
872 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
873 :help "Go to the occurrence the current line describes, in another window"))
874 (bindings--define-key map [occur-mode-goto-occurrence]
875 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
876 :help "Go to the occurrence the current line describes"))
877 (bindings--define-key map [occur-mode-display-occurrence]
878 '(menu-item "Display Occurrence" occur-mode-display-occurrence
879 :help "Display in another window the occurrence the current line describes"))
880 (bindings--define-key map [occur-next]
881 '(menu-item "Move to Next Match" occur-next
882 :help "Move to the Nth (default 1) next match in an Occur mode buffer"))
883 (bindings--define-key map [occur-prev]
884 '(menu-item "Move to Previous Match" occur-prev
885 :help "Move to the Nth (default 1) previous match in an Occur mode buffer"))
886 map)
887 "Menu keymap for `occur-mode'.")
888
889 (defvar occur-mode-map
890 (let ((map (make-sparse-keymap)))
891 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
892 (define-key map [mouse-2] 'occur-mode-mouse-goto)
893 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
894 (define-key map "e" 'occur-edit-mode)
895 (define-key map "\C-m" 'occur-mode-goto-occurrence)
896 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
897 (define-key map "\C-o" 'occur-mode-display-occurrence)
898 (define-key map "\M-n" 'occur-next)
899 (define-key map "\M-p" 'occur-prev)
900 (define-key map "r" 'occur-rename-buffer)
901 (define-key map "c" 'clone-buffer)
902 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
903 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
904 map)
905 "Keymap for `occur-mode'.")
906
907 (defvar occur-revert-arguments nil
908 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
909 See `occur-revert-function'.")
910 (make-variable-buffer-local 'occur-revert-arguments)
911 (put 'occur-revert-arguments 'permanent-local t)
912
913 (defcustom occur-mode-hook '(turn-on-font-lock)
914 "Hook run when entering Occur mode."
915 :type 'hook
916 :group 'matching)
917
918 (defcustom occur-hook nil
919 "Hook run by Occur when there are any matches."
920 :type 'hook
921 :group 'matching)
922
923 (defcustom occur-mode-find-occurrence-hook nil
924 "Hook run by Occur after locating an occurrence.
925 This will be called with the cursor position at the occurrence. An application
926 for this is to reveal context in an outline-mode when the occurrence is hidden."
927 :type 'hook
928 :group 'matching)
929
930 (put 'occur-mode 'mode-class 'special)
931 (define-derived-mode occur-mode special-mode "Occur"
932 "Major mode for output from \\[occur].
933 \\<occur-mode-map>Move point to one of the items in this buffer, then use
934 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
935 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
936
937 \\{occur-mode-map}"
938 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
939 (setq next-error-function 'occur-next-error))
940
941 \f
942 ;;; Occur Edit mode
943
944 (defvar occur-edit-mode-map
945 (let ((map (make-sparse-keymap)))
946 (set-keymap-parent map text-mode-map)
947 (define-key map [mouse-2] 'occur-mode-mouse-goto)
948 (define-key map "\C-c\C-c" 'occur-cease-edit)
949 (define-key map "\C-o" 'occur-mode-display-occurrence)
950 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
951 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
952 map)
953 "Keymap for `occur-edit-mode'.")
954
955 (define-derived-mode occur-edit-mode occur-mode "Occur-Edit"
956 "Major mode for editing *Occur* buffers.
957 In this mode, changes to the *Occur* buffer are also applied to
958 the originating buffer.
959
960 To return to ordinary Occur mode, use \\[occur-cease-edit]."
961 (setq buffer-read-only nil)
962 (add-hook 'after-change-functions 'occur-after-change-function nil t)
963 (message (substitute-command-keys
964 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
965
966 (defun occur-cease-edit ()
967 "Switch from Occur Edit mode to Occur mode."
968 (interactive)
969 (when (derived-mode-p 'occur-edit-mode)
970 (occur-mode)
971 (message "Switching to Occur mode.")))
972
973 (defun occur-after-change-function (beg end length)
974 (save-excursion
975 (goto-char beg)
976 (let* ((line-beg (line-beginning-position))
977 (m (get-text-property line-beg 'occur-target))
978 (buf (marker-buffer m))
979 col)
980 (when (and (get-text-property line-beg 'occur-prefix)
981 (not (get-text-property end 'occur-prefix)))
982 (when (= length 0)
983 ;; Apply occur-target property to inserted (e.g. yanked) text.
984 (put-text-property beg end 'occur-target m)
985 ;; Did we insert a newline? Occur Edit mode can't create new
986 ;; Occur entries; just discard everything after the newline.
987 (save-excursion
988 (and (search-forward "\n" end t)
989 (delete-region (1- (point)) end))))
990 (let* ((line (- (line-number-at-pos)
991 (line-number-at-pos (window-start))))
992 (readonly (with-current-buffer buf buffer-read-only))
993 (win (or (get-buffer-window buf)
994 (display-buffer buf
995 '(nil (inhibit-same-window . t)
996 (inhibit-switch-frame . t)))))
997 (line-end (line-end-position))
998 (text (save-excursion
999 (goto-char (next-single-property-change
1000 line-beg 'occur-prefix nil
1001 line-end))
1002 (setq col (- (point) line-beg))
1003 (buffer-substring-no-properties (point) line-end))))
1004 (with-selected-window win
1005 (goto-char m)
1006 (recenter line)
1007 (if readonly
1008 (message "Buffer `%s' is read only." buf)
1009 (delete-region (line-beginning-position) (line-end-position))
1010 (insert text))
1011 (move-to-column col)))))))
1012
1013 \f
1014 (defun occur-revert-function (_ignore1 _ignore2)
1015 "Handle `revert-buffer' for Occur mode buffers."
1016 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
1017
1018 (defun occur-mode-find-occurrence ()
1019 (let ((pos (get-text-property (point) 'occur-target)))
1020 (unless pos
1021 (error "No occurrence on this line"))
1022 (unless (buffer-live-p (marker-buffer pos))
1023 (error "Buffer for this occurrence was killed"))
1024 pos))
1025
1026 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
1027 (defun occur-mode-goto-occurrence (&optional event)
1028 "Go to the occurrence on the current line."
1029 (interactive (list last-nonmenu-event))
1030 (let ((pos
1031 (if (null event)
1032 ;; Actually `event-end' works correctly with a nil argument as
1033 ;; well, so we could dispense with this test, but let's not
1034 ;; rely on this undocumented behavior.
1035 (occur-mode-find-occurrence)
1036 (with-current-buffer (window-buffer (posn-window (event-end event)))
1037 (save-excursion
1038 (goto-char (posn-point (event-end event)))
1039 (occur-mode-find-occurrence))))))
1040 (pop-to-buffer (marker-buffer pos))
1041 (goto-char pos)
1042 (run-hooks 'occur-mode-find-occurrence-hook)))
1043
1044 (defun occur-mode-goto-occurrence-other-window ()
1045 "Go to the occurrence the current line describes, in another window."
1046 (interactive)
1047 (let ((pos (occur-mode-find-occurrence)))
1048 (switch-to-buffer-other-window (marker-buffer pos))
1049 (goto-char pos)
1050 (run-hooks 'occur-mode-find-occurrence-hook)))
1051
1052 (defun occur-mode-display-occurrence ()
1053 "Display in another window the occurrence the current line describes."
1054 (interactive)
1055 (let ((pos (occur-mode-find-occurrence))
1056 window)
1057 (setq window (display-buffer (marker-buffer pos) t))
1058 ;; This is the way to set point in the proper window.
1059 (save-selected-window
1060 (select-window window)
1061 (goto-char pos)
1062 (run-hooks 'occur-mode-find-occurrence-hook))))
1063
1064 (defun occur-find-match (n search message)
1065 (if (not n) (setq n 1))
1066 (let ((r))
1067 (while (> n 0)
1068 (setq r (funcall search (point) 'occur-match))
1069 (and r
1070 (get-text-property r 'occur-match)
1071 (setq r (funcall search r 'occur-match)))
1072 (if r
1073 (goto-char r)
1074 (error message))
1075 (setq n (1- n)))))
1076
1077 (defun occur-next (&optional n)
1078 "Move to the Nth (default 1) next match in an Occur mode buffer."
1079 (interactive "p")
1080 (occur-find-match n #'next-single-property-change "No more matches"))
1081
1082 (defun occur-prev (&optional n)
1083 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1084 (interactive "p")
1085 (occur-find-match n #'previous-single-property-change "No earlier matches"))
1086
1087 (defun occur-next-error (&optional argp reset)
1088 "Move to the Nth (default 1) next match in an Occur mode buffer.
1089 Compatibility function for \\[next-error] invocations."
1090 (interactive "p")
1091 ;; we need to run occur-find-match from within the Occur buffer
1092 (with-current-buffer
1093 ;; Choose the buffer and make it current.
1094 (if (next-error-buffer-p (current-buffer))
1095 (current-buffer)
1096 (next-error-find-buffer nil nil
1097 (lambda ()
1098 (eq major-mode 'occur-mode))))
1099
1100 (goto-char (cond (reset (point-min))
1101 ((< argp 0) (line-beginning-position))
1102 ((> argp 0) (line-end-position))
1103 ((point))))
1104 (occur-find-match
1105 (abs argp)
1106 (if (> 0 argp)
1107 #'previous-single-property-change
1108 #'next-single-property-change)
1109 "No more matches")
1110 ;; In case the *Occur* buffer is visible in a nonselected window.
1111 (let ((win (get-buffer-window (current-buffer) t)))
1112 (if win (set-window-point win (point))))
1113 (occur-mode-goto-occurrence)))
1114 \f
1115 (defface match
1116 '((((class color) (min-colors 88) (background light))
1117 :background "yellow1")
1118 (((class color) (min-colors 88) (background dark))
1119 :background "RoyalBlue3")
1120 (((class color) (min-colors 8) (background light))
1121 :background "yellow" :foreground "black")
1122 (((class color) (min-colors 8) (background dark))
1123 :background "blue" :foreground "white")
1124 (((type tty) (class mono))
1125 :inverse-video t)
1126 (t :background "gray"))
1127 "Face used to highlight matches permanently."
1128 :group 'matching
1129 :version "22.1")
1130
1131 (defcustom list-matching-lines-default-context-lines 0
1132 "Default number of context lines included around `list-matching-lines' matches.
1133 A negative number means to include that many lines before the match.
1134 A positive number means to include that many lines both before and after."
1135 :type 'integer
1136 :group 'matching)
1137
1138 (defalias 'list-matching-lines 'occur)
1139
1140 (defcustom list-matching-lines-face 'match
1141 "Face used by \\[list-matching-lines] to show the text that matches.
1142 If the value is nil, don't highlight the matching portions specially."
1143 :type 'face
1144 :group 'matching)
1145
1146 (defcustom list-matching-lines-buffer-name-face 'underline
1147 "Face used by \\[list-matching-lines] to show the names of buffers.
1148 If the value is nil, don't highlight the buffer names specially."
1149 :type 'face
1150 :group 'matching)
1151
1152 (defcustom list-matching-lines-prefix-face 'shadow
1153 "Face used by \\[list-matching-lines] to show the prefix column.
1154 If the face doesn't differ from the default face,
1155 don't highlight the prefix with line numbers specially."
1156 :type 'face
1157 :group 'matching
1158 :version "24.4")
1159
1160 (defcustom occur-excluded-properties
1161 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1162 yank-handler follow-link)
1163 "Text properties to discard when copying lines to the *Occur* buffer.
1164 The value should be a list of text properties to discard or t,
1165 which means to discard all text properties."
1166 :type '(choice (const :tag "All" t) (repeat symbol))
1167 :group 'matching
1168 :version "22.1")
1169
1170 (defvar occur-read-regexp-defaults-function
1171 'occur-read-regexp-defaults
1172 "Function that provides default regexp(s) for occur commands.
1173 This function should take no arguments and return one of nil, a
1174 regexp or a list of regexps for use with occur commands -
1175 `occur', `multi-occur' and `multi-occur-in-matching-buffers'.
1176 The return value of this function is used as DEFAULTS param of
1177 `read-regexp' while executing the occur command. This function
1178 is called only during interactive use.
1179
1180 For example, to check for occurrence of symbol at point use
1181
1182 (setq occur-read-regexp-defaults-function
1183 'find-tag-default-as-regexp).")
1184
1185 (defun occur-read-regexp-defaults ()
1186 "Return the latest regexp from `regexp-history'.
1187 See `occur-read-regexp-defaults-function' for details."
1188 (car regexp-history))
1189
1190 (defun occur-read-primary-args ()
1191 (let* ((perform-collect (consp current-prefix-arg))
1192 (regexp (read-regexp (if perform-collect
1193 "Collect strings matching regexp"
1194 "List lines matching regexp")
1195 (funcall occur-read-regexp-defaults-function))))
1196 (list regexp
1197 (if perform-collect
1198 ;; Perform collect operation
1199 (if (zerop (regexp-opt-depth regexp))
1200 ;; No subexpression so collect the entire match.
1201 "\\&"
1202 ;; Get the regexp for collection pattern.
1203 (let ((default (car occur-collect-regexp-history)))
1204 (read-regexp
1205 (format "Regexp to collect (default %s): " default)
1206 default 'occur-collect-regexp-history)))
1207 ;; Otherwise normal occur takes numerical prefix argument.
1208 (when current-prefix-arg
1209 (prefix-numeric-value current-prefix-arg))))))
1210
1211 (defun occur-rename-buffer (&optional unique-p interactive-p)
1212 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1213 Here `original-buffer-name' is the buffer name where Occur was originally run.
1214 When given the prefix argument, or called non-interactively, the renaming
1215 will not clobber the existing buffer(s) of that name, but use
1216 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1217 if you always want a separate *Occur* buffer for each buffer where you
1218 invoke `occur'."
1219 (interactive "P\np")
1220 (with-current-buffer
1221 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1222 (rename-buffer (concat "*Occur: "
1223 (mapconcat #'buffer-name
1224 (car (cddr occur-revert-arguments)) "/")
1225 "*")
1226 (or unique-p (not interactive-p)))))
1227
1228 (defun occur (regexp &optional nlines)
1229 "Show all lines in the current buffer containing a match for REGEXP.
1230 If a match spreads across multiple lines, all those lines are shown.
1231
1232 Each line is displayed with NLINES lines before and after, or -NLINES
1233 before if NLINES is negative.
1234 NLINES defaults to `list-matching-lines-default-context-lines'.
1235 Interactively it is the prefix arg.
1236
1237 The lines are shown in a buffer named `*Occur*'.
1238 It serves as a menu to find any of the occurrences in this buffer.
1239 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1240
1241 If REGEXP contains upper case characters (excluding those preceded by `\\')
1242 and `search-upper-case' is non-nil, the matching is case-sensitive.
1243
1244 When NLINES is a string or when the function is called
1245 interactively with prefix argument without a number (`C-u' alone
1246 as prefix) the matching strings are collected into the `*Occur*'
1247 buffer by using NLINES as a replacement regexp. NLINES may
1248 contain \\& and \\N which convention follows `replace-match'.
1249 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1250 \"\\1\" for NLINES collects all the function names in a lisp
1251 program. When there is no parenthesized subexpressions in REGEXP
1252 the entire match is collected. In any case the searched buffer
1253 is not modified."
1254 (interactive (occur-read-primary-args))
1255 (occur-1 regexp nlines (list (current-buffer))))
1256
1257 (defvar ido-ignore-item-temp-list)
1258
1259 (defun multi-occur (bufs regexp &optional nlines)
1260 "Show all lines in buffers BUFS containing a match for REGEXP.
1261 This function acts on multiple buffers; otherwise, it is exactly like
1262 `occur'. When you invoke this command interactively, you must specify
1263 the buffer names that you want, one by one.
1264 See also `multi-occur-in-matching-buffers'."
1265 (interactive
1266 (cons
1267 (let* ((bufs (list (read-buffer "First buffer to search: "
1268 (current-buffer) t)))
1269 (buf nil)
1270 (ido-ignore-item-temp-list bufs))
1271 (while (not (string-equal
1272 (setq buf (read-buffer
1273 (if (eq read-buffer-function 'ido-read-buffer)
1274 "Next buffer to search (C-j to end): "
1275 "Next buffer to search (RET to end): ")
1276 nil t))
1277 ""))
1278 (add-to-list 'bufs buf)
1279 (setq ido-ignore-item-temp-list bufs))
1280 (nreverse (mapcar #'get-buffer bufs)))
1281 (occur-read-primary-args)))
1282 (occur-1 regexp nlines bufs))
1283
1284 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1285 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1286 Normally BUFREGEXP matches against each buffer's visited file name,
1287 but if you specify a prefix argument, it matches against the buffer name.
1288 See also `multi-occur'."
1289 (interactive
1290 (cons
1291 (let* ((default (car regexp-history))
1292 (input
1293 (read-regexp
1294 (if current-prefix-arg
1295 "List lines in buffers whose names match regexp: "
1296 "List lines in buffers whose filenames match regexp: "))))
1297 (if (equal input "")
1298 default
1299 input))
1300 (occur-read-primary-args)))
1301 (when bufregexp
1302 (occur-1 regexp nil
1303 (delq nil
1304 (mapcar (lambda (buf)
1305 (when (if allbufs
1306 (string-match bufregexp
1307 (buffer-name buf))
1308 (and (buffer-file-name buf)
1309 (string-match bufregexp
1310 (buffer-file-name buf))))
1311 buf))
1312 (buffer-list))))))
1313
1314 (defun occur-1 (regexp nlines bufs &optional buf-name)
1315 (unless (and regexp (not (equal regexp "")))
1316 (error "Occur doesn't work with the empty regexp"))
1317 (unless buf-name
1318 (setq buf-name "*Occur*"))
1319 (let (occur-buf
1320 (active-bufs (delq nil (mapcar #'(lambda (buf)
1321 (when (buffer-live-p buf) buf))
1322 bufs))))
1323 ;; Handle the case where one of the buffers we're searching is the
1324 ;; output buffer. Just rename it.
1325 (when (member buf-name (mapcar 'buffer-name active-bufs))
1326 (with-current-buffer (get-buffer buf-name)
1327 (rename-uniquely)))
1328
1329 ;; Now find or create the output buffer.
1330 ;; If we just renamed that buffer, we will make a new one here.
1331 (setq occur-buf (get-buffer-create buf-name))
1332
1333 (with-current-buffer occur-buf
1334 (if (stringp nlines)
1335 (fundamental-mode) ;; This is for collect operation.
1336 (occur-mode))
1337 (let ((inhibit-read-only t)
1338 ;; Don't generate undo entries for creation of the initial contents.
1339 (buffer-undo-list t))
1340 (erase-buffer)
1341 (let ((count
1342 (if (stringp nlines)
1343 ;; Treat nlines as a regexp to collect.
1344 (let ((bufs active-bufs)
1345 (count 0))
1346 (while bufs
1347 (with-current-buffer (car bufs)
1348 (save-excursion
1349 (goto-char (point-min))
1350 (while (re-search-forward regexp nil t)
1351 ;; Insert the replacement regexp.
1352 (let ((str (match-substitute-replacement nlines)))
1353 (if str
1354 (with-current-buffer occur-buf
1355 (insert str)
1356 (setq count (1+ count))
1357 (or (zerop (current-column))
1358 (insert "\n"))))))))
1359 (setq bufs (cdr bufs)))
1360 count)
1361 ;; Perform normal occur.
1362 (occur-engine
1363 regexp active-bufs occur-buf
1364 (or nlines list-matching-lines-default-context-lines)
1365 (if (and case-fold-search search-upper-case)
1366 (isearch-no-upper-case-p regexp t)
1367 case-fold-search)
1368 list-matching-lines-buffer-name-face
1369 (if (face-differs-from-default-p list-matching-lines-prefix-face)
1370 list-matching-lines-prefix-face)
1371 list-matching-lines-face
1372 (not (eq occur-excluded-properties t))))))
1373 (let* ((bufcount (length active-bufs))
1374 (diff (- (length bufs) bufcount)))
1375 (message "Searched %d buffer%s%s; %s match%s%s"
1376 bufcount (if (= bufcount 1) "" "s")
1377 (if (zerop diff) "" (format " (%d killed)" diff))
1378 (if (zerop count) "no" (format "%d" count))
1379 (if (= count 1) "" "es")
1380 ;; Don't display regexp if with remaining text
1381 ;; it is longer than window-width.
1382 (if (> (+ (length regexp) 42) (window-width))
1383 "" (format " for `%s'" (query-replace-descr regexp)))))
1384 (setq occur-revert-arguments (list regexp nlines bufs))
1385 (if (= count 0)
1386 (kill-buffer occur-buf)
1387 (display-buffer occur-buf)
1388 (setq next-error-last-buffer occur-buf)
1389 (setq buffer-read-only t)
1390 (set-buffer-modified-p nil)
1391 (run-hooks 'occur-hook)))))))
1392
1393 (defun occur-engine (regexp buffers out-buf nlines case-fold
1394 title-face prefix-face match-face keep-props)
1395 (with-current-buffer out-buf
1396 (let ((global-lines 0) ;; total count of matching lines
1397 (global-matches 0) ;; total count of matches
1398 (coding nil)
1399 (case-fold-search case-fold))
1400 ;; Map over all the buffers
1401 (dolist (buf buffers)
1402 (when (buffer-live-p buf)
1403 (let ((lines 0) ;; count of matching lines
1404 (matches 0) ;; count of matches
1405 (curr-line 1) ;; line count
1406 (prev-line nil) ;; line number of prev match endpt
1407 (prev-after-lines nil) ;; context lines of prev match
1408 (matchbeg 0)
1409 (origpt nil)
1410 (begpt nil)
1411 (endpt nil)
1412 (marker nil)
1413 (curstring "")
1414 (ret nil)
1415 (inhibit-field-text-motion t)
1416 (headerpt (with-current-buffer out-buf (point))))
1417 (with-current-buffer buf
1418 (or coding
1419 ;; Set CODING only if the current buffer locally
1420 ;; binds buffer-file-coding-system.
1421 (not (local-variable-p 'buffer-file-coding-system))
1422 (setq coding buffer-file-coding-system))
1423 (save-excursion
1424 (goto-char (point-min)) ;; begin searching in the buffer
1425 (while (not (eobp))
1426 (setq origpt (point))
1427 (when (setq endpt (re-search-forward regexp nil t))
1428 (setq lines (1+ lines)) ;; increment matching lines count
1429 (setq matchbeg (match-beginning 0))
1430 ;; Get beginning of first match line and end of the last.
1431 (save-excursion
1432 (goto-char matchbeg)
1433 (setq begpt (line-beginning-position))
1434 (goto-char endpt)
1435 (setq endpt (line-end-position)))
1436 ;; Sum line numbers up to the first match line.
1437 (setq curr-line (+ curr-line (count-lines origpt begpt)))
1438 (setq marker (make-marker))
1439 (set-marker marker matchbeg)
1440 (setq curstring (occur-engine-line begpt endpt keep-props))
1441 ;; Highlight the matches
1442 (let ((len (length curstring))
1443 (start 0))
1444 (while (and (< start len)
1445 (string-match regexp curstring start))
1446 (setq matches (1+ matches))
1447 (add-text-properties
1448 (match-beginning 0) (match-end 0)
1449 (append
1450 `(occur-match t)
1451 (when match-face
1452 ;; Use `face' rather than `font-lock-face' here
1453 ;; so as to override faces copied from the buffer.
1454 `(face ,match-face)))
1455 curstring)
1456 (setq start (match-end 0))))
1457 ;; Generate the string to insert for this match
1458 (let* ((match-prefix
1459 ;; Using 7 digits aligns tabs properly.
1460 (apply #'propertize (format "%7d:" curr-line)
1461 (append
1462 (when prefix-face
1463 `(font-lock-face ,prefix-face))
1464 `(occur-prefix t mouse-face (highlight)
1465 ;; Allow insertion of text at
1466 ;; the end of the prefix (for
1467 ;; Occur Edit mode).
1468 front-sticky t rear-nonsticky t
1469 occur-target ,marker follow-link t
1470 help-echo "mouse-2: go to this occurrence"))))
1471 (match-str
1472 ;; We don't put `mouse-face' on the newline,
1473 ;; because that loses. And don't put it
1474 ;; on context lines to reduce flicker.
1475 (propertize curstring 'mouse-face (list 'highlight)
1476 'occur-target marker
1477 'follow-link t
1478 'help-echo
1479 "mouse-2: go to this occurrence"))
1480 (out-line
1481 (concat
1482 match-prefix
1483 ;; Add non-numeric prefix to all non-first lines
1484 ;; of multi-line matches.
1485 (replace-regexp-in-string
1486 "\n"
1487 (if prefix-face
1488 (propertize "\n :" 'font-lock-face prefix-face)
1489 "\n :")
1490 match-str)
1491 ;; Add marker at eol, but no mouse props.
1492 (propertize "\n" 'occur-target marker)))
1493 (data
1494 (if (= nlines 0)
1495 ;; The simple display style
1496 out-line
1497 ;; The complex multi-line display style.
1498 (setq ret (occur-context-lines
1499 out-line nlines keep-props begpt endpt
1500 curr-line prev-line prev-after-lines
1501 prefix-face))
1502 ;; Set first elem of the returned list to `data',
1503 ;; and the second elem to `prev-after-lines'.
1504 (setq prev-after-lines (nth 1 ret))
1505 (nth 0 ret))))
1506 ;; Actually insert the match display data
1507 (with-current-buffer out-buf
1508 (insert data)))
1509 (goto-char endpt))
1510 (if endpt
1511 (progn
1512 ;; Sum line numbers between first and last match lines.
1513 (setq curr-line (+ curr-line (count-lines begpt endpt)
1514 ;; Add 1 for empty last match line since
1515 ;; count-lines returns 1 line less.
1516 (if (and (bolp) (eolp)) 1 0)))
1517 ;; On to the next match...
1518 (forward-line 1))
1519 (goto-char (point-max)))
1520 (setq prev-line (1- curr-line)))
1521 ;; Flush remaining context after-lines.
1522 (when prev-after-lines
1523 (with-current-buffer out-buf
1524 (insert (apply #'concat (occur-engine-add-prefix
1525 prev-after-lines prefix-face)))))))
1526 (when (not (zerop lines)) ;; is the count zero?
1527 (setq global-lines (+ global-lines lines)
1528 global-matches (+ global-matches matches))
1529 (with-current-buffer out-buf
1530 (goto-char headerpt)
1531 (let ((beg (point))
1532 end)
1533 (insert (propertize
1534 (format "%d match%s%s%s in buffer: %s\n"
1535 matches (if (= matches 1) "" "es")
1536 ;; Don't display the same number of lines
1537 ;; and matches in case of 1 match per line.
1538 (if (= lines matches)
1539 "" (format " in %d line%s"
1540 lines (if (= lines 1) "" "s")))
1541 ;; Don't display regexp for multi-buffer.
1542 (if (> (length buffers) 1)
1543 "" (format " for \"%s\""
1544 (query-replace-descr regexp)))
1545 (buffer-name buf))
1546 'read-only t))
1547 (setq end (point))
1548 (add-text-properties beg end
1549 (append
1550 (when title-face
1551 `(font-lock-face ,title-face))
1552 `(occur-title ,buf))))
1553 (goto-char (point-min)))))))
1554 ;; Display total match count and regexp for multi-buffer.
1555 (when (and (not (zerop global-lines)) (> (length buffers) 1))
1556 (goto-char (point-min))
1557 (let ((beg (point))
1558 end)
1559 (insert (format "%d match%s%s total for \"%s\":\n"
1560 global-matches (if (= global-matches 1) "" "es")
1561 ;; Don't display the same number of lines
1562 ;; and matches in case of 1 match per line.
1563 (if (= global-lines global-matches)
1564 "" (format " in %d line%s"
1565 global-lines (if (= global-lines 1) "" "s")))
1566 (query-replace-descr regexp)))
1567 (setq end (point))
1568 (add-text-properties beg end (when title-face
1569 `(font-lock-face ,title-face))))
1570 (goto-char (point-min)))
1571 (if coding
1572 ;; CODING is buffer-file-coding-system of the first buffer
1573 ;; that locally binds it. Let's use it also for the output
1574 ;; buffer.
1575 (set-buffer-file-coding-system coding))
1576 ;; Return the number of matches
1577 global-matches)))
1578
1579 (defun occur-engine-line (beg end &optional keep-props)
1580 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1581 (text-property-not-all beg end 'fontified t))
1582 (if (fboundp 'jit-lock-fontify-now)
1583 (jit-lock-fontify-now beg end)))
1584 (if (and keep-props (not (eq occur-excluded-properties t)))
1585 (let ((str (buffer-substring beg end)))
1586 (remove-list-of-text-properties
1587 0 (length str) occur-excluded-properties str)
1588 str)
1589 (buffer-substring-no-properties beg end)))
1590
1591 (defun occur-engine-add-prefix (lines &optional prefix-face)
1592 (mapcar
1593 #'(lambda (line)
1594 (concat (if prefix-face
1595 (propertize " :" 'font-lock-face prefix-face)
1596 " :")
1597 line "\n"))
1598 lines))
1599
1600 (defun occur-accumulate-lines (count &optional keep-props pt)
1601 (save-excursion
1602 (when pt
1603 (goto-char pt))
1604 (let ((forwardp (> count 0))
1605 result beg end moved)
1606 (while (not (or (zerop count)
1607 (if forwardp
1608 (eobp)
1609 (and (bobp) (not moved)))))
1610 (setq count (+ count (if forwardp -1 1)))
1611 (setq beg (line-beginning-position)
1612 end (line-end-position))
1613 (push (occur-engine-line beg end keep-props) result)
1614 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1615 (nreverse result))))
1616
1617 ;; Generate context display for occur.
1618 ;; OUT-LINE is the line where the match is.
1619 ;; NLINES and KEEP-PROPS are args to occur-engine.
1620 ;; CURR-LINE is line count of the current match,
1621 ;; PREV-LINE is line count of the previous match,
1622 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1623 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1624 ;; then concatenate them all together.
1625 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1626 curr-line prev-line prev-after-lines
1627 &optional prefix-face)
1628 ;; Find after- and before-context lines of the current match.
1629 (let ((before-lines
1630 (nreverse (cdr (occur-accumulate-lines
1631 (- (1+ (abs nlines))) keep-props begpt))))
1632 (after-lines
1633 (cdr (occur-accumulate-lines
1634 (1+ nlines) keep-props endpt)))
1635 separator)
1636
1637 ;; Combine after-lines of the previous match
1638 ;; with before-lines of the current match.
1639
1640 (when prev-after-lines
1641 ;; Don't overlap prev after-lines with current before-lines.
1642 (if (>= (+ prev-line (length prev-after-lines))
1643 (- curr-line (length before-lines)))
1644 (setq prev-after-lines
1645 (butlast prev-after-lines
1646 (- (length prev-after-lines)
1647 (- curr-line prev-line (length before-lines) 1))))
1648 ;; Separate non-overlapping context lines with a dashed line.
1649 (setq separator "-------\n")))
1650
1651 (when prev-line
1652 ;; Don't overlap current before-lines with previous match line.
1653 (if (<= (- curr-line (length before-lines))
1654 prev-line)
1655 (setq before-lines
1656 (nthcdr (- (length before-lines)
1657 (- curr-line prev-line 1))
1658 before-lines))
1659 ;; Separate non-overlapping before-context lines.
1660 (unless (> nlines 0)
1661 (setq separator "-------\n"))))
1662
1663 (list
1664 ;; Return a list where the first element is the output line.
1665 (apply #'concat
1666 (append
1667 (if prev-after-lines
1668 (occur-engine-add-prefix prev-after-lines prefix-face))
1669 (if separator
1670 (list (if prefix-face
1671 (propertize separator 'font-lock-face prefix-face)
1672 separator)))
1673 (occur-engine-add-prefix before-lines prefix-face)
1674 (list out-line)))
1675 ;; And the second element is the list of context after-lines.
1676 (if (> nlines 0) after-lines))))
1677
1678 \f
1679 ;; It would be nice to use \\[...], but there is no reasonable way
1680 ;; to make that display both SPC and Y.
1681 (defconst query-replace-help
1682 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1683 RET or `q' to exit, Period to replace one match and exit,
1684 Comma to replace but not move point immediately,
1685 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1686 C-w to delete match and recursive edit,
1687 C-l to clear the screen, redisplay, and offer same replacement again,
1688 ! to replace all remaining matches in this buffer with no more questions,
1689 ^ to move point back to previous match,
1690 E to edit the replacement string.
1691 In multi-buffer replacements type `Y' to replace all remaining
1692 matches in all remaining buffers with no more questions,
1693 `N' to skip to the next buffer without replacing remaining matches
1694 in the current buffer."
1695 "Help message while in `query-replace'.")
1696
1697 (defvar query-replace-map
1698 (let ((map (make-sparse-keymap)))
1699 (define-key map " " 'act)
1700 (define-key map "\d" 'skip)
1701 (define-key map [delete] 'skip)
1702 (define-key map [backspace] 'skip)
1703 (define-key map "y" 'act)
1704 (define-key map "n" 'skip)
1705 (define-key map "Y" 'act)
1706 (define-key map "N" 'skip)
1707 (define-key map "e" 'edit-replacement)
1708 (define-key map "E" 'edit-replacement)
1709 (define-key map "," 'act-and-show)
1710 (define-key map "q" 'exit)
1711 (define-key map "\r" 'exit)
1712 (define-key map [return] 'exit)
1713 (define-key map "." 'act-and-exit)
1714 (define-key map "\C-r" 'edit)
1715 (define-key map "\C-w" 'delete-and-edit)
1716 (define-key map "\C-l" 'recenter)
1717 (define-key map "!" 'automatic)
1718 (define-key map "^" 'backup)
1719 (define-key map "\C-h" 'help)
1720 (define-key map [f1] 'help)
1721 (define-key map [help] 'help)
1722 (define-key map "?" 'help)
1723 (define-key map "\C-g" 'quit)
1724 (define-key map "\C-]" 'quit)
1725 (define-key map "\C-v" 'scroll-up)
1726 (define-key map "\M-v" 'scroll-down)
1727 (define-key map [next] 'scroll-up)
1728 (define-key map [prior] 'scroll-down)
1729 (define-key map [?\C-\M-v] 'scroll-other-window)
1730 (define-key map [M-next] 'scroll-other-window)
1731 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1732 (define-key map [M-prior] 'scroll-other-window-down)
1733 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1734 ;; should check for ESC specially.
1735 ;; (define-key map "\e" 'exit-prefix)
1736 (define-key map [escape] 'exit-prefix)
1737 map)
1738 "Keymap of responses to questions posed by commands like `query-replace'.
1739 The \"bindings\" in this map are not commands; they are answers.
1740 The valid answers include `act', `skip', `act-and-show',
1741 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1742 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1743 `edit', `edit-replacement', `delete-and-edit', `automatic',
1744 `backup', `quit', and `help'.
1745
1746 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1747
1748 (defvar multi-query-replace-map
1749 (let ((map (make-sparse-keymap)))
1750 (set-keymap-parent map query-replace-map)
1751 (define-key map "Y" 'automatic-all)
1752 (define-key map "N" 'exit-current)
1753 map)
1754 "Keymap that defines additional bindings for multi-buffer replacements.
1755 It extends its parent map `query-replace-map' with new bindings to
1756 operate on a set of buffers/files. The difference with its parent map
1757 is the additional answers `automatic-all' to replace all remaining
1758 matches in all remaining buffers with no more questions, and
1759 `exit-current' to skip remaining matches in the current buffer
1760 and to continue with the next buffer in the sequence.")
1761
1762 (defun replace-match-string-symbols (n)
1763 "Process a list (and any sub-lists), expanding certain symbols.
1764 Symbol Expands To
1765 N (match-string N) (where N is a string of digits)
1766 #N (string-to-number (match-string N))
1767 & (match-string 0)
1768 #& (string-to-number (match-string 0))
1769 # replace-count
1770
1771 Note that these symbols must be preceded by a backslash in order to
1772 type them using Lisp syntax."
1773 (while (consp n)
1774 (cond
1775 ((consp (car n))
1776 (replace-match-string-symbols (car n))) ;Process sub-list
1777 ((symbolp (car n))
1778 (let ((name (symbol-name (car n))))
1779 (cond
1780 ((string-match "^[0-9]+$" name)
1781 (setcar n (list 'match-string (string-to-number name))))
1782 ((string-match "^#[0-9]+$" name)
1783 (setcar n (list 'string-to-number
1784 (list 'match-string
1785 (string-to-number (substring name 1))))))
1786 ((string= "&" name)
1787 (setcar n '(match-string 0)))
1788 ((string= "#&" name)
1789 (setcar n '(string-to-number (match-string 0))))
1790 ((string= "#" name)
1791 (setcar n 'replace-count))))))
1792 (setq n (cdr n))))
1793
1794 (defun replace-eval-replacement (expression count)
1795 (let* ((replace-count count)
1796 err
1797 (replacement
1798 (condition-case err
1799 (eval expression)
1800 (error
1801 (error "Error evaluating replacement expression: %S" err)))))
1802 (if (stringp replacement)
1803 replacement
1804 (prin1-to-string replacement t))))
1805
1806 (defun replace-quote (replacement)
1807 "Quote a replacement string.
1808 This just doubles all backslashes in REPLACEMENT and
1809 returns the resulting string. If REPLACEMENT is not
1810 a string, it is first passed through `prin1-to-string'
1811 with the `noescape' argument set.
1812
1813 `match-data' is preserved across the call."
1814 (save-match-data
1815 (replace-regexp-in-string "\\\\" "\\\\"
1816 (if (stringp replacement)
1817 replacement
1818 (prin1-to-string replacement t))
1819 t t)))
1820
1821 (defun replace-loop-through-replacements (data count)
1822 ;; DATA is a vector containing the following values:
1823 ;; 0 next-rotate-count
1824 ;; 1 repeat-count
1825 ;; 2 next-replacement
1826 ;; 3 replacements
1827 (if (= (aref data 0) count)
1828 (progn
1829 (aset data 0 (+ count (aref data 1)))
1830 (let ((next (cdr (aref data 2))))
1831 (aset data 2 (if (consp next) next (aref data 3))))))
1832 (car (aref data 2)))
1833
1834 (defun replace-match-data (integers reuse &optional new)
1835 "Like `match-data', but markers in REUSE get invalidated.
1836 If NEW is non-nil, it is set and returned instead of fresh data,
1837 but coerced to the correct value of INTEGERS."
1838 (or (and new
1839 (progn
1840 (set-match-data new)
1841 (and (eq new reuse)
1842 (eq (null integers) (markerp (car reuse)))
1843 new)))
1844 (match-data integers reuse t)))
1845
1846 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1847 "Make a replacement with `replace-match', editing `\\?'.
1848 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1849 check for `\\?' is made to save time. MATCH-DATA is used for the
1850 replacement. In case editing is done, it is changed to use markers.
1851
1852 The return value is non-nil if there has been no `\\?' or NOEDIT was
1853 passed in. If LITERAL is set, no checking is done, anyway."
1854 (unless (or literal noedit)
1855 (setq noedit t)
1856 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1857 newtext)
1858 (setq newtext
1859 (read-string "Edit replacement string: "
1860 (prog1
1861 (cons
1862 (replace-match "" t t newtext 3)
1863 (1+ (match-beginning 3)))
1864 (setq match-data
1865 (replace-match-data
1866 nil match-data match-data))))
1867 noedit nil)))
1868 (set-match-data match-data)
1869 (replace-match newtext fixedcase literal)
1870 noedit)
1871
1872 (defvar replace-search-function nil
1873 "Function to use when searching for strings to replace.
1874 It is used by `query-replace' and `replace-string', and is called
1875 with three arguments, as if it were `search-forward'.")
1876
1877 (defvar replace-re-search-function nil
1878 "Function to use when searching for regexps to replace.
1879 It is used by `query-replace-regexp', `replace-regexp',
1880 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1881 It is called with three arguments, as if it were
1882 `re-search-forward'.")
1883
1884 (defun replace-search (search-string limit regexp-flag delimited-flag
1885 case-fold-search)
1886 "Search for the next occurrence of SEARCH-STRING to replace."
1887 ;; Let-bind global isearch-* variables to values used
1888 ;; to search the next replacement. These let-bindings
1889 ;; should be effective both at the time of calling
1890 ;; `isearch-search-fun-default' and also at the
1891 ;; time of funcalling `search-function'.
1892 ;; These isearch-* bindings can't be placed higher
1893 ;; outside of this function because then another I-search
1894 ;; used after `recursive-edit' might override them.
1895 (let* ((isearch-regexp regexp-flag)
1896 (isearch-word delimited-flag)
1897 (isearch-lax-whitespace
1898 replace-lax-whitespace)
1899 (isearch-regexp-lax-whitespace
1900 replace-regexp-lax-whitespace)
1901 (isearch-case-fold-search case-fold-search)
1902 (isearch-adjusted nil)
1903 (isearch-nonincremental t) ; don't use lax word mode
1904 (isearch-forward t)
1905 (search-function
1906 (or (if regexp-flag
1907 replace-re-search-function
1908 replace-search-function)
1909 (isearch-search-fun-default))))
1910 (funcall search-function search-string limit t)))
1911
1912 (defvar replace-overlay nil)
1913
1914 (defun replace-highlight (match-beg match-end range-beg range-end
1915 search-string regexp-flag delimited-flag
1916 case-fold-search)
1917 (if query-replace-highlight
1918 (if replace-overlay
1919 (move-overlay replace-overlay match-beg match-end (current-buffer))
1920 (setq replace-overlay (make-overlay match-beg match-end))
1921 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
1922 (overlay-put replace-overlay 'face 'query-replace)))
1923 (if query-replace-lazy-highlight
1924 (let ((isearch-string search-string)
1925 (isearch-regexp regexp-flag)
1926 (isearch-word delimited-flag)
1927 (isearch-lax-whitespace
1928 replace-lax-whitespace)
1929 (isearch-regexp-lax-whitespace
1930 replace-regexp-lax-whitespace)
1931 (isearch-case-fold-search case-fold-search)
1932 (isearch-forward t)
1933 (isearch-other-end match-beg)
1934 (isearch-error nil))
1935 (isearch-lazy-highlight-new-loop range-beg range-end))))
1936
1937 (defun replace-dehighlight ()
1938 (when replace-overlay
1939 (delete-overlay replace-overlay))
1940 (when query-replace-lazy-highlight
1941 (lazy-highlight-cleanup lazy-highlight-cleanup)
1942 (setq isearch-lazy-highlight-last-string nil))
1943 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
1944 (isearch-clean-overlays))
1945
1946 (defun perform-replace (from-string replacements
1947 query-flag regexp-flag delimited-flag
1948 &optional repeat-count map start end)
1949 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1950 Don't use this in your own program unless you want to query and set the mark
1951 just as `query-replace' does. Instead, write a simple loop like this:
1952
1953 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1954 (replace-match \"foobar\" nil nil))
1955
1956 which will run faster and probably do exactly what you want. Please
1957 see the documentation of `replace-match' to find out how to simulate
1958 `case-replace'.
1959
1960 This function returns nil if and only if there were no matches to
1961 make, or the user didn't cancel the call."
1962 (or map (setq map query-replace-map))
1963 (and query-flag minibuffer-auto-raise
1964 (raise-frame (window-frame (minibuffer-window))))
1965 (let* ((case-fold-search
1966 (if (and case-fold-search search-upper-case)
1967 (isearch-no-upper-case-p from-string regexp-flag)
1968 case-fold-search))
1969 (nocasify (not (and case-replace case-fold-search)))
1970 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1971 (search-string from-string)
1972 (real-match-data nil) ; The match data for the current match.
1973 (next-replacement nil)
1974 ;; This is non-nil if we know there is nothing for the user
1975 ;; to edit in the replacement.
1976 (noedit nil)
1977 (keep-going t)
1978 (stack nil)
1979 (replace-count 0)
1980 (skip-read-only-count 0)
1981 (skip-filtered-count 0)
1982 (skip-invisible-count 0)
1983 (nonempty-match nil)
1984 (multi-buffer nil)
1985 (recenter-last-op nil) ; Start cycling order with initial position.
1986
1987 ;; If non-nil, it is marker saying where in the buffer to stop.
1988 (limit nil)
1989
1990 ;; Data for the next match. If a cons, it has the same format as
1991 ;; (match-data); otherwise it is t if a match is possible at point.
1992 (match-again t)
1993
1994 (message
1995 (if query-flag
1996 (apply 'propertize
1997 (substitute-command-keys
1998 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1999 minibuffer-prompt-properties))))
2000
2001 ;; If region is active, in Transient Mark mode, operate on region.
2002 (when start
2003 (setq limit (copy-marker (max start end)))
2004 (goto-char (min start end))
2005 (deactivate-mark))
2006
2007 ;; If last typed key in previous call of multi-buffer perform-replace
2008 ;; was `automatic-all', don't ask more questions in next files
2009 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2010 (setq query-flag nil multi-buffer t))
2011
2012 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
2013 ;; containing a function and its first argument. The function is
2014 ;; called to generate each replacement like this:
2015 ;; (funcall (car replacements) (cdr replacements) replace-count)
2016 ;; It must return a string.
2017 (cond
2018 ((stringp replacements)
2019 (setq next-replacement replacements
2020 replacements nil))
2021 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2022 (or repeat-count (setq repeat-count 1))
2023 (setq replacements (cons 'replace-loop-through-replacements
2024 (vector repeat-count repeat-count
2025 replacements replacements)))))
2026
2027 (when query-replace-lazy-highlight
2028 (setq isearch-lazy-highlight-last-string nil))
2029
2030 (push-mark)
2031 (undo-boundary)
2032 (unwind-protect
2033 ;; Loop finding occurrences that perhaps should be replaced.
2034 (while (and keep-going
2035 (not (or (eobp) (and limit (>= (point) limit))))
2036 ;; Use the next match if it is already known;
2037 ;; otherwise, search for a match after moving forward
2038 ;; one char if progress is required.
2039 (setq real-match-data
2040 (cond ((consp match-again)
2041 (goto-char (nth 1 match-again))
2042 (replace-match-data
2043 t real-match-data match-again))
2044 ;; MATCH-AGAIN non-nil means accept an
2045 ;; adjacent match.
2046 (match-again
2047 (and
2048 (replace-search search-string limit
2049 regexp-flag delimited-flag
2050 case-fold-search)
2051 ;; For speed, use only integers and
2052 ;; reuse the list used last time.
2053 (replace-match-data t real-match-data)))
2054 ((and (< (1+ (point)) (point-max))
2055 (or (null limit)
2056 (< (1+ (point)) limit)))
2057 ;; If not accepting adjacent matches,
2058 ;; move one char to the right before
2059 ;; searching again. Undo the motion
2060 ;; if the search fails.
2061 (let ((opoint (point)))
2062 (forward-char 1)
2063 (if (replace-search search-string limit
2064 regexp-flag delimited-flag
2065 case-fold-search)
2066 (replace-match-data
2067 t real-match-data)
2068 (goto-char opoint)
2069 nil))))))
2070
2071 ;; Record whether the match is nonempty, to avoid an infinite loop
2072 ;; repeatedly matching the same empty string.
2073 (setq nonempty-match
2074 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2075
2076 ;; If the match is empty, record that the next one can't be
2077 ;; adjacent.
2078
2079 ;; Otherwise, if matching a regular expression, do the next
2080 ;; match now, since the replacement for this match may
2081 ;; affect whether the next match is adjacent to this one.
2082 ;; If that match is empty, don't use it.
2083 (setq match-again
2084 (and nonempty-match
2085 (or (not regexp-flag)
2086 (and (looking-at search-string)
2087 (let ((match (match-data)))
2088 (and (/= (nth 0 match) (nth 1 match))
2089 match))))))
2090
2091 (cond
2092 ;; Optionally ignore matches that have a read-only property.
2093 ((not (or (not query-replace-skip-read-only)
2094 (not (text-property-not-all
2095 (nth 0 real-match-data) (nth 1 real-match-data)
2096 'read-only nil))))
2097 (setq skip-read-only-count (1+ skip-read-only-count)))
2098 ;; Optionally filter out matches.
2099 ((not (funcall isearch-filter-predicate
2100 (nth 0 real-match-data) (nth 1 real-match-data)))
2101 (setq skip-filtered-count (1+ skip-filtered-count)))
2102 ;; Optionally ignore invisible matches.
2103 ((not (or (eq search-invisible t)
2104 ;; Don't open overlays for automatic replacements.
2105 (and (not query-flag) search-invisible)
2106 ;; Open hidden overlays for interactive replacements.
2107 (not (isearch-range-invisible
2108 (nth 0 real-match-data) (nth 1 real-match-data)))))
2109 (setq skip-invisible-count (1+ skip-invisible-count)))
2110 (t
2111 ;; Calculate the replacement string, if necessary.
2112 (when replacements
2113 (set-match-data real-match-data)
2114 (setq next-replacement
2115 (funcall (car replacements) (cdr replacements)
2116 replace-count)))
2117 (if (not query-flag)
2118 (progn
2119 (unless (or literal noedit)
2120 (replace-highlight
2121 (nth 0 real-match-data) (nth 1 real-match-data)
2122 start end search-string
2123 regexp-flag delimited-flag case-fold-search))
2124 (setq noedit
2125 (replace-match-maybe-edit
2126 next-replacement nocasify literal
2127 noedit real-match-data)
2128 replace-count (1+ replace-count)))
2129 (undo-boundary)
2130 (let (done replaced key def)
2131 ;; Loop reading commands until one of them sets done,
2132 ;; which means it has finished handling this
2133 ;; occurrence. Any command that sets `done' should
2134 ;; leave behind proper match data for the stack.
2135 ;; Commands not setting `done' need to adjust
2136 ;; `real-match-data'.
2137 (while (not done)
2138 (set-match-data real-match-data)
2139 (replace-highlight
2140 (match-beginning 0) (match-end 0)
2141 start end search-string
2142 regexp-flag delimited-flag case-fold-search)
2143 ;; Bind message-log-max so we don't fill up the message log
2144 ;; with a bunch of identical messages.
2145 (let ((message-log-max nil)
2146 (replacement-presentation
2147 (if query-replace-show-replacement
2148 (save-match-data
2149 (set-match-data real-match-data)
2150 (match-substitute-replacement next-replacement
2151 nocasify literal))
2152 next-replacement)))
2153 (message message
2154 (query-replace-descr from-string)
2155 (query-replace-descr replacement-presentation)))
2156 (setq key (read-event))
2157 ;; Necessary in case something happens during read-event
2158 ;; that clobbers the match data.
2159 (set-match-data real-match-data)
2160 (setq key (vector key))
2161 (setq def (lookup-key map key))
2162 ;; Restore the match data while we process the command.
2163 (cond ((eq def 'help)
2164 (with-output-to-temp-buffer "*Help*"
2165 (princ
2166 (concat "Query replacing "
2167 (if delimited-flag
2168 (or (and (symbolp delimited-flag)
2169 (get delimited-flag 'isearch-message-prefix))
2170 "word ") "")
2171 (if regexp-flag "regexp " "")
2172 from-string " with "
2173 next-replacement ".\n\n"
2174 (substitute-command-keys
2175 query-replace-help)))
2176 (with-current-buffer standard-output
2177 (help-mode))))
2178 ((eq def 'exit)
2179 (setq keep-going nil)
2180 (setq done t))
2181 ((eq def 'exit-current)
2182 (setq multi-buffer t keep-going nil done t))
2183 ((eq def 'backup)
2184 (if stack
2185 (let ((elt (pop stack)))
2186 (goto-char (nth 0 elt))
2187 (setq replaced (nth 1 elt)
2188 real-match-data
2189 (replace-match-data
2190 t real-match-data
2191 (nth 2 elt))))
2192 (message "No previous match")
2193 (ding 'no-terminate)
2194 (sit-for 1)))
2195 ((eq def 'act)
2196 (or replaced
2197 (setq noedit
2198 (replace-match-maybe-edit
2199 next-replacement nocasify literal
2200 noedit real-match-data)
2201 replace-count (1+ replace-count)))
2202 (setq done t replaced t))
2203 ((eq def 'act-and-exit)
2204 (or replaced
2205 (setq noedit
2206 (replace-match-maybe-edit
2207 next-replacement nocasify literal
2208 noedit real-match-data)
2209 replace-count (1+ replace-count)))
2210 (setq keep-going nil)
2211 (setq done t replaced t))
2212 ((eq def 'act-and-show)
2213 (if (not replaced)
2214 (setq noedit
2215 (replace-match-maybe-edit
2216 next-replacement nocasify literal
2217 noedit real-match-data)
2218 replace-count (1+ replace-count)
2219 real-match-data (replace-match-data
2220 t real-match-data)
2221 replaced t)))
2222 ((or (eq def 'automatic) (eq def 'automatic-all))
2223 (or replaced
2224 (setq noedit
2225 (replace-match-maybe-edit
2226 next-replacement nocasify literal
2227 noedit real-match-data)
2228 replace-count (1+ replace-count)))
2229 (setq done t query-flag nil replaced t)
2230 (if (eq def 'automatic-all) (setq multi-buffer t)))
2231 ((eq def 'skip)
2232 (setq done t))
2233 ((eq def 'recenter)
2234 ;; `this-command' has the value `query-replace',
2235 ;; so we need to bind it to `recenter-top-bottom'
2236 ;; to allow it to detect a sequence of `C-l'.
2237 (let ((this-command 'recenter-top-bottom)
2238 (last-command 'recenter-top-bottom))
2239 (recenter-top-bottom)))
2240 ((eq def 'edit)
2241 (let ((opos (point-marker)))
2242 (setq real-match-data (replace-match-data
2243 nil real-match-data
2244 real-match-data))
2245 (goto-char (match-beginning 0))
2246 (save-excursion
2247 (save-window-excursion
2248 (recursive-edit)))
2249 (goto-char opos)
2250 (set-marker opos nil))
2251 ;; Before we make the replacement,
2252 ;; decide whether the search string
2253 ;; can match again just after this match.
2254 (if (and regexp-flag nonempty-match)
2255 (setq match-again (and (looking-at search-string)
2256 (match-data)))))
2257 ;; Edit replacement.
2258 ((eq def 'edit-replacement)
2259 (setq real-match-data (replace-match-data
2260 nil real-match-data
2261 real-match-data)
2262 next-replacement
2263 (read-string "Edit replacement string: "
2264 next-replacement)
2265 noedit nil)
2266 (if replaced
2267 (set-match-data real-match-data)
2268 (setq noedit
2269 (replace-match-maybe-edit
2270 next-replacement nocasify literal noedit
2271 real-match-data)
2272 replaced t))
2273 (setq done t))
2274
2275 ((eq def 'delete-and-edit)
2276 (replace-match "" t t)
2277 (setq real-match-data (replace-match-data
2278 nil real-match-data))
2279 (replace-dehighlight)
2280 (save-excursion (recursive-edit))
2281 (setq replaced t))
2282 ;; Note: we do not need to treat `exit-prefix'
2283 ;; specially here, since we reread
2284 ;; any unrecognized character.
2285 (t
2286 (setq this-command 'mode-exited)
2287 (setq keep-going nil)
2288 (setq unread-command-events
2289 (append (listify-key-sequence key)
2290 unread-command-events))
2291 (setq done t)))
2292 (when query-replace-lazy-highlight
2293 ;; Force lazy rehighlighting only after replacements.
2294 (if (not (memq def '(skip backup)))
2295 (setq isearch-lazy-highlight-last-string nil)))
2296 (unless (eq def 'recenter)
2297 ;; Reset recenter cycling order to initial position.
2298 (setq recenter-last-op nil)))
2299 ;; Record previous position for ^ when we move on.
2300 ;; Change markers to numbers in the match data
2301 ;; since lots of markers slow down editing.
2302 (push (list (point) replaced
2303 ;;; If the replacement has already happened, all we need is the
2304 ;;; current match start and end. We could get this with a trivial
2305 ;;; match like
2306 ;;; (save-excursion (goto-char (match-beginning 0))
2307 ;;; (search-forward (match-string 0))
2308 ;;; (match-data t))
2309 ;;; if we really wanted to avoid manually constructing match data.
2310 ;;; Adding current-buffer is necessary so that match-data calls can
2311 ;;; return markers which are appropriate for editing.
2312 (if replaced
2313 (list
2314 (match-beginning 0)
2315 (match-end 0)
2316 (current-buffer))
2317 (match-data t)))
2318 stack))))))
2319
2320 (replace-dehighlight))
2321 (or unread-command-events
2322 (message "Replaced %d occurrence%s%s"
2323 replace-count
2324 (if (= replace-count 1) "" "s")
2325 (if (> (+ skip-read-only-count
2326 skip-filtered-count
2327 skip-invisible-count) 0)
2328 (format " (skipped %s)"
2329 (mapconcat
2330 'identity
2331 (delq nil (list
2332 (if (> skip-read-only-count 0)
2333 (format "%s read-only"
2334 skip-read-only-count))
2335 (if (> skip-invisible-count 0)
2336 (format "%s invisible"
2337 skip-invisible-count))
2338 (if (> skip-filtered-count 0)
2339 (format "%s filtered out"
2340 skip-filtered-count))))
2341 ", "))
2342 "")))
2343 (or (and keep-going stack) multi-buffer)))
2344
2345 ;;; replace.el ends here