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