]> code.delx.au - gnu-emacs/blob - lisp/replace.el
Further progress making Isearch, Ispell, Replace work with Follow Mode.
[gnu-emacs] / lisp / replace.el
1 ;;; replace.el --- replace commands for Emacs
2
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2015 Free
4 ;; Software Foundation, Inc.
5
6 ;; Maintainer: emacs-devel@gnu.org
7 ;; Package: emacs
8
9 ;; This file is part of GNU Emacs.
10
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
15
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
20
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23
24 ;;; Commentary:
25
26 ;; This package supplies the string and regular-expression replace functions
27 ;; documented in the Emacs user's manual.
28
29 ;;; Code:
30
31 (defcustom case-replace t
32 "Non-nil means `query-replace' should preserve case in replacements."
33 :type 'boolean
34 :group 'matching)
35
36 (defcustom replace-character-fold nil
37 "Non-nil means 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 'sexp
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 :version "22.1")
1272
1273 (defcustom list-matching-lines-default-context-lines 0
1274 "Default number of context lines included around `list-matching-lines' matches.
1275 A negative number means to include that many lines before the match.
1276 A positive number means to include that many lines both before and after."
1277 :type 'integer
1278 :group 'matching)
1279
1280 (defalias 'list-matching-lines 'occur)
1281
1282 (defcustom list-matching-lines-face 'match
1283 "Face used by \\[list-matching-lines] to show the text that matches.
1284 If the value is nil, don't highlight the matching portions specially."
1285 :type 'face
1286 :group 'matching)
1287
1288 (defcustom list-matching-lines-buffer-name-face 'underline
1289 "Face used by \\[list-matching-lines] to show the names of buffers.
1290 If the value is nil, don't highlight the buffer names specially."
1291 :type 'face
1292 :group 'matching)
1293
1294 (defcustom list-matching-lines-prefix-face 'shadow
1295 "Face used by \\[list-matching-lines] to show the prefix column.
1296 If the face doesn't differ from the default face,
1297 don't highlight the prefix with line numbers specially."
1298 :type 'face
1299 :group 'matching
1300 :version "24.4")
1301
1302 (defcustom occur-excluded-properties
1303 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1304 yank-handler follow-link)
1305 "Text properties to discard when copying lines to the *Occur* buffer.
1306 The value should be a list of text properties to discard or t,
1307 which means to discard all text properties."
1308 :type '(choice (const :tag "All" t) (repeat symbol))
1309 :group 'matching
1310 :version "22.1")
1311
1312 (defun occur-read-primary-args ()
1313 (let* ((perform-collect (consp current-prefix-arg))
1314 (regexp (read-regexp (if perform-collect
1315 "Collect strings matching regexp"
1316 "List lines matching regexp")
1317 'regexp-history-last)))
1318 (list regexp
1319 (if perform-collect
1320 ;; Perform collect operation
1321 (if (zerop (regexp-opt-depth regexp))
1322 ;; No subexpression so collect the entire match.
1323 "\\&"
1324 ;; Get the regexp for collection pattern.
1325 (let ((default (car occur-collect-regexp-history)))
1326 (read-regexp
1327 (format "Regexp to collect (default %s): " default)
1328 default 'occur-collect-regexp-history)))
1329 ;; Otherwise normal occur takes numerical prefix argument.
1330 (when current-prefix-arg
1331 (prefix-numeric-value current-prefix-arg))))))
1332
1333 (defun occur-rename-buffer (&optional unique-p interactive-p)
1334 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1335 Here `original-buffer-name' is the buffer name where Occur was originally run.
1336 When given the prefix argument, or called non-interactively, the renaming
1337 will not clobber the existing buffer(s) of that name, but use
1338 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1339 if you always want a separate *Occur* buffer for each buffer where you
1340 invoke `occur'."
1341 (interactive "P\np")
1342 (with-current-buffer
1343 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1344 (rename-buffer (concat "*Occur: "
1345 (mapconcat #'buffer-name
1346 (car (cddr occur-revert-arguments)) "/")
1347 "*")
1348 (or unique-p (not interactive-p)))))
1349
1350 (defun occur (regexp &optional nlines)
1351 "Show all lines in the current buffer containing a match for REGEXP.
1352 If a match spreads across multiple lines, all those lines are shown.
1353
1354 Each line is displayed with NLINES lines before and after, or -NLINES
1355 before if NLINES is negative.
1356 NLINES defaults to `list-matching-lines-default-context-lines'.
1357 Interactively it is the prefix arg.
1358
1359 The lines are shown in a buffer named `*Occur*'.
1360 It serves as a menu to find any of the occurrences in this buffer.
1361 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1362
1363 If REGEXP contains upper case characters (excluding those preceded by `\\')
1364 and `search-upper-case' is non-nil, the matching is case-sensitive.
1365
1366 When NLINES is a string or when the function is called
1367 interactively with prefix argument without a number (`C-u' alone
1368 as prefix) the matching strings are collected into the `*Occur*'
1369 buffer by using NLINES as a replacement regexp. NLINES may
1370 contain \\& and \\N which convention follows `replace-match'.
1371 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1372 \"\\1\" for NLINES collects all the function names in a lisp
1373 program. When there is no parenthesized subexpressions in REGEXP
1374 the entire match is collected. In any case the searched buffer
1375 is not modified."
1376 (interactive (occur-read-primary-args))
1377 (occur-1 regexp nlines (list (current-buffer))))
1378
1379 (defvar ido-ignore-item-temp-list)
1380
1381 (defun multi-occur (bufs regexp &optional nlines)
1382 "Show all lines in buffers BUFS containing a match for REGEXP.
1383 This function acts on multiple buffers; otherwise, it is exactly like
1384 `occur'. When you invoke this command interactively, you must specify
1385 the buffer names that you want, one by one.
1386 See also `multi-occur-in-matching-buffers'."
1387 (interactive
1388 (cons
1389 (let* ((bufs (list (read-buffer "First buffer to search: "
1390 (current-buffer) t)))
1391 (buf nil)
1392 (ido-ignore-item-temp-list bufs))
1393 (while (not (string-equal
1394 (setq buf (read-buffer
1395 (if (eq read-buffer-function #'ido-read-buffer)
1396 "Next buffer to search (C-j to end): "
1397 "Next buffer to search (RET to end): ")
1398 nil t))
1399 ""))
1400 (add-to-list 'bufs buf)
1401 (setq ido-ignore-item-temp-list bufs))
1402 (nreverse (mapcar #'get-buffer bufs)))
1403 (occur-read-primary-args)))
1404 (occur-1 regexp nlines bufs))
1405
1406 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1407 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1408 Normally BUFREGEXP matches against each buffer's visited file name,
1409 but if you specify a prefix argument, it matches against the buffer name.
1410 See also `multi-occur'."
1411 (interactive
1412 (cons
1413 (let* ((default (car regexp-history))
1414 (input
1415 (read-regexp
1416 (if current-prefix-arg
1417 "List lines in buffers whose names match regexp: "
1418 "List lines in buffers whose filenames match regexp: "))))
1419 (if (equal input "")
1420 default
1421 input))
1422 (occur-read-primary-args)))
1423 (when bufregexp
1424 (occur-1 regexp nil
1425 (delq nil
1426 (mapcar (lambda (buf)
1427 (when (if allbufs
1428 (string-match bufregexp
1429 (buffer-name buf))
1430 (and (buffer-file-name buf)
1431 (string-match bufregexp
1432 (buffer-file-name buf))))
1433 buf))
1434 (buffer-list))))))
1435
1436 (defun occur-regexp-descr (regexp)
1437 (format " for %s\"%s\""
1438 (or (get-text-property 0 'isearch-regexp-function-descr regexp)
1439 "")
1440 (if (get-text-property 0 'isearch-string regexp)
1441 (propertize
1442 (query-replace-descr
1443 (get-text-property 0 'isearch-string regexp))
1444 'help-echo regexp)
1445 (query-replace-descr regexp))))
1446
1447 (defun occur-1 (regexp nlines bufs &optional buf-name)
1448 (unless (and regexp (not (equal regexp "")))
1449 (error "Occur doesn't work with the empty regexp"))
1450 (unless buf-name
1451 (setq buf-name "*Occur*"))
1452 (let (occur-buf
1453 (active-bufs (delq nil (mapcar #'(lambda (buf)
1454 (when (buffer-live-p buf) buf))
1455 bufs))))
1456 ;; Handle the case where one of the buffers we're searching is the
1457 ;; output buffer. Just rename it.
1458 (when (member buf-name (mapcar 'buffer-name active-bufs))
1459 (with-current-buffer (get-buffer buf-name)
1460 (rename-uniquely)))
1461
1462 ;; Now find or create the output buffer.
1463 ;; If we just renamed that buffer, we will make a new one here.
1464 (setq occur-buf (get-buffer-create buf-name))
1465
1466 (with-current-buffer occur-buf
1467 (if (stringp nlines)
1468 (fundamental-mode) ;; This is for collect operation.
1469 (occur-mode))
1470 (let ((inhibit-read-only t)
1471 ;; Don't generate undo entries for creation of the initial contents.
1472 (buffer-undo-list t))
1473 (erase-buffer)
1474 (let ((count
1475 (if (stringp nlines)
1476 ;; Treat nlines as a regexp to collect.
1477 (let ((bufs active-bufs)
1478 (count 0))
1479 (while bufs
1480 (with-current-buffer (car bufs)
1481 (save-excursion
1482 (goto-char (point-min))
1483 (while (re-search-forward regexp nil t)
1484 ;; Insert the replacement regexp.
1485 (let ((str (match-substitute-replacement nlines)))
1486 (if str
1487 (with-current-buffer occur-buf
1488 (insert str)
1489 (setq count (1+ count))
1490 (or (zerop (current-column))
1491 (insert "\n"))))))))
1492 (setq bufs (cdr bufs)))
1493 count)
1494 ;; Perform normal occur.
1495 (occur-engine
1496 regexp active-bufs occur-buf
1497 (or nlines list-matching-lines-default-context-lines)
1498 (if (and case-fold-search search-upper-case)
1499 (isearch-no-upper-case-p regexp t)
1500 case-fold-search)
1501 list-matching-lines-buffer-name-face
1502 (if (face-differs-from-default-p list-matching-lines-prefix-face)
1503 list-matching-lines-prefix-face)
1504 list-matching-lines-face
1505 (not (eq occur-excluded-properties t))))))
1506 (let* ((bufcount (length active-bufs))
1507 (diff (- (length bufs) bufcount)))
1508 (message "Searched %d buffer%s%s; %s match%s%s"
1509 bufcount (if (= bufcount 1) "" "s")
1510 (if (zerop diff) "" (format " (%d killed)" diff))
1511 (if (zerop count) "no" (format "%d" count))
1512 (if (= count 1) "" "es")
1513 ;; Don't display regexp if with remaining text
1514 ;; it is longer than window-width.
1515 (if (> (+ (length (or (get-text-property 0 'isearch-string regexp)
1516 regexp))
1517 42)
1518 (window-width))
1519 "" (occur-regexp-descr regexp))))
1520 (setq occur-revert-arguments (list regexp nlines bufs))
1521 (if (= count 0)
1522 (kill-buffer occur-buf)
1523 (display-buffer occur-buf)
1524 (setq next-error-last-buffer occur-buf)
1525 (setq buffer-read-only t)
1526 (set-buffer-modified-p nil)
1527 (run-hooks 'occur-hook)))))))
1528
1529 (defun occur-engine (regexp buffers out-buf nlines case-fold
1530 title-face prefix-face match-face keep-props)
1531 (with-current-buffer out-buf
1532 (let ((global-lines 0) ;; total count of matching lines
1533 (global-matches 0) ;; total count of matches
1534 (coding nil)
1535 (case-fold-search case-fold))
1536 ;; Map over all the buffers
1537 (dolist (buf buffers)
1538 (when (buffer-live-p buf)
1539 (let ((lines 0) ;; count of matching lines
1540 (matches 0) ;; count of matches
1541 (curr-line 1) ;; line count
1542 (prev-line nil) ;; line number of prev match endpt
1543 (prev-after-lines nil) ;; context lines of prev match
1544 (matchbeg 0)
1545 (origpt nil)
1546 (begpt nil)
1547 (endpt nil)
1548 (marker nil)
1549 (curstring "")
1550 (ret nil)
1551 (inhibit-field-text-motion t)
1552 (headerpt (with-current-buffer out-buf (point))))
1553 (with-current-buffer buf
1554 (or coding
1555 ;; Set CODING only if the current buffer locally
1556 ;; binds buffer-file-coding-system.
1557 (not (local-variable-p 'buffer-file-coding-system))
1558 (setq coding buffer-file-coding-system))
1559 (save-excursion
1560 (goto-char (point-min)) ;; begin searching in the buffer
1561 (while (not (eobp))
1562 (setq origpt (point))
1563 (when (setq endpt (re-search-forward regexp nil t))
1564 (setq lines (1+ lines)) ;; increment matching lines count
1565 (setq matchbeg (match-beginning 0))
1566 ;; Get beginning of first match line and end of the last.
1567 (save-excursion
1568 (goto-char matchbeg)
1569 (setq begpt (line-beginning-position))
1570 (goto-char endpt)
1571 (setq endpt (line-end-position)))
1572 ;; Sum line numbers up to the first match line.
1573 (setq curr-line (+ curr-line (count-lines origpt begpt)))
1574 (setq marker (make-marker))
1575 (set-marker marker matchbeg)
1576 (setq curstring (occur-engine-line begpt endpt keep-props))
1577 ;; Highlight the matches
1578 (let ((len (length curstring))
1579 (start 0))
1580 ;; Count empty lines that don't use next loop (Bug#22062).
1581 (when (zerop len)
1582 (setq matches (1+ matches)))
1583 (while (and (< start len)
1584 (string-match regexp curstring start))
1585 (setq matches (1+ matches))
1586 (add-text-properties
1587 (match-beginning 0) (match-end 0)
1588 '(occur-match t) curstring)
1589 (when match-face
1590 ;; Add `match-face' to faces copied from the buffer.
1591 (add-face-text-property
1592 (match-beginning 0) (match-end 0)
1593 match-face nil curstring))
1594 ;; Avoid infloop (Bug#7593).
1595 (let ((end (match-end 0)))
1596 (setq start (if (= start end) (1+ start) end)))))
1597 ;; Generate the string to insert for this match
1598 (let* ((match-prefix
1599 ;; Using 7 digits aligns tabs properly.
1600 (apply #'propertize (format "%7d:" curr-line)
1601 (append
1602 (when prefix-face
1603 `(font-lock-face ,prefix-face))
1604 `(occur-prefix t mouse-face (highlight)
1605 ;; Allow insertion of text at
1606 ;; the end of the prefix (for
1607 ;; Occur Edit mode).
1608 front-sticky t rear-nonsticky t
1609 occur-target ,marker follow-link t
1610 help-echo "mouse-2: go to this occurrence"))))
1611 (match-str
1612 ;; We don't put `mouse-face' on the newline,
1613 ;; because that loses. And don't put it
1614 ;; on context lines to reduce flicker.
1615 (propertize curstring 'mouse-face (list 'highlight)
1616 'occur-target marker
1617 'follow-link t
1618 'help-echo
1619 "mouse-2: go to this occurrence"))
1620 (out-line
1621 (concat
1622 match-prefix
1623 ;; Add non-numeric prefix to all non-first lines
1624 ;; of multi-line matches.
1625 (replace-regexp-in-string
1626 "\n"
1627 (if prefix-face
1628 (propertize "\n :" 'font-lock-face prefix-face)
1629 "\n :")
1630 match-str)
1631 ;; Add marker at eol, but no mouse props.
1632 (propertize "\n" 'occur-target marker)))
1633 (data
1634 (if (= nlines 0)
1635 ;; The simple display style
1636 out-line
1637 ;; The complex multi-line display style.
1638 (setq ret (occur-context-lines
1639 out-line nlines keep-props begpt endpt
1640 curr-line prev-line prev-after-lines
1641 prefix-face))
1642 ;; Set first elem of the returned list to `data',
1643 ;; and the second elem to `prev-after-lines'.
1644 (setq prev-after-lines (nth 1 ret))
1645 (nth 0 ret))))
1646 ;; Actually insert the match display data
1647 (with-current-buffer out-buf
1648 (insert data)))
1649 (goto-char endpt))
1650 (if endpt
1651 (progn
1652 ;; Sum line numbers between first and last match lines.
1653 (setq curr-line (+ curr-line (count-lines begpt endpt)
1654 ;; Add 1 for empty last match line since
1655 ;; count-lines returns 1 line less.
1656 (if (and (bolp) (eolp)) 1 0)))
1657 ;; On to the next match...
1658 (forward-line 1))
1659 (goto-char (point-max)))
1660 (setq prev-line (1- curr-line)))
1661 ;; Flush remaining context after-lines.
1662 (when prev-after-lines
1663 (with-current-buffer out-buf
1664 (insert (apply #'concat (occur-engine-add-prefix
1665 prev-after-lines prefix-face)))))))
1666 (when (not (zerop lines)) ;; is the count zero?
1667 (setq global-lines (+ global-lines lines)
1668 global-matches (+ global-matches matches))
1669 (with-current-buffer out-buf
1670 (goto-char headerpt)
1671 (let ((beg (point))
1672 end)
1673 (insert (propertize
1674 (format "%d match%s%s%s in buffer: %s\n"
1675 matches (if (= matches 1) "" "es")
1676 ;; Don't display the same number of lines
1677 ;; and matches in case of 1 match per line.
1678 (if (= lines matches)
1679 "" (format " in %d line%s"
1680 lines (if (= lines 1) "" "s")))
1681 ;; Don't display regexp for multi-buffer.
1682 (if (> (length buffers) 1)
1683 "" (occur-regexp-descr regexp))
1684 (buffer-name buf))
1685 'read-only t))
1686 (setq end (point))
1687 (add-text-properties beg end `(occur-title ,buf))
1688 (when title-face
1689 (add-face-text-property beg end title-face)))
1690 (goto-char (point-min)))))))
1691 ;; Display total match count and regexp for multi-buffer.
1692 (when (and (not (zerop global-lines)) (> (length buffers) 1))
1693 (goto-char (point-min))
1694 (let ((beg (point))
1695 end)
1696 (insert (format "%d match%s%s total%s:\n"
1697 global-matches (if (= global-matches 1) "" "es")
1698 ;; Don't display the same number of lines
1699 ;; and matches in case of 1 match per line.
1700 (if (= global-lines global-matches)
1701 "" (format " in %d line%s"
1702 global-lines (if (= global-lines 1) "" "s")))
1703 (occur-regexp-descr regexp)))
1704 (setq end (point))
1705 (when title-face
1706 (add-face-text-property beg end title-face)))
1707 (goto-char (point-min)))
1708 (if coding
1709 ;; CODING is buffer-file-coding-system of the first buffer
1710 ;; that locally binds it. Let's use it also for the output
1711 ;; buffer.
1712 (set-buffer-file-coding-system coding))
1713 ;; Return the number of matches
1714 global-matches)))
1715
1716 (defun occur-engine-line (beg end &optional keep-props)
1717 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1718 (text-property-not-all beg end 'fontified t))
1719 (if (fboundp 'jit-lock-fontify-now)
1720 (jit-lock-fontify-now beg end)))
1721 (if (and keep-props (not (eq occur-excluded-properties t)))
1722 (let ((str (buffer-substring beg end)))
1723 (remove-list-of-text-properties
1724 0 (length str) occur-excluded-properties str)
1725 str)
1726 (buffer-substring-no-properties beg end)))
1727
1728 (defun occur-engine-add-prefix (lines &optional prefix-face)
1729 (mapcar
1730 #'(lambda (line)
1731 (concat (if prefix-face
1732 (propertize " :" 'font-lock-face prefix-face)
1733 " :")
1734 line "\n"))
1735 lines))
1736
1737 (defun occur-accumulate-lines (count &optional keep-props pt)
1738 (save-excursion
1739 (when pt
1740 (goto-char pt))
1741 (let ((forwardp (> count 0))
1742 result beg end moved)
1743 (while (not (or (zerop count)
1744 (if forwardp
1745 (eobp)
1746 (and (bobp) (not moved)))))
1747 (setq count (+ count (if forwardp -1 1)))
1748 (setq beg (line-beginning-position)
1749 end (line-end-position))
1750 (push (occur-engine-line beg end keep-props) result)
1751 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1752 (nreverse result))))
1753
1754 ;; Generate context display for occur.
1755 ;; OUT-LINE is the line where the match is.
1756 ;; NLINES and KEEP-PROPS are args to occur-engine.
1757 ;; CURR-LINE is line count of the current match,
1758 ;; PREV-LINE is line count of the previous match,
1759 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1760 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1761 ;; then concatenate them all together.
1762 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1763 curr-line prev-line prev-after-lines
1764 &optional prefix-face)
1765 ;; Find after- and before-context lines of the current match.
1766 (let ((before-lines
1767 (nreverse (cdr (occur-accumulate-lines
1768 (- (1+ (abs nlines))) keep-props begpt))))
1769 (after-lines
1770 (cdr (occur-accumulate-lines
1771 (1+ nlines) keep-props endpt)))
1772 separator)
1773
1774 ;; Combine after-lines of the previous match
1775 ;; with before-lines of the current match.
1776
1777 (when prev-after-lines
1778 ;; Don't overlap prev after-lines with current before-lines.
1779 (if (>= (+ prev-line (length prev-after-lines))
1780 (- curr-line (length before-lines)))
1781 (setq prev-after-lines
1782 (butlast prev-after-lines
1783 (- (length prev-after-lines)
1784 (- curr-line prev-line (length before-lines) 1))))
1785 ;; Separate non-overlapping context lines with a dashed line.
1786 (setq separator "-------\n")))
1787
1788 (when prev-line
1789 ;; Don't overlap current before-lines with previous match line.
1790 (if (<= (- curr-line (length before-lines))
1791 prev-line)
1792 (setq before-lines
1793 (nthcdr (- (length before-lines)
1794 (- curr-line prev-line 1))
1795 before-lines))
1796 ;; Separate non-overlapping before-context lines.
1797 (unless (> nlines 0)
1798 (setq separator "-------\n"))))
1799
1800 (list
1801 ;; Return a list where the first element is the output line.
1802 (apply #'concat
1803 (append
1804 (if prev-after-lines
1805 (occur-engine-add-prefix prev-after-lines prefix-face))
1806 (if separator
1807 (list (if prefix-face
1808 (propertize separator 'font-lock-face prefix-face)
1809 separator)))
1810 (occur-engine-add-prefix before-lines prefix-face)
1811 (list out-line)))
1812 ;; And the second element is the list of context after-lines.
1813 (if (> nlines 0) after-lines))))
1814
1815 \f
1816 ;; It would be nice to use \\[...], but there is no reasonable way
1817 ;; to make that display both SPC and Y.
1818 (defconst query-replace-help
1819 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1820 RET or `q' to exit, Period to replace one match and exit,
1821 Comma to replace but not move point immediately,
1822 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1823 C-w to delete match and recursive edit,
1824 C-l to clear the screen, redisplay, and offer same replacement again,
1825 ! to replace all remaining matches in this buffer with no more questions,
1826 ^ to move point back to previous match,
1827 E to edit the replacement string.
1828 In multi-buffer replacements type `Y' to replace all remaining
1829 matches in all remaining buffers with no more questions,
1830 `N' to skip to the next buffer without replacing remaining matches
1831 in the current buffer."
1832 "Help message while in `query-replace'.")
1833
1834 (defvar query-replace-map
1835 (let ((map (make-sparse-keymap)))
1836 (define-key map " " 'act)
1837 (define-key map "\d" 'skip)
1838 (define-key map [delete] 'skip)
1839 (define-key map [backspace] 'skip)
1840 (define-key map "y" 'act)
1841 (define-key map "n" 'skip)
1842 (define-key map "Y" 'act)
1843 (define-key map "N" 'skip)
1844 (define-key map "e" 'edit-replacement)
1845 (define-key map "E" 'edit-replacement)
1846 (define-key map "," 'act-and-show)
1847 (define-key map "q" 'exit)
1848 (define-key map "\r" 'exit)
1849 (define-key map [return] 'exit)
1850 (define-key map "." 'act-and-exit)
1851 (define-key map "\C-r" 'edit)
1852 (define-key map "\C-w" 'delete-and-edit)
1853 (define-key map "\C-l" 'recenter)
1854 (define-key map "!" 'automatic)
1855 (define-key map "^" 'backup)
1856 (define-key map "\C-h" 'help)
1857 (define-key map [f1] 'help)
1858 (define-key map [help] 'help)
1859 (define-key map "?" 'help)
1860 (define-key map "\C-g" 'quit)
1861 (define-key map "\C-]" 'quit)
1862 (define-key map "\C-v" 'scroll-up)
1863 (define-key map "\M-v" 'scroll-down)
1864 (define-key map [next] 'scroll-up)
1865 (define-key map [prior] 'scroll-down)
1866 (define-key map [?\C-\M-v] 'scroll-other-window)
1867 (define-key map [M-next] 'scroll-other-window)
1868 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1869 (define-key map [M-prior] 'scroll-other-window-down)
1870 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1871 ;; should check for ESC specially.
1872 ;; (define-key map "\e" 'exit-prefix)
1873 (define-key map [escape] 'exit-prefix)
1874 map)
1875 "Keymap of responses to questions posed by commands like `query-replace'.
1876 The \"bindings\" in this map are not commands; they are answers.
1877 The valid answers include `act', `skip', `act-and-show',
1878 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1879 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1880 `edit', `edit-replacement', `delete-and-edit', `automatic',
1881 `backup', `quit', and `help'.
1882
1883 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1884
1885 (defvar multi-query-replace-map
1886 (let ((map (make-sparse-keymap)))
1887 (set-keymap-parent map query-replace-map)
1888 (define-key map "Y" 'automatic-all)
1889 (define-key map "N" 'exit-current)
1890 map)
1891 "Keymap that defines additional bindings for multi-buffer replacements.
1892 It extends its parent map `query-replace-map' with new bindings to
1893 operate on a set of buffers/files. The difference with its parent map
1894 is the additional answers `automatic-all' to replace all remaining
1895 matches in all remaining buffers with no more questions, and
1896 `exit-current' to skip remaining matches in the current buffer
1897 and to continue with the next buffer in the sequence.")
1898
1899 (defun replace-match-string-symbols (n)
1900 "Process a list (and any sub-lists), expanding certain symbols.
1901 Symbol Expands To
1902 N (match-string N) (where N is a string of digits)
1903 #N (string-to-number (match-string N))
1904 & (match-string 0)
1905 #& (string-to-number (match-string 0))
1906 # replace-count
1907
1908 Note that these symbols must be preceded by a backslash in order to
1909 type them using Lisp syntax."
1910 (while (consp n)
1911 (cond
1912 ((consp (car n))
1913 (replace-match-string-symbols (car n))) ;Process sub-list
1914 ((symbolp (car n))
1915 (let ((name (symbol-name (car n))))
1916 (cond
1917 ((string-match "^[0-9]+$" name)
1918 (setcar n (list 'match-string (string-to-number name))))
1919 ((string-match "^#[0-9]+$" name)
1920 (setcar n (list 'string-to-number
1921 (list 'match-string
1922 (string-to-number (substring name 1))))))
1923 ((string= "&" name)
1924 (setcar n '(match-string 0)))
1925 ((string= "#&" name)
1926 (setcar n '(string-to-number (match-string 0))))
1927 ((string= "#" name)
1928 (setcar n 'replace-count))))))
1929 (setq n (cdr n))))
1930
1931 (defun replace-eval-replacement (expression count)
1932 (let* ((replace-count count)
1933 err
1934 (replacement
1935 (condition-case err
1936 (eval expression)
1937 (error
1938 (error "Error evaluating replacement expression: %S" err)))))
1939 (if (stringp replacement)
1940 replacement
1941 (prin1-to-string replacement t))))
1942
1943 (defun replace-quote (replacement)
1944 "Quote a replacement string.
1945 This just doubles all backslashes in REPLACEMENT and
1946 returns the resulting string. If REPLACEMENT is not
1947 a string, it is first passed through `prin1-to-string'
1948 with the `noescape' argument set.
1949
1950 `match-data' is preserved across the call."
1951 (save-match-data
1952 (replace-regexp-in-string "\\\\" "\\\\"
1953 (if (stringp replacement)
1954 replacement
1955 (prin1-to-string replacement t))
1956 t t)))
1957
1958 (defun replace-loop-through-replacements (data count)
1959 ;; DATA is a vector containing the following values:
1960 ;; 0 next-rotate-count
1961 ;; 1 repeat-count
1962 ;; 2 next-replacement
1963 ;; 3 replacements
1964 (if (= (aref data 0) count)
1965 (progn
1966 (aset data 0 (+ count (aref data 1)))
1967 (let ((next (cdr (aref data 2))))
1968 (aset data 2 (if (consp next) next (aref data 3))))))
1969 (car (aref data 2)))
1970
1971 (defun replace-match-data (integers reuse &optional new)
1972 "Like `match-data', but markers in REUSE get invalidated.
1973 If NEW is non-nil, it is set and returned instead of fresh data,
1974 but coerced to the correct value of INTEGERS."
1975 (or (and new
1976 (progn
1977 (set-match-data new)
1978 (and (eq new reuse)
1979 (eq (null integers) (markerp (car reuse)))
1980 new)))
1981 (match-data integers reuse t)))
1982
1983 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data backward)
1984 "Make a replacement with `replace-match', editing `\\?'.
1985 FIXEDCASE, LITERAL are passed to `replace-match' (which see).
1986 After possibly editing it (if `\\?' is present), NEWTEXT is also
1987 passed to `replace-match'. If NOEDIT is true, no check for `\\?'
1988 is made (to save time). MATCH-DATA is used for the replacement.
1989 In case editing is done, it is changed to use markers.
1990
1991 The return value is non-nil if there has been no `\\?' or NOEDIT was
1992 passed in. If LITERAL is set, no checking is done, anyway."
1993 (unless (or literal noedit)
1994 (setq noedit t)
1995 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1996 newtext)
1997 (setq newtext
1998 (read-string "Edit replacement string: "
1999 (prog1
2000 (cons
2001 (replace-match "" t t newtext 3)
2002 (1+ (match-beginning 3)))
2003 (setq match-data
2004 (replace-match-data
2005 nil match-data match-data))))
2006 noedit nil)))
2007 (set-match-data match-data)
2008 (replace-match newtext fixedcase literal)
2009 ;; `replace-match' leaves point at the end of the replacement text,
2010 ;; so move point to the beginning when replacing backward.
2011 (when backward (goto-char (nth 0 match-data)))
2012 noedit)
2013
2014 (defvar replace-update-post-hook nil
2015 "Function(s) to call after query-replace has found a match in the buffer.")
2016
2017 (defvar replace-search-function nil
2018 "Function to use when searching for strings to replace.
2019 It is used by `query-replace' and `replace-string', and is called
2020 with three arguments, as if it were `search-forward'.")
2021
2022 (defvar replace-re-search-function nil
2023 "Function to use when searching for regexps to replace.
2024 It is used by `query-replace-regexp', `replace-regexp',
2025 `query-replace-regexp-eval', and `map-query-replace-regexp'.
2026 It is called with three arguments, as if it were
2027 `re-search-forward'.")
2028
2029 (defun replace-search (search-string limit regexp-flag delimited-flag
2030 case-fold-search backward)
2031 "Search for the next occurrence of SEARCH-STRING to replace."
2032 ;; Let-bind global isearch-* variables to values used
2033 ;; to search the next replacement. These let-bindings
2034 ;; should be effective both at the time of calling
2035 ;; `isearch-search-fun-default' and also at the
2036 ;; time of funcalling `search-function'.
2037 ;; These isearch-* bindings can't be placed higher
2038 ;; outside of this function because then another I-search
2039 ;; used after `recursive-edit' might override them.
2040 (let* ((isearch-regexp regexp-flag)
2041 (isearch-regexp-function (or delimited-flag
2042 (and replace-character-fold
2043 (not regexp-flag)
2044 #'character-fold-to-regexp)))
2045 (isearch-lax-whitespace
2046 replace-lax-whitespace)
2047 (isearch-regexp-lax-whitespace
2048 replace-regexp-lax-whitespace)
2049 (isearch-case-fold-search case-fold-search)
2050 (isearch-adjusted nil)
2051 (isearch-nonincremental t) ; don't use lax word mode
2052 (isearch-forward (not backward))
2053 (search-function
2054 (or (if regexp-flag
2055 replace-re-search-function
2056 replace-search-function)
2057 (isearch-search-fun-default))))
2058 (funcall search-function search-string limit t)))
2059
2060 (defvar replace-overlay nil)
2061
2062 (defun replace-highlight (match-beg match-end range-beg range-end
2063 search-string regexp-flag delimited-flag
2064 case-fold-search backward)
2065 (if query-replace-highlight
2066 (if replace-overlay
2067 (move-overlay replace-overlay match-beg match-end (current-buffer))
2068 (setq replace-overlay (make-overlay match-beg match-end))
2069 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2070 (overlay-put replace-overlay 'face 'query-replace)))
2071 (if query-replace-lazy-highlight
2072 (let ((isearch-string search-string)
2073 (isearch-regexp regexp-flag)
2074 (isearch-regexp-function delimited-flag)
2075 (isearch-lax-whitespace
2076 replace-lax-whitespace)
2077 (isearch-regexp-lax-whitespace
2078 replace-regexp-lax-whitespace)
2079 (isearch-case-fold-search case-fold-search)
2080 (isearch-forward (not backward))
2081 (isearch-other-end match-beg)
2082 (isearch-error nil))
2083 (isearch-lazy-highlight-new-loop range-beg range-end))))
2084
2085 (defun replace-dehighlight ()
2086 (when replace-overlay
2087 (delete-overlay replace-overlay))
2088 (when query-replace-lazy-highlight
2089 (lazy-highlight-cleanup lazy-highlight-cleanup)
2090 (setq isearch-lazy-highlight-last-string nil))
2091 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
2092 (isearch-clean-overlays))
2093
2094 (defun perform-replace (from-string replacements
2095 query-flag regexp-flag delimited-flag
2096 &optional repeat-count map start end backward region-noncontiguous-p)
2097 "Subroutine of `query-replace'. Its complexity handles interactive queries.
2098 Don't use this in your own program unless you want to query and set the mark
2099 just as `query-replace' does. Instead, write a simple loop like this:
2100
2101 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2102 (replace-match \"foobar\" nil nil))
2103
2104 which will run faster and probably do exactly what you want. Please
2105 see the documentation of `replace-match' to find out how to simulate
2106 `case-replace'.
2107
2108 This function returns nil if and only if there were no matches to
2109 make, or the user didn't cancel the call.
2110
2111 REPLACEMENTS is either a string, a list of strings, or a cons cell
2112 containing a function and its first argument. The function is
2113 called to generate each replacement like this:
2114 (funcall (car replacements) (cdr replacements) replace-count)
2115 It must return a string."
2116 (or map (setq map query-replace-map))
2117 (and query-flag minibuffer-auto-raise
2118 (raise-frame (window-frame (minibuffer-window))))
2119 (let* ((case-fold-search
2120 (if (and case-fold-search search-upper-case)
2121 (isearch-no-upper-case-p from-string regexp-flag)
2122 case-fold-search))
2123 (nocasify (not (and case-replace case-fold-search)))
2124 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2125 (search-string from-string)
2126 (real-match-data nil) ; The match data for the current match.
2127 (next-replacement nil)
2128 ;; This is non-nil if we know there is nothing for the user
2129 ;; to edit in the replacement.
2130 (noedit nil)
2131 (keep-going t)
2132 (stack nil)
2133 (replace-count 0)
2134 (skip-read-only-count 0)
2135 (skip-filtered-count 0)
2136 (skip-invisible-count 0)
2137 (nonempty-match nil)
2138 (multi-buffer nil)
2139 (recenter-last-op nil) ; Start cycling order with initial position.
2140
2141 ;; If non-nil, it is marker saying where in the buffer to stop.
2142 (limit nil)
2143 ;; Use local binding in add-function below.
2144 (isearch-filter-predicate isearch-filter-predicate)
2145 (region-bounds nil)
2146
2147 ;; Data for the next match. If a cons, it has the same format as
2148 ;; (match-data); otherwise it is t if a match is possible at point.
2149 (match-again t)
2150
2151 (message
2152 (if query-flag
2153 (apply 'propertize
2154 (substitute-command-keys
2155 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2156 minibuffer-prompt-properties))))
2157
2158 ;; Unless a single contiguous chunk is selected, operate on multiple chunks.
2159 (when region-noncontiguous-p
2160 (setq region-bounds
2161 (mapcar (lambda (position)
2162 (cons (copy-marker (car position))
2163 (copy-marker (cdr position))))
2164 (funcall region-extract-function 'bounds)))
2165 (add-function :after-while isearch-filter-predicate
2166 (lambda (start end)
2167 (delq nil (mapcar
2168 (lambda (bounds)
2169 (and
2170 (>= start (car bounds))
2171 (<= start (cdr bounds))
2172 (>= end (car bounds))
2173 (<= end (cdr bounds))))
2174 region-bounds)))))
2175
2176 ;; If region is active, in Transient Mark mode, operate on region.
2177 (if backward
2178 (when end
2179 (setq limit (copy-marker (min start end)))
2180 (goto-char (max start end))
2181 (deactivate-mark))
2182 (when start
2183 (setq limit (copy-marker (max start end)))
2184 (goto-char (min start end))
2185 (deactivate-mark)))
2186
2187 ;; If last typed key in previous call of multi-buffer perform-replace
2188 ;; was `automatic-all', don't ask more questions in next files
2189 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2190 (setq query-flag nil multi-buffer t))
2191
2192 (cond
2193 ((stringp replacements)
2194 (setq next-replacement replacements
2195 replacements nil))
2196 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2197 (or repeat-count (setq repeat-count 1))
2198 (setq replacements (cons 'replace-loop-through-replacements
2199 (vector repeat-count repeat-count
2200 replacements replacements)))))
2201
2202 (when query-replace-lazy-highlight
2203 (setq isearch-lazy-highlight-last-string nil))
2204
2205 (push-mark)
2206 (undo-boundary)
2207 (unwind-protect
2208 ;; Loop finding occurrences that perhaps should be replaced.
2209 (while (and keep-going
2210 (if backward
2211 (not (or (bobp) (and limit (<= (point) limit))))
2212 (not (or (eobp) (and limit (>= (point) limit)))))
2213 ;; Use the next match if it is already known;
2214 ;; otherwise, search for a match after moving forward
2215 ;; one char if progress is required.
2216 (setq real-match-data
2217 (cond ((consp match-again)
2218 (goto-char (if backward
2219 (nth 0 match-again)
2220 (nth 1 match-again)))
2221 (replace-match-data
2222 t real-match-data match-again))
2223 ;; MATCH-AGAIN non-nil means accept an
2224 ;; adjacent match.
2225 (match-again
2226 (and
2227 (replace-search search-string limit
2228 regexp-flag delimited-flag
2229 case-fold-search backward)
2230 ;; For speed, use only integers and
2231 ;; reuse the list used last time.
2232 (replace-match-data t real-match-data)))
2233 ((and (if backward
2234 (> (1- (point)) (point-min))
2235 (< (1+ (point)) (point-max)))
2236 (or (null limit)
2237 (if backward
2238 (> (1- (point)) limit)
2239 (< (1+ (point)) limit))))
2240 ;; If not accepting adjacent matches,
2241 ;; move one char to the right before
2242 ;; searching again. Undo the motion
2243 ;; if the search fails.
2244 (let ((opoint (point)))
2245 (forward-char (if backward -1 1))
2246 (if (replace-search search-string limit
2247 regexp-flag delimited-flag
2248 case-fold-search backward)
2249 (replace-match-data
2250 t real-match-data)
2251 (goto-char opoint)
2252 nil))))))
2253
2254 ;; Record whether the match is nonempty, to avoid an infinite loop
2255 ;; repeatedly matching the same empty string.
2256 (setq nonempty-match
2257 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2258
2259 ;; If the match is empty, record that the next one can't be
2260 ;; adjacent.
2261
2262 ;; Otherwise, if matching a regular expression, do the next
2263 ;; match now, since the replacement for this match may
2264 ;; affect whether the next match is adjacent to this one.
2265 ;; If that match is empty, don't use it.
2266 (setq match-again
2267 (and nonempty-match
2268 (or (not regexp-flag)
2269 (and (if backward
2270 (looking-back search-string nil)
2271 (looking-at search-string))
2272 (let ((match (match-data)))
2273 (and (/= (nth 0 match) (nth 1 match))
2274 match))))))
2275
2276 (cond
2277 ;; Optionally ignore matches that have a read-only property.
2278 ((not (or (not query-replace-skip-read-only)
2279 (not (text-property-not-all
2280 (nth 0 real-match-data) (nth 1 real-match-data)
2281 'read-only nil))))
2282 (setq skip-read-only-count (1+ skip-read-only-count)))
2283 ;; Optionally filter out matches.
2284 ((not (funcall isearch-filter-predicate
2285 (nth 0 real-match-data) (nth 1 real-match-data)))
2286 (setq skip-filtered-count (1+ skip-filtered-count)))
2287 ;; Optionally ignore invisible matches.
2288 ((not (or (eq search-invisible t)
2289 ;; Don't open overlays for automatic replacements.
2290 (and (not query-flag) search-invisible)
2291 ;; Open hidden overlays for interactive replacements.
2292 (not (isearch-range-invisible
2293 (nth 0 real-match-data) (nth 1 real-match-data)))))
2294 (setq skip-invisible-count (1+ skip-invisible-count)))
2295 (t
2296 ;; Calculate the replacement string, if necessary.
2297 (when replacements
2298 (set-match-data real-match-data)
2299 (setq next-replacement
2300 (funcall (car replacements) (cdr replacements)
2301 replace-count)))
2302 (if (not query-flag)
2303 (progn
2304 (unless (or literal noedit)
2305 (replace-highlight
2306 (nth 0 real-match-data) (nth 1 real-match-data)
2307 start end search-string
2308 regexp-flag delimited-flag case-fold-search backward))
2309 (setq noedit
2310 (replace-match-maybe-edit
2311 next-replacement nocasify literal
2312 noedit real-match-data backward)
2313 replace-count (1+ replace-count)))
2314 (undo-boundary)
2315 (let (done replaced key def)
2316 ;; Loop reading commands until one of them sets done,
2317 ;; which means it has finished handling this
2318 ;; occurrence. Any command that sets `done' should
2319 ;; leave behind proper match data for the stack.
2320 ;; Commands not setting `done' need to adjust
2321 ;; `real-match-data'.
2322 (while (not done)
2323 (set-match-data real-match-data)
2324 (run-hooks 'replace-update-post-hook) ; Before `replace-highlight'.
2325 (replace-highlight
2326 (match-beginning 0) (match-end 0)
2327 start end search-string
2328 regexp-flag delimited-flag case-fold-search backward)
2329 ;; Bind message-log-max so we don't fill up the message log
2330 ;; with a bunch of identical messages.
2331 (let ((message-log-max nil)
2332 (replacement-presentation
2333 (if query-replace-show-replacement
2334 (save-match-data
2335 (set-match-data real-match-data)
2336 (match-substitute-replacement next-replacement
2337 nocasify literal))
2338 next-replacement)))
2339 (message message
2340 (query-replace-descr from-string)
2341 (query-replace-descr replacement-presentation)))
2342 (setq key (read-event))
2343 ;; Necessary in case something happens during read-event
2344 ;; that clobbers the match data.
2345 (set-match-data real-match-data)
2346 (setq key (vector key))
2347 (setq def (lookup-key map key))
2348 ;; Restore the match data while we process the command.
2349 (cond ((eq def 'help)
2350 (with-output-to-temp-buffer "*Help*"
2351 (princ
2352 (concat "Query replacing "
2353 (if delimited-flag
2354 (or (and (symbolp delimited-flag)
2355 (get delimited-flag 'isearch-message-prefix))
2356 "word ") "")
2357 (if regexp-flag "regexp " "")
2358 (if backward "backward " "")
2359 from-string " with "
2360 next-replacement ".\n\n"
2361 (substitute-command-keys
2362 query-replace-help)))
2363 (with-current-buffer standard-output
2364 (help-mode))))
2365 ((eq def 'exit)
2366 (setq keep-going nil)
2367 (setq done t))
2368 ((eq def 'exit-current)
2369 (setq multi-buffer t keep-going nil done t))
2370 ((eq def 'backup)
2371 (if stack
2372 (let ((elt (pop stack)))
2373 (goto-char (nth 0 elt))
2374 (setq replaced (nth 1 elt)
2375 real-match-data
2376 (replace-match-data
2377 t real-match-data
2378 (nth 2 elt))))
2379 (message "No previous match")
2380 (ding 'no-terminate)
2381 (sit-for 1)))
2382 ((eq def 'act)
2383 (or replaced
2384 (setq noedit
2385 (replace-match-maybe-edit
2386 next-replacement nocasify literal
2387 noedit real-match-data backward)
2388 replace-count (1+ replace-count)))
2389 (setq done t replaced t))
2390 ((eq def 'act-and-exit)
2391 (or replaced
2392 (setq noedit
2393 (replace-match-maybe-edit
2394 next-replacement nocasify literal
2395 noedit real-match-data backward)
2396 replace-count (1+ replace-count)))
2397 (setq keep-going nil)
2398 (setq done t replaced t))
2399 ((eq def 'act-and-show)
2400 (if (not replaced)
2401 (setq noedit
2402 (replace-match-maybe-edit
2403 next-replacement nocasify literal
2404 noedit real-match-data backward)
2405 replace-count (1+ replace-count)
2406 real-match-data (replace-match-data
2407 t real-match-data)
2408 replaced t)))
2409 ((or (eq def 'automatic) (eq def 'automatic-all))
2410 (or replaced
2411 (setq noedit
2412 (replace-match-maybe-edit
2413 next-replacement nocasify literal
2414 noedit real-match-data backward)
2415 replace-count (1+ replace-count)))
2416 (setq done t query-flag nil replaced t)
2417 (if (eq def 'automatic-all) (setq multi-buffer t)))
2418 ((eq def 'skip)
2419 (setq done t))
2420 ((eq def 'recenter)
2421 ;; `this-command' has the value `query-replace',
2422 ;; so we need to bind it to `recenter-top-bottom'
2423 ;; to allow it to detect a sequence of `C-l'.
2424 (let ((this-command 'recenter-top-bottom)
2425 (last-command 'recenter-top-bottom))
2426 (recenter-top-bottom)))
2427 ((eq def 'edit)
2428 (let ((opos (point-marker)))
2429 (setq real-match-data (replace-match-data
2430 nil real-match-data
2431 real-match-data))
2432 (goto-char (match-beginning 0))
2433 (save-excursion
2434 (save-window-excursion
2435 (recursive-edit)))
2436 (goto-char opos)
2437 (set-marker opos nil))
2438 ;; Before we make the replacement,
2439 ;; decide whether the search string
2440 ;; can match again just after this match.
2441 (if (and regexp-flag nonempty-match)
2442 (setq match-again (and (looking-at search-string)
2443 (match-data)))))
2444 ;; Edit replacement.
2445 ((eq def 'edit-replacement)
2446 (setq real-match-data (replace-match-data
2447 nil real-match-data
2448 real-match-data)
2449 next-replacement
2450 (read-string "Edit replacement string: "
2451 next-replacement)
2452 noedit nil)
2453 (if replaced
2454 (set-match-data real-match-data)
2455 (setq noedit
2456 (replace-match-maybe-edit
2457 next-replacement nocasify literal noedit
2458 real-match-data backward)
2459 replaced t))
2460 (setq done t))
2461
2462 ((eq def 'delete-and-edit)
2463 (replace-match "" t t)
2464 (setq real-match-data (replace-match-data
2465 nil real-match-data))
2466 (replace-dehighlight)
2467 (save-excursion (recursive-edit))
2468 (setq replaced t))
2469 ;; Note: we do not need to treat `exit-prefix'
2470 ;; specially here, since we reread
2471 ;; any unrecognized character.
2472 (t
2473 (setq this-command 'mode-exited)
2474 (setq keep-going nil)
2475 (setq unread-command-events
2476 (append (listify-key-sequence key)
2477 unread-command-events))
2478 (setq done t)))
2479 (when query-replace-lazy-highlight
2480 ;; Force lazy rehighlighting only after replacements.
2481 (if (not (memq def '(skip backup)))
2482 (setq isearch-lazy-highlight-last-string nil)))
2483 (unless (eq def 'recenter)
2484 ;; Reset recenter cycling order to initial position.
2485 (setq recenter-last-op nil)))
2486 ;; Record previous position for ^ when we move on.
2487 ;; Change markers to numbers in the match data
2488 ;; since lots of markers slow down editing.
2489 (push (list (point) replaced
2490 ;;; If the replacement has already happened, all we need is the
2491 ;;; current match start and end. We could get this with a trivial
2492 ;;; match like
2493 ;;; (save-excursion (goto-char (match-beginning 0))
2494 ;;; (search-forward (match-string 0))
2495 ;;; (match-data t))
2496 ;;; if we really wanted to avoid manually constructing match data.
2497 ;;; Adding current-buffer is necessary so that match-data calls can
2498 ;;; return markers which are appropriate for editing.
2499 (if replaced
2500 (list
2501 (match-beginning 0)
2502 (match-end 0)
2503 (current-buffer))
2504 (match-data t)))
2505 stack))))))
2506
2507 (replace-dehighlight))
2508 (or unread-command-events
2509 (message "Replaced %d occurrence%s%s"
2510 replace-count
2511 (if (= replace-count 1) "" "s")
2512 (if (> (+ skip-read-only-count
2513 skip-filtered-count
2514 skip-invisible-count) 0)
2515 (format " (skipped %s)"
2516 (mapconcat
2517 'identity
2518 (delq nil (list
2519 (if (> skip-read-only-count 0)
2520 (format "%s read-only"
2521 skip-read-only-count))
2522 (if (> skip-invisible-count 0)
2523 (format "%s invisible"
2524 skip-invisible-count))
2525 (if (> skip-filtered-count 0)
2526 (format "%s filtered out"
2527 skip-filtered-count))))
2528 ", "))
2529 "")))
2530 (or (and keep-going stack) multi-buffer)))
2531
2532 ;;; replace.el ends here