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