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