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