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