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