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