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