* vc/vc-bzr.el (vc-bzr-print-log): Improve START-REVISION with LIMIT != 1.
[emacs.git] / lisp / replace.el
blob1bebff448fa2fae9b3f47c92d4ae3cb034d561b1
1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2013 Free
4 ;; Software Foundation, Inc.
6 ;; Maintainer: FSF
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
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.
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.
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/>.
24 ;;; Commentary:
26 ;; This package supplies the string and regular-expression replace functions
27 ;; documented in the Emacs user's manual.
29 ;;; Code:
31 (defcustom case-replace t
32 "Non-nil means `query-replace' should preserve case in replacements."
33 :type 'boolean
34 :group 'matching)
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")
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")
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'.")
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.")
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")
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")
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")
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")
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")
100 (defcustom query-replace-highlight t
101 "Non-nil means to highlight matches during query replacement."
102 :type 'boolean
103 :group 'matching)
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")
115 (defface query-replace
116 '((t (:inherit isearch)))
117 "Face for highlighting query replacement matches."
118 :group 'matching
119 :version "22.1")
121 (defvar replace-count 0
122 "Number of replacements done so far.
123 See `replace-regexp' and `query-replace-regexp-eval'.")
125 (defun query-replace-descr (string)
126 (mapconcat 'isearch-text-char-description string ""))
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))))
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))
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))
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)))
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.
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.
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.
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.)
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'.
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.
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))
279 (define-key esc-map "%" 'query-replace)
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.
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.
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.
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.)
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'.
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.
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.
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).
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.
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))
350 (define-key esc-map [?\C-%] 'query-replace-regexp)
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.
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.
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.
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).
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'.
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.
376 Use \\<minibuffer-local-map>\\[next-history-element] \
377 to pull the last incremental search regexp to the minibuffer
378 that reads REGEXP.
380 Preserves case in each replacement if `case-replace' and `case-fold-search'
381 are non-nil and REGEXP has no uppercase letters.
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'.
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))
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.
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.
427 Non-interactively, TO-STRINGS may be a list of replacement strings.
429 Use \\<minibuffer-local-map>\\[next-history-element] \
430 to pull the last incremental search regexp to the minibuffer
431 that reads REGEXP.
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)))
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.)
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'.
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.
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.
484 Use \\<minibuffer-local-map>\\[next-history-element] \
485 to pull the last incremental search string to the minibuffer
486 that reads FROM-STRING.
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))
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.
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'.
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.
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.
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.
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.
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.
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.
549 Use \\<minibuffer-local-map>\\[next-history-element] \
550 to pull the last incremental search regexp to the minibuffer
551 that reads REGEXP.
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))
574 (defvar regexp-history nil
575 "History list for some commands that read regular expressions.
577 Maximum length of the history list is determined by the value
578 of `history-length', which see.")
580 (defvar occur-collect-regexp-history '("\\1")
581 "History of regexp for occur's collect operation")
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.
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.
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)))
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)))))
630 (defalias 'delete-non-matching-lines 'keep-lines)
631 (defalias 'delete-matching-lines 'flush-lines)
632 (defalias 'count-matches 'how-many)
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))
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.
647 If REGEXP contains upper case characters (excluding those preceded by `\\')
648 and `search-upper-case' is non-nil, the matching is case-sensitive.
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.)
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.
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."
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))))
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)
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.
723 If REGEXP contains upper case characters (excluding those preceded by `\\')
724 and `search-upper-case' is non-nil, the matching is case-sensitive.
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.
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.
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."
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)
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.
775 If REGEXP contains upper case characters (excluding those preceded by `\\')
776 and `search-upper-case' is non-nil, the matching is case-sensitive.
778 Second and third arg RSTART and REND specify the region to operate on.
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.
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."
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)))
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'.")
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'.")
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)
889 (defcustom occur-mode-hook '(turn-on-font-lock)
890 "Hook run when entering Occur mode."
891 :type 'hook
892 :group 'matching)
894 (defcustom occur-hook nil
895 "Hook run by Occur when there are any matches."
896 :type 'hook
897 :group 'matching)
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)
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.
913 \\{occur-mode-map}"
914 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
915 (setq next-error-function 'occur-next-error))
918 ;;; Occur Edit mode
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'.")
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.
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.")))
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.")))
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)))))))
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)))))
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))
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)))
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)))
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))))
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)))))
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"))
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"))
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))))
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)))
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")
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)
1114 (defalias 'list-matching-lines 'occur)
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)
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)
1128 (defcustom list-matching-lines-prefix-face 'shadow
1129 "Face used by \\[list-matching-lines] to show the prefix column.
1130 If the face doesn't differ from the default face,
1131 don't highlight the prefix with line numbers specially."
1132 :type 'face
1133 :group 'matching
1134 :version "24.4")
1136 (defcustom occur-excluded-properties
1137 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1138 yank-handler follow-link)
1139 "Text properties to discard when copying lines to the *Occur* buffer.
1140 The value should be a list of text properties to discard or t,
1141 which means to discard all text properties."
1142 :type '(choice (const :tag "All" t) (repeat symbol))
1143 :group 'matching
1144 :version "22.1")
1146 (defvar occur-read-regexp-defaults-function
1147 'occur-read-regexp-defaults
1148 "Function that provides default regexp(s) for occur commands.
1149 This function should take no arguments and return one of nil, a
1150 regexp or a list of regexps for use with occur commands -
1151 `occur', `multi-occur' and `multi-occur-in-matching-buffers'.
1152 The return value of this function is used as DEFAULTS param of
1153 `read-regexp' while executing the occur command. This function
1154 is called only during interactive use.
1156 For example, to check for occurrence of symbol at point use
1158 \(setq occur-read-regexp-defaults-function
1159 'find-tag-default-as-regexp\).")
1161 (defun occur-read-regexp-defaults ()
1162 "Return the latest regexp from `regexp-history'.
1163 See `occur-read-regexp-defaults-function' for details."
1164 (car regexp-history))
1166 (defun occur-read-primary-args ()
1167 (let* ((perform-collect (consp current-prefix-arg))
1168 (regexp (read-regexp (if perform-collect
1169 "Collect strings matching regexp"
1170 "List lines matching regexp")
1171 (funcall occur-read-regexp-defaults-function))))
1172 (list regexp
1173 (if perform-collect
1174 ;; Perform collect operation
1175 (if (zerop (regexp-opt-depth regexp))
1176 ;; No subexpression so collect the entire match.
1177 "\\&"
1178 ;; Get the regexp for collection pattern.
1179 (let ((default (car occur-collect-regexp-history)))
1180 (read-regexp
1181 (format "Regexp to collect (default %s): " default)
1182 default 'occur-collect-regexp-history)))
1183 ;; Otherwise normal occur takes numerical prefix argument.
1184 (when current-prefix-arg
1185 (prefix-numeric-value current-prefix-arg))))))
1187 (defun occur-rename-buffer (&optional unique-p interactive-p)
1188 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1189 Here `original-buffer-name' is the buffer name where Occur was originally run.
1190 When given the prefix argument, or called non-interactively, the renaming
1191 will not clobber the existing buffer(s) of that name, but use
1192 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1193 if you always want a separate *Occur* buffer for each buffer where you
1194 invoke `occur'."
1195 (interactive "P\np")
1196 (with-current-buffer
1197 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1198 (rename-buffer (concat "*Occur: "
1199 (mapconcat #'buffer-name
1200 (car (cddr occur-revert-arguments)) "/")
1201 "*")
1202 (or unique-p (not interactive-p)))))
1204 (defun occur (regexp &optional nlines)
1205 "Show all lines in the current buffer containing a match for REGEXP.
1206 If a match spreads across multiple lines, all those lines are shown.
1208 Each line is displayed with NLINES lines before and after, or -NLINES
1209 before if NLINES is negative.
1210 NLINES defaults to `list-matching-lines-default-context-lines'.
1211 Interactively it is the prefix arg.
1213 The lines are shown in a buffer named `*Occur*'.
1214 It serves as a menu to find any of the occurrences in this buffer.
1215 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1217 If REGEXP contains upper case characters (excluding those preceded by `\\')
1218 and `search-upper-case' is non-nil, the matching is case-sensitive.
1220 When NLINES is a string or when the function is called
1221 interactively with prefix argument without a number (`C-u' alone
1222 as prefix) the matching strings are collected into the `*Occur*'
1223 buffer by using NLINES as a replacement regexp. NLINES may
1224 contain \\& and \\N which convention follows `replace-match'.
1225 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1226 \"\\1\" for NLINES collects all the function names in a lisp
1227 program. When there is no parenthesized subexpressions in REGEXP
1228 the entire match is collected. In any case the searched buffer
1229 is not modified."
1230 (interactive (occur-read-primary-args))
1231 (occur-1 regexp nlines (list (current-buffer))))
1233 (defvar ido-ignore-item-temp-list)
1235 (defun multi-occur (bufs regexp &optional nlines)
1236 "Show all lines in buffers BUFS containing a match for REGEXP.
1237 This function acts on multiple buffers; otherwise, it is exactly like
1238 `occur'. When you invoke this command interactively, you must specify
1239 the buffer names that you want, one by one.
1240 See also `multi-occur-in-matching-buffers'."
1241 (interactive
1242 (cons
1243 (let* ((bufs (list (read-buffer "First buffer to search: "
1244 (current-buffer) t)))
1245 (buf nil)
1246 (ido-ignore-item-temp-list bufs))
1247 (while (not (string-equal
1248 (setq buf (read-buffer
1249 (if (eq read-buffer-function 'ido-read-buffer)
1250 "Next buffer to search (C-j to end): "
1251 "Next buffer to search (RET to end): ")
1252 nil t))
1253 ""))
1254 (add-to-list 'bufs buf)
1255 (setq ido-ignore-item-temp-list bufs))
1256 (nreverse (mapcar #'get-buffer bufs)))
1257 (occur-read-primary-args)))
1258 (occur-1 regexp nlines bufs))
1260 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1261 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1262 Normally BUFREGEXP matches against each buffer's visited file name,
1263 but if you specify a prefix argument, it matches against the buffer name.
1264 See also `multi-occur'."
1265 (interactive
1266 (cons
1267 (let* ((default (car regexp-history))
1268 (input
1269 (read-regexp
1270 (if current-prefix-arg
1271 "List lines in buffers whose names match regexp: "
1272 "List lines in buffers whose filenames match regexp: "))))
1273 (if (equal input "")
1274 default
1275 input))
1276 (occur-read-primary-args)))
1277 (when bufregexp
1278 (occur-1 regexp nil
1279 (delq nil
1280 (mapcar (lambda (buf)
1281 (when (if allbufs
1282 (string-match bufregexp
1283 (buffer-name buf))
1284 (and (buffer-file-name buf)
1285 (string-match bufregexp
1286 (buffer-file-name buf))))
1287 buf))
1288 (buffer-list))))))
1290 (defun occur-1 (regexp nlines bufs &optional buf-name)
1291 (unless (and regexp (not (equal regexp "")))
1292 (error "Occur doesn't work with the empty regexp"))
1293 (unless buf-name
1294 (setq buf-name "*Occur*"))
1295 (let (occur-buf
1296 (active-bufs (delq nil (mapcar #'(lambda (buf)
1297 (when (buffer-live-p buf) buf))
1298 bufs))))
1299 ;; Handle the case where one of the buffers we're searching is the
1300 ;; output buffer. Just rename it.
1301 (when (member buf-name (mapcar 'buffer-name active-bufs))
1302 (with-current-buffer (get-buffer buf-name)
1303 (rename-uniquely)))
1305 ;; Now find or create the output buffer.
1306 ;; If we just renamed that buffer, we will make a new one here.
1307 (setq occur-buf (get-buffer-create buf-name))
1309 (with-current-buffer occur-buf
1310 (if (stringp nlines)
1311 (fundamental-mode) ;; This is for collect operation.
1312 (occur-mode))
1313 (let ((inhibit-read-only t)
1314 ;; Don't generate undo entries for creation of the initial contents.
1315 (buffer-undo-list t))
1316 (erase-buffer)
1317 (let ((count
1318 (if (stringp nlines)
1319 ;; Treat nlines as a regexp to collect.
1320 (let ((bufs active-bufs)
1321 (count 0))
1322 (while bufs
1323 (with-current-buffer (car bufs)
1324 (save-excursion
1325 (goto-char (point-min))
1326 (while (re-search-forward regexp nil t)
1327 ;; Insert the replacement regexp.
1328 (let ((str (match-substitute-replacement nlines)))
1329 (if str
1330 (with-current-buffer occur-buf
1331 (insert str)
1332 (setq count (1+ count))
1333 (or (zerop (current-column))
1334 (insert "\n"))))))))
1335 (setq bufs (cdr bufs)))
1336 count)
1337 ;; Perform normal occur.
1338 (occur-engine
1339 regexp active-bufs occur-buf
1340 (or nlines list-matching-lines-default-context-lines)
1341 (if (and case-fold-search search-upper-case)
1342 (isearch-no-upper-case-p regexp t)
1343 case-fold-search)
1344 list-matching-lines-buffer-name-face
1345 (if (face-differs-from-default-p list-matching-lines-prefix-face)
1346 list-matching-lines-prefix-face)
1347 list-matching-lines-face
1348 (not (eq occur-excluded-properties t))))))
1349 (let* ((bufcount (length active-bufs))
1350 (diff (- (length bufs) bufcount)))
1351 (message "Searched %d buffer%s%s; %s match%s%s"
1352 bufcount (if (= bufcount 1) "" "s")
1353 (if (zerop diff) "" (format " (%d killed)" diff))
1354 (if (zerop count) "no" (format "%d" count))
1355 (if (= count 1) "" "es")
1356 ;; Don't display regexp if with remaining text
1357 ;; it is longer than window-width.
1358 (if (> (+ (length regexp) 42) (window-width))
1359 "" (format " for `%s'" (query-replace-descr regexp)))))
1360 (setq occur-revert-arguments (list regexp nlines bufs))
1361 (if (= count 0)
1362 (kill-buffer occur-buf)
1363 (display-buffer occur-buf)
1364 (setq next-error-last-buffer occur-buf)
1365 (setq buffer-read-only t)
1366 (set-buffer-modified-p nil)
1367 (run-hooks 'occur-hook)))))))
1369 (defun occur-engine (regexp buffers out-buf nlines case-fold
1370 title-face prefix-face match-face keep-props)
1371 (with-current-buffer out-buf
1372 (let ((globalcount 0)
1373 (coding nil)
1374 (case-fold-search case-fold))
1375 ;; Map over all the buffers
1376 (dolist (buf buffers)
1377 (when (buffer-live-p buf)
1378 (let ((matches 0) ;; count of matched lines
1379 (lines 1) ;; line count
1380 (prev-after-lines nil) ;; context lines of prev match
1381 (prev-lines nil) ;; line number of prev match endpt
1382 (matchbeg 0)
1383 (origpt nil)
1384 (begpt nil)
1385 (endpt nil)
1386 (marker nil)
1387 (curstring "")
1388 (ret nil)
1389 (inhibit-field-text-motion t)
1390 (headerpt (with-current-buffer out-buf (point))))
1391 (with-current-buffer buf
1392 (or coding
1393 ;; Set CODING only if the current buffer locally
1394 ;; binds buffer-file-coding-system.
1395 (not (local-variable-p 'buffer-file-coding-system))
1396 (setq coding buffer-file-coding-system))
1397 (save-excursion
1398 (goto-char (point-min)) ;; begin searching in the buffer
1399 (while (not (eobp))
1400 (setq origpt (point))
1401 (when (setq endpt (re-search-forward regexp nil t))
1402 (setq matches (1+ matches)) ;; increment match count
1403 (setq matchbeg (match-beginning 0))
1404 ;; Get beginning of first match line and end of the last.
1405 (save-excursion
1406 (goto-char matchbeg)
1407 (setq begpt (line-beginning-position))
1408 (goto-char endpt)
1409 (setq endpt (line-end-position)))
1410 ;; Sum line numbers up to the first match line.
1411 (setq lines (+ lines (count-lines origpt begpt)))
1412 (setq marker (make-marker))
1413 (set-marker marker matchbeg)
1414 (setq curstring (occur-engine-line begpt endpt keep-props))
1415 ;; Highlight the matches
1416 (let ((len (length curstring))
1417 (start 0))
1418 (while (and (< start len)
1419 (string-match regexp curstring start))
1420 (add-text-properties
1421 (match-beginning 0) (match-end 0)
1422 (append
1423 `(occur-match t)
1424 (when match-face
1425 ;; Use `face' rather than `font-lock-face' here
1426 ;; so as to override faces copied from the buffer.
1427 `(face ,match-face)))
1428 curstring)
1429 (setq start (match-end 0))))
1430 ;; Generate the string to insert for this match
1431 (let* ((match-prefix
1432 ;; Using 7 digits aligns tabs properly.
1433 (apply #'propertize (format "%7d:" lines)
1434 (append
1435 (when prefix-face
1436 `(font-lock-face ,prefix-face))
1437 `(occur-prefix t mouse-face (highlight)
1438 ;; Allow insertion of text at
1439 ;; the end of the prefix (for
1440 ;; Occur Edit mode).
1441 front-sticky t rear-nonsticky t
1442 occur-target ,marker follow-link t
1443 help-echo "mouse-2: go to this occurrence"))))
1444 (match-str
1445 ;; We don't put `mouse-face' on the newline,
1446 ;; because that loses. And don't put it
1447 ;; on context lines to reduce flicker.
1448 (propertize curstring 'mouse-face (list 'highlight)
1449 'occur-target marker
1450 'follow-link t
1451 'help-echo
1452 "mouse-2: go to this occurrence"))
1453 (out-line
1454 (concat
1455 match-prefix
1456 ;; Add non-numeric prefix to all non-first lines
1457 ;; of multi-line matches.
1458 (replace-regexp-in-string
1459 "\n"
1460 (if prefix-face
1461 (propertize "\n :" 'font-lock-face prefix-face)
1462 "\n :")
1463 match-str)
1464 ;; Add marker at eol, but no mouse props.
1465 (propertize "\n" 'occur-target marker)))
1466 (data
1467 (if (= nlines 0)
1468 ;; The simple display style
1469 out-line
1470 ;; The complex multi-line display style.
1471 (setq ret (occur-context-lines
1472 out-line nlines keep-props begpt endpt
1473 lines prev-lines prev-after-lines
1474 prefix-face))
1475 ;; Set first elem of the returned list to `data',
1476 ;; and the second elem to `prev-after-lines'.
1477 (setq prev-after-lines (nth 1 ret))
1478 (nth 0 ret))))
1479 ;; Actually insert the match display data
1480 (with-current-buffer out-buf
1481 (insert data)))
1482 (goto-char endpt))
1483 (if endpt
1484 (progn
1485 ;; Sum line numbers between first and last match lines.
1486 (setq lines (+ lines (count-lines begpt endpt)
1487 ;; Add 1 for empty last match line since
1488 ;; count-lines returns 1 line less.
1489 (if (and (bolp) (eolp)) 1 0)))
1490 ;; On to the next match...
1491 (forward-line 1))
1492 (goto-char (point-max)))
1493 (setq prev-lines (1- lines)))
1494 ;; Flush remaining context after-lines.
1495 (when prev-after-lines
1496 (with-current-buffer out-buf
1497 (insert (apply #'concat (occur-engine-add-prefix
1498 prev-after-lines prefix-face)))))))
1499 (when (not (zerop matches)) ;; is the count zero?
1500 (setq globalcount (+ globalcount matches))
1501 (with-current-buffer out-buf
1502 (goto-char headerpt)
1503 (let ((beg (point))
1504 end)
1505 (insert (propertize
1506 (format "%d match%s%s in buffer: %s\n"
1507 matches (if (= matches 1) "" "es")
1508 ;; Don't display regexp for multi-buffer.
1509 (if (> (length buffers) 1)
1510 "" (format " for \"%s\""
1511 (query-replace-descr regexp)))
1512 (buffer-name buf))
1513 'read-only t))
1514 (setq end (point))
1515 (add-text-properties beg end
1516 (append
1517 (when title-face
1518 `(font-lock-face ,title-face))
1519 `(occur-title ,buf))))
1520 (goto-char (point-min)))))))
1521 ;; Display total match count and regexp for multi-buffer.
1522 (when (and (not (zerop globalcount)) (> (length buffers) 1))
1523 (goto-char (point-min))
1524 (let ((beg (point))
1525 end)
1526 (insert (format "%d match%s total for \"%s\":\n"
1527 globalcount (if (= globalcount 1) "" "es")
1528 (query-replace-descr regexp)))
1529 (setq end (point))
1530 (add-text-properties beg end (when title-face
1531 `(font-lock-face ,title-face))))
1532 (goto-char (point-min)))
1533 (if coding
1534 ;; CODING is buffer-file-coding-system of the first buffer
1535 ;; that locally binds it. Let's use it also for the output
1536 ;; buffer.
1537 (set-buffer-file-coding-system coding))
1538 ;; Return the number of matches
1539 globalcount)))
1541 (defun occur-engine-line (beg end &optional keep-props)
1542 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1543 (text-property-not-all beg end 'fontified t))
1544 (if (fboundp 'jit-lock-fontify-now)
1545 (jit-lock-fontify-now beg end)))
1546 (if (and keep-props (not (eq occur-excluded-properties t)))
1547 (let ((str (buffer-substring beg end)))
1548 (remove-list-of-text-properties
1549 0 (length str) occur-excluded-properties str)
1550 str)
1551 (buffer-substring-no-properties beg end)))
1553 (defun occur-engine-add-prefix (lines &optional prefix-face)
1554 (mapcar
1555 #'(lambda (line)
1556 (concat (if prefix-face
1557 (propertize " :" 'font-lock-face prefix-face)
1558 " :")
1559 line "\n"))
1560 lines))
1562 (defun occur-accumulate-lines (count &optional keep-props pt)
1563 (save-excursion
1564 (when pt
1565 (goto-char pt))
1566 (let ((forwardp (> count 0))
1567 result beg end moved)
1568 (while (not (or (zerop count)
1569 (if forwardp
1570 (eobp)
1571 (and (bobp) (not moved)))))
1572 (setq count (+ count (if forwardp -1 1)))
1573 (setq beg (line-beginning-position)
1574 end (line-end-position))
1575 (push (occur-engine-line beg end keep-props) result)
1576 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1577 (nreverse result))))
1579 ;; Generate context display for occur.
1580 ;; OUT-LINE is the line where the match is.
1581 ;; NLINES and KEEP-PROPS are args to occur-engine.
1582 ;; LINES is line count of the current match,
1583 ;; PREV-LINES is line count of the previous match,
1584 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1585 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1586 ;; then concatenate them all together.
1587 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1588 lines prev-lines prev-after-lines
1589 &optional prefix-face)
1590 ;; Find after- and before-context lines of the current match.
1591 (let ((before-lines
1592 (nreverse (cdr (occur-accumulate-lines
1593 (- (1+ (abs nlines))) keep-props begpt))))
1594 (after-lines
1595 (cdr (occur-accumulate-lines
1596 (1+ nlines) keep-props endpt)))
1597 separator)
1599 ;; Combine after-lines of the previous match
1600 ;; with before-lines of the current match.
1602 (when prev-after-lines
1603 ;; Don't overlap prev after-lines with current before-lines.
1604 (if (>= (+ prev-lines (length prev-after-lines))
1605 (- lines (length before-lines)))
1606 (setq prev-after-lines
1607 (butlast prev-after-lines
1608 (- (length prev-after-lines)
1609 (- lines prev-lines (length before-lines) 1))))
1610 ;; Separate non-overlapping context lines with a dashed line.
1611 (setq separator "-------\n")))
1613 (when prev-lines
1614 ;; Don't overlap current before-lines with previous match line.
1615 (if (<= (- lines (length before-lines))
1616 prev-lines)
1617 (setq before-lines
1618 (nthcdr (- (length before-lines)
1619 (- lines prev-lines 1))
1620 before-lines))
1621 ;; Separate non-overlapping before-context lines.
1622 (unless (> nlines 0)
1623 (setq separator "-------\n"))))
1625 (list
1626 ;; Return a list where the first element is the output line.
1627 (apply #'concat
1628 (append
1629 (if prev-after-lines
1630 (occur-engine-add-prefix prev-after-lines prefix-face))
1631 (if separator
1632 (list (if prefix-face
1633 (propertize separator 'font-lock-face prefix-face)
1634 separator)))
1635 (occur-engine-add-prefix before-lines prefix-face)
1636 (list out-line)))
1637 ;; And the second element is the list of context after-lines.
1638 (if (> nlines 0) after-lines))))
1641 ;; It would be nice to use \\[...], but there is no reasonable way
1642 ;; to make that display both SPC and Y.
1643 (defconst query-replace-help
1644 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1645 RET or `q' to exit, Period to replace one match and exit,
1646 Comma to replace but not move point immediately,
1647 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1648 C-w to delete match and recursive edit,
1649 C-l to clear the screen, redisplay, and offer same replacement again,
1650 ! to replace all remaining matches in this buffer with no more questions,
1651 ^ to move point back to previous match,
1652 E to edit the replacement string.
1653 In multi-buffer replacements type `Y' to replace all remaining
1654 matches in all remaining buffers with no more questions,
1655 `N' to skip to the next buffer without replacing remaining matches
1656 in the current buffer."
1657 "Help message while in `query-replace'.")
1659 (defvar query-replace-map
1660 (let ((map (make-sparse-keymap)))
1661 (define-key map " " 'act)
1662 (define-key map "\d" 'skip)
1663 (define-key map [delete] 'skip)
1664 (define-key map [backspace] 'skip)
1665 (define-key map "y" 'act)
1666 (define-key map "n" 'skip)
1667 (define-key map "Y" 'act)
1668 (define-key map "N" 'skip)
1669 (define-key map "e" 'edit-replacement)
1670 (define-key map "E" 'edit-replacement)
1671 (define-key map "," 'act-and-show)
1672 (define-key map "q" 'exit)
1673 (define-key map "\r" 'exit)
1674 (define-key map [return] 'exit)
1675 (define-key map "." 'act-and-exit)
1676 (define-key map "\C-r" 'edit)
1677 (define-key map "\C-w" 'delete-and-edit)
1678 (define-key map "\C-l" 'recenter)
1679 (define-key map "!" 'automatic)
1680 (define-key map "^" 'backup)
1681 (define-key map "\C-h" 'help)
1682 (define-key map [f1] 'help)
1683 (define-key map [help] 'help)
1684 (define-key map "?" 'help)
1685 (define-key map "\C-g" 'quit)
1686 (define-key map "\C-]" 'quit)
1687 (define-key map "\C-v" 'scroll-up)
1688 (define-key map "\M-v" 'scroll-down)
1689 (define-key map [next] 'scroll-up)
1690 (define-key map [prior] 'scroll-down)
1691 (define-key map [?\C-\M-v] 'scroll-other-window)
1692 (define-key map [M-next] 'scroll-other-window)
1693 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1694 (define-key map [M-prior] 'scroll-other-window-down)
1695 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1696 ;; should check for ESC specially.
1697 ;; (define-key map "\e" 'exit-prefix)
1698 (define-key map [escape] 'exit-prefix)
1699 map)
1700 "Keymap of responses to questions posed by commands like `query-replace'.
1701 The \"bindings\" in this map are not commands; they are answers.
1702 The valid answers include `act', `skip', `act-and-show',
1703 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1704 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1705 `edit', `edit-replacement', `delete-and-edit', `automatic',
1706 `backup', `quit', and `help'.
1708 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1710 (defvar multi-query-replace-map
1711 (let ((map (make-sparse-keymap)))
1712 (set-keymap-parent map query-replace-map)
1713 (define-key map "Y" 'automatic-all)
1714 (define-key map "N" 'exit-current)
1715 map)
1716 "Keymap that defines additional bindings for multi-buffer replacements.
1717 It extends its parent map `query-replace-map' with new bindings to
1718 operate on a set of buffers/files. The difference with its parent map
1719 is the additional answers `automatic-all' to replace all remaining
1720 matches in all remaining buffers with no more questions, and
1721 `exit-current' to skip remaining matches in the current buffer
1722 and to continue with the next buffer in the sequence.")
1724 (defun replace-match-string-symbols (n)
1725 "Process a list (and any sub-lists), expanding certain symbols.
1726 Symbol Expands To
1727 N (match-string N) (where N is a string of digits)
1728 #N (string-to-number (match-string N))
1729 & (match-string 0)
1730 #& (string-to-number (match-string 0))
1731 # replace-count
1733 Note that these symbols must be preceded by a backslash in order to
1734 type them using Lisp syntax."
1735 (while (consp n)
1736 (cond
1737 ((consp (car n))
1738 (replace-match-string-symbols (car n))) ;Process sub-list
1739 ((symbolp (car n))
1740 (let ((name (symbol-name (car n))))
1741 (cond
1742 ((string-match "^[0-9]+$" name)
1743 (setcar n (list 'match-string (string-to-number name))))
1744 ((string-match "^#[0-9]+$" name)
1745 (setcar n (list 'string-to-number
1746 (list 'match-string
1747 (string-to-number (substring name 1))))))
1748 ((string= "&" name)
1749 (setcar n '(match-string 0)))
1750 ((string= "#&" name)
1751 (setcar n '(string-to-number (match-string 0))))
1752 ((string= "#" name)
1753 (setcar n 'replace-count))))))
1754 (setq n (cdr n))))
1756 (defun replace-eval-replacement (expression count)
1757 (let* ((replace-count count)
1758 (replacement (eval expression)))
1759 (if (stringp replacement)
1760 replacement
1761 (prin1-to-string replacement t))))
1763 (defun replace-quote (replacement)
1764 "Quote a replacement string.
1765 This just doubles all backslashes in REPLACEMENT and
1766 returns the resulting string. If REPLACEMENT is not
1767 a string, it is first passed through `prin1-to-string'
1768 with the `noescape' argument set.
1770 `match-data' is preserved across the call."
1771 (save-match-data
1772 (replace-regexp-in-string "\\\\" "\\\\"
1773 (if (stringp replacement)
1774 replacement
1775 (prin1-to-string replacement t))
1776 t t)))
1778 (defun replace-loop-through-replacements (data count)
1779 ;; DATA is a vector containing the following values:
1780 ;; 0 next-rotate-count
1781 ;; 1 repeat-count
1782 ;; 2 next-replacement
1783 ;; 3 replacements
1784 (if (= (aref data 0) count)
1785 (progn
1786 (aset data 0 (+ count (aref data 1)))
1787 (let ((next (cdr (aref data 2))))
1788 (aset data 2 (if (consp next) next (aref data 3))))))
1789 (car (aref data 2)))
1791 (defun replace-match-data (integers reuse &optional new)
1792 "Like `match-data', but markers in REUSE get invalidated.
1793 If NEW is non-nil, it is set and returned instead of fresh data,
1794 but coerced to the correct value of INTEGERS."
1795 (or (and new
1796 (progn
1797 (set-match-data new)
1798 (and (eq new reuse)
1799 (eq (null integers) (markerp (car reuse)))
1800 new)))
1801 (match-data integers reuse t)))
1803 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1804 "Make a replacement with `replace-match', editing `\\?'.
1805 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1806 check for `\\?' is made to save time. MATCH-DATA is used for the
1807 replacement. In case editing is done, it is changed to use markers.
1809 The return value is non-nil if there has been no `\\?' or NOEDIT was
1810 passed in. If LITERAL is set, no checking is done, anyway."
1811 (unless (or literal noedit)
1812 (setq noedit t)
1813 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1814 newtext)
1815 (setq newtext
1816 (read-string "Edit replacement string: "
1817 (prog1
1818 (cons
1819 (replace-match "" t t newtext 3)
1820 (1+ (match-beginning 3)))
1821 (setq match-data
1822 (replace-match-data
1823 nil match-data match-data))))
1824 noedit nil)))
1825 (set-match-data match-data)
1826 (replace-match newtext fixedcase literal)
1827 noedit)
1829 (defvar replace-search-function nil
1830 "Function to use when searching for strings to replace.
1831 It is used by `query-replace' and `replace-string', and is called
1832 with three arguments, as if it were `search-forward'.")
1834 (defvar replace-re-search-function nil
1835 "Function to use when searching for regexps to replace.
1836 It is used by `query-replace-regexp', `replace-regexp',
1837 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1838 It is called with three arguments, as if it were
1839 `re-search-forward'.")
1841 (defun perform-replace (from-string replacements
1842 query-flag regexp-flag delimited-flag
1843 &optional repeat-count map start end)
1844 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1845 Don't use this in your own program unless you want to query and set the mark
1846 just as `query-replace' does. Instead, write a simple loop like this:
1848 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1849 (replace-match \"foobar\" nil nil))
1851 which will run faster and probably do exactly what you want. Please
1852 see the documentation of `replace-match' to find out how to simulate
1853 `case-replace'.
1855 This function returns nil if and only if there were no matches to
1856 make, or the user didn't cancel the call."
1857 (or map (setq map query-replace-map))
1858 (and query-flag minibuffer-auto-raise
1859 (raise-frame (window-frame (minibuffer-window))))
1860 (let* ((case-fold-search
1861 (if (and case-fold-search search-upper-case)
1862 (isearch-no-upper-case-p from-string regexp-flag)
1863 case-fold-search))
1864 (nocasify (not (and case-replace case-fold-search)))
1865 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1866 (search-string from-string)
1867 (real-match-data nil) ; The match data for the current match.
1868 (next-replacement nil)
1869 ;; This is non-nil if we know there is nothing for the user
1870 ;; to edit in the replacement.
1871 (noedit nil)
1872 (keep-going t)
1873 (stack nil)
1874 (replace-count 0)
1875 (nonempty-match nil)
1876 (multi-buffer nil)
1877 (recenter-last-op nil) ; Start cycling order with initial position.
1879 ;; If non-nil, it is marker saying where in the buffer to stop.
1880 (limit nil)
1882 ;; Data for the next match. If a cons, it has the same format as
1883 ;; (match-data); otherwise it is t if a match is possible at point.
1884 (match-again t)
1886 (message
1887 (if query-flag
1888 (apply 'propertize
1889 (substitute-command-keys
1890 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1891 minibuffer-prompt-properties))))
1893 ;; If region is active, in Transient Mark mode, operate on region.
1894 (when start
1895 (setq limit (copy-marker (max start end)))
1896 (goto-char (min start end))
1897 (deactivate-mark))
1899 ;; If last typed key in previous call of multi-buffer perform-replace
1900 ;; was `automatic-all', don't ask more questions in next files
1901 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
1902 (setq query-flag nil multi-buffer t))
1904 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1905 ;; containing a function and its first argument. The function is
1906 ;; called to generate each replacement like this:
1907 ;; (funcall (car replacements) (cdr replacements) replace-count)
1908 ;; It must return a string.
1909 (cond
1910 ((stringp replacements)
1911 (setq next-replacement replacements
1912 replacements nil))
1913 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1914 (or repeat-count (setq repeat-count 1))
1915 (setq replacements (cons 'replace-loop-through-replacements
1916 (vector repeat-count repeat-count
1917 replacements replacements)))))
1919 (when query-replace-lazy-highlight
1920 (setq isearch-lazy-highlight-last-string nil))
1922 (push-mark)
1923 (undo-boundary)
1924 (unwind-protect
1925 ;; Loop finding occurrences that perhaps should be replaced.
1926 (while (and keep-going
1927 (not (or (eobp) (and limit (>= (point) limit))))
1928 ;; Let-bind global isearch-* variables to values used
1929 ;; to search the next replacement. These let-bindings
1930 ;; should be effective both at the time of calling
1931 ;; `isearch-search-fun-default' and also at the
1932 ;; time of funcalling `search-function'.
1933 ;; These isearch-* bindings can't be placed higher
1934 ;; outside of this loop because then another I-search
1935 ;; used after `recursive-edit' might override them.
1936 (let* ((isearch-regexp regexp-flag)
1937 (isearch-word delimited-flag)
1938 (isearch-lax-whitespace
1939 replace-lax-whitespace)
1940 (isearch-regexp-lax-whitespace
1941 replace-regexp-lax-whitespace)
1942 (isearch-case-fold-search case-fold-search)
1943 (isearch-adjusted nil)
1944 (isearch-nonincremental t) ; don't use lax word mode
1945 (isearch-forward t)
1946 (search-function
1947 (or (if regexp-flag
1948 replace-re-search-function
1949 replace-search-function)
1950 (isearch-search-fun-default))))
1951 ;; Use the next match if it is already known;
1952 ;; otherwise, search for a match after moving forward
1953 ;; one char if progress is required.
1954 (setq real-match-data
1955 (cond ((consp match-again)
1956 (goto-char (nth 1 match-again))
1957 (replace-match-data
1958 t real-match-data match-again))
1959 ;; MATCH-AGAIN non-nil means accept an
1960 ;; adjacent match.
1961 (match-again
1962 (and
1963 (funcall search-function search-string
1964 limit t)
1965 ;; For speed, use only integers and
1966 ;; reuse the list used last time.
1967 (replace-match-data t real-match-data)))
1968 ((and (< (1+ (point)) (point-max))
1969 (or (null limit)
1970 (< (1+ (point)) limit)))
1971 ;; If not accepting adjacent matches,
1972 ;; move one char to the right before
1973 ;; searching again. Undo the motion
1974 ;; if the search fails.
1975 (let ((opoint (point)))
1976 (forward-char 1)
1977 (if (funcall
1978 search-function search-string
1979 limit t)
1980 (replace-match-data
1981 t real-match-data)
1982 (goto-char opoint)
1983 nil)))))))
1985 ;; Record whether the match is nonempty, to avoid an infinite loop
1986 ;; repeatedly matching the same empty string.
1987 (setq nonempty-match
1988 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1990 ;; If the match is empty, record that the next one can't be
1991 ;; adjacent.
1993 ;; Otherwise, if matching a regular expression, do the next
1994 ;; match now, since the replacement for this match may
1995 ;; affect whether the next match is adjacent to this one.
1996 ;; If that match is empty, don't use it.
1997 (setq match-again
1998 (and nonempty-match
1999 (or (not regexp-flag)
2000 (and (looking-at search-string)
2001 (let ((match (match-data)))
2002 (and (/= (nth 0 match) (nth 1 match))
2003 match))))))
2005 ;; Optionally ignore matches that have a read-only property.
2006 (unless (and query-replace-skip-read-only
2007 (text-property-not-all
2008 (nth 0 real-match-data) (nth 1 real-match-data)
2009 'read-only nil))
2011 ;; Calculate the replacement string, if necessary.
2012 (when replacements
2013 (set-match-data real-match-data)
2014 (setq next-replacement
2015 (funcall (car replacements) (cdr replacements)
2016 replace-count)))
2017 (if (not query-flag)
2018 (progn
2019 (unless (or literal noedit)
2020 (replace-highlight
2021 (nth 0 real-match-data) (nth 1 real-match-data)
2022 start end search-string
2023 regexp-flag delimited-flag case-fold-search))
2024 (setq noedit
2025 (replace-match-maybe-edit
2026 next-replacement nocasify literal
2027 noedit real-match-data)
2028 replace-count (1+ replace-count)))
2029 (undo-boundary)
2030 (let (done replaced key def)
2031 ;; Loop reading commands until one of them sets done,
2032 ;; which means it has finished handling this
2033 ;; occurrence. Any command that sets `done' should
2034 ;; leave behind proper match data for the stack.
2035 ;; Commands not setting `done' need to adjust
2036 ;; `real-match-data'.
2037 (while (not done)
2038 (set-match-data real-match-data)
2039 (replace-highlight
2040 (match-beginning 0) (match-end 0)
2041 start end search-string
2042 regexp-flag delimited-flag case-fold-search)
2043 ;; Bind message-log-max so we don't fill up the message log
2044 ;; with a bunch of identical messages.
2045 (let ((message-log-max nil)
2046 (replacement-presentation
2047 (if query-replace-show-replacement
2048 (save-match-data
2049 (set-match-data real-match-data)
2050 (match-substitute-replacement next-replacement
2051 nocasify literal))
2052 next-replacement)))
2053 (message message
2054 (query-replace-descr from-string)
2055 (query-replace-descr replacement-presentation)))
2056 (setq key (read-event))
2057 ;; Necessary in case something happens during read-event
2058 ;; that clobbers the match data.
2059 (set-match-data real-match-data)
2060 (setq key (vector key))
2061 (setq def (lookup-key map key))
2062 ;; Restore the match data while we process the command.
2063 (cond ((eq def 'help)
2064 (with-output-to-temp-buffer "*Help*"
2065 (princ
2066 (concat "Query replacing "
2067 (if delimited-flag "word " "")
2068 (if regexp-flag "regexp " "")
2069 from-string " with "
2070 next-replacement ".\n\n"
2071 (substitute-command-keys
2072 query-replace-help)))
2073 (with-current-buffer standard-output
2074 (help-mode))))
2075 ((eq def 'exit)
2076 (setq keep-going nil)
2077 (setq done t))
2078 ((eq def 'exit-current)
2079 (setq multi-buffer t keep-going nil done t))
2080 ((eq def 'backup)
2081 (if stack
2082 (let ((elt (pop stack)))
2083 (goto-char (nth 0 elt))
2084 (setq replaced (nth 1 elt)
2085 real-match-data
2086 (replace-match-data
2087 t real-match-data
2088 (nth 2 elt))))
2089 (message "No previous match")
2090 (ding 'no-terminate)
2091 (sit-for 1)))
2092 ((eq def 'act)
2093 (or replaced
2094 (setq noedit
2095 (replace-match-maybe-edit
2096 next-replacement nocasify literal
2097 noedit real-match-data)
2098 replace-count (1+ replace-count)))
2099 (setq done t replaced t))
2100 ((eq def 'act-and-exit)
2101 (or replaced
2102 (setq noedit
2103 (replace-match-maybe-edit
2104 next-replacement nocasify literal
2105 noedit real-match-data)
2106 replace-count (1+ replace-count)))
2107 (setq keep-going nil)
2108 (setq done t replaced t))
2109 ((eq def 'act-and-show)
2110 (if (not replaced)
2111 (setq noedit
2112 (replace-match-maybe-edit
2113 next-replacement nocasify literal
2114 noedit real-match-data)
2115 replace-count (1+ replace-count)
2116 real-match-data (replace-match-data
2117 t real-match-data)
2118 replaced t)))
2119 ((or (eq def 'automatic) (eq def 'automatic-all))
2120 (or replaced
2121 (setq noedit
2122 (replace-match-maybe-edit
2123 next-replacement nocasify literal
2124 noedit real-match-data)
2125 replace-count (1+ replace-count)))
2126 (setq done t query-flag nil replaced t)
2127 (if (eq def 'automatic-all) (setq multi-buffer t)))
2128 ((eq def 'skip)
2129 (setq done t))
2130 ((eq def 'recenter)
2131 ;; `this-command' has the value `query-replace',
2132 ;; so we need to bind it to `recenter-top-bottom'
2133 ;; to allow it to detect a sequence of `C-l'.
2134 (let ((this-command 'recenter-top-bottom)
2135 (last-command 'recenter-top-bottom))
2136 (recenter-top-bottom)))
2137 ((eq def 'edit)
2138 (let ((opos (point-marker)))
2139 (setq real-match-data (replace-match-data
2140 nil real-match-data
2141 real-match-data))
2142 (goto-char (match-beginning 0))
2143 (save-excursion
2144 (save-window-excursion
2145 (recursive-edit)))
2146 (goto-char opos)
2147 (set-marker opos nil))
2148 ;; Before we make the replacement,
2149 ;; decide whether the search string
2150 ;; can match again just after this match.
2151 (if (and regexp-flag nonempty-match)
2152 (setq match-again (and (looking-at search-string)
2153 (match-data)))))
2154 ;; Edit replacement.
2155 ((eq def 'edit-replacement)
2156 (setq real-match-data (replace-match-data
2157 nil real-match-data
2158 real-match-data)
2159 next-replacement
2160 (read-string "Edit replacement string: "
2161 next-replacement)
2162 noedit nil)
2163 (if replaced
2164 (set-match-data real-match-data)
2165 (setq noedit
2166 (replace-match-maybe-edit
2167 next-replacement nocasify literal noedit
2168 real-match-data)
2169 replaced t))
2170 (setq done t))
2172 ((eq def 'delete-and-edit)
2173 (replace-match "" t t)
2174 (setq real-match-data (replace-match-data
2175 nil real-match-data))
2176 (replace-dehighlight)
2177 (save-excursion (recursive-edit))
2178 (setq replaced t))
2179 ;; Note: we do not need to treat `exit-prefix'
2180 ;; specially here, since we reread
2181 ;; any unrecognized character.
2183 (setq this-command 'mode-exited)
2184 (setq keep-going nil)
2185 (setq unread-command-events
2186 (append (listify-key-sequence key)
2187 unread-command-events))
2188 (setq done t)))
2189 (when query-replace-lazy-highlight
2190 ;; Force lazy rehighlighting only after replacements.
2191 (if (not (memq def '(skip backup)))
2192 (setq isearch-lazy-highlight-last-string nil)))
2193 (unless (eq def 'recenter)
2194 ;; Reset recenter cycling order to initial position.
2195 (setq recenter-last-op nil)))
2196 ;; Record previous position for ^ when we move on.
2197 ;; Change markers to numbers in the match data
2198 ;; since lots of markers slow down editing.
2199 (push (list (point) replaced
2200 ;;; If the replacement has already happened, all we need is the
2201 ;;; current match start and end. We could get this with a trivial
2202 ;;; match like
2203 ;;; (save-excursion (goto-char (match-beginning 0))
2204 ;;; (search-forward (match-string 0))
2205 ;;; (match-data t))
2206 ;;; if we really wanted to avoid manually constructing match data.
2207 ;;; Adding current-buffer is necessary so that match-data calls can
2208 ;;; return markers which are appropriate for editing.
2209 (if replaced
2210 (list
2211 (match-beginning 0)
2212 (match-end 0)
2213 (current-buffer))
2214 (match-data t)))
2215 stack)))))
2217 (replace-dehighlight))
2218 (or unread-command-events
2219 (message "Replaced %d occurrence%s"
2220 replace-count
2221 (if (= replace-count 1) "" "s")))
2222 (or (and keep-going stack) multi-buffer)))
2224 (defvar replace-overlay nil)
2226 (defun replace-highlight (match-beg match-end range-beg range-end
2227 search-string regexp-flag delimited-flag
2228 case-fold-search)
2229 (if query-replace-highlight
2230 (if replace-overlay
2231 (move-overlay replace-overlay match-beg match-end (current-buffer))
2232 (setq replace-overlay (make-overlay match-beg match-end))
2233 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2234 (overlay-put replace-overlay 'face 'query-replace)))
2235 (if query-replace-lazy-highlight
2236 (let ((isearch-string search-string)
2237 (isearch-regexp regexp-flag)
2238 (isearch-word delimited-flag)
2239 (isearch-lax-whitespace
2240 replace-lax-whitespace)
2241 (isearch-regexp-lax-whitespace
2242 replace-regexp-lax-whitespace)
2243 (isearch-case-fold-search case-fold-search)
2244 (isearch-forward t)
2245 (isearch-other-end match-beg)
2246 (isearch-error nil))
2247 (isearch-lazy-highlight-new-loop range-beg range-end))))
2249 (defun replace-dehighlight ()
2250 (when replace-overlay
2251 (delete-overlay replace-overlay))
2252 (when query-replace-lazy-highlight
2253 (lazy-highlight-cleanup lazy-highlight-cleanup)
2254 (setq isearch-lazy-highlight-last-string nil)))
2256 ;;; replace.el ends here