Merge from mainline.
[bpt/emacs.git] / lisp / replace.el
1 ;;; replace.el --- replace commands for Emacs
2
3 ;; Copyright (C) 1985, 1986, 1987, 1992, 1994, 1996, 1997, 2000, 2001,
4 ;; 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010
5 ;; Free Software Foundation, Inc.
6
7 ;; Maintainer: FSF
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 (defvar query-replace-history nil
37 "Default history list for query-replace commands.
38 See `query-replace-from-history-variable' and
39 `query-replace-to-history-variable'.")
40
41 (defvar query-replace-defaults nil
42 "Default values of FROM-STRING and TO-STRING for `query-replace'.
43 This is a cons cell (FROM-STRING . TO-STRING), or nil if there is
44 no default value.")
45
46 (defvar query-replace-interactive nil
47 "Non-nil means `query-replace' uses the last search string.
48 That becomes the \"string to replace\".")
49
50 (defcustom query-replace-from-history-variable 'query-replace-history
51 "History list to use for the FROM argument of `query-replace' commands.
52 The value of this variable should be a symbol; that symbol
53 is used as a variable to hold a history list for the strings
54 or patterns to be replaced."
55 :group 'matching
56 :type 'symbol
57 :version "20.3")
58
59 (defcustom query-replace-to-history-variable 'query-replace-history
60 "History list to use for the TO argument of `query-replace' commands.
61 The value of this variable should be a symbol; that symbol
62 is used as a variable to hold a history list for replacement
63 strings or patterns."
64 :group 'matching
65 :type 'symbol
66 :version "20.3")
67
68 (defcustom query-replace-skip-read-only nil
69 "Non-nil means `query-replace' and friends ignore read-only matches."
70 :type 'boolean
71 :group 'matching
72 :version "22.1")
73
74 (defcustom query-replace-show-replacement t
75 "Non-nil means to show what actual replacement text will be."
76 :type 'boolean
77 :group 'matching
78 :version "23.1")
79
80 (defcustom query-replace-highlight t
81 "Non-nil means to highlight matches during query replacement."
82 :type 'boolean
83 :group 'matching)
84
85 (defcustom query-replace-lazy-highlight t
86 "Controls the lazy-highlighting during query replacements.
87 When non-nil, all text in the buffer matching the current match
88 is highlighted lazily using isearch lazy highlighting (see
89 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
90 :type 'boolean
91 :group 'lazy-highlight
92 :group 'matching
93 :version "22.1")
94
95 (defface query-replace
96 '((t (:inherit isearch)))
97 "Face for highlighting query replacement matches."
98 :group 'matching
99 :version "22.1")
100
101 (defun query-replace-descr (string)
102 (mapconcat 'isearch-text-char-description string ""))
103
104 (defun query-replace-read-from (prompt regexp-flag)
105 "Query and return the `from' argument of a query-replace operation.
106 The return value can also be a pair (FROM . TO) indicating that the user
107 wants to replace FROM with TO."
108 (if query-replace-interactive
109 (car (if regexp-flag regexp-search-ring search-ring))
110 (let* ((history-add-new-input nil)
111 (from
112 ;; The save-excursion here is in case the user marks and copies
113 ;; a region in order to specify the minibuffer input.
114 ;; That should not clobber the region for the query-replace itself.
115 (save-excursion
116 (read-from-minibuffer
117 (if query-replace-defaults
118 (format "%s (default %s -> %s): " prompt
119 (query-replace-descr (car query-replace-defaults))
120 (query-replace-descr (cdr query-replace-defaults)))
121 (format "%s: " prompt))
122 nil nil nil
123 query-replace-from-history-variable
124 nil t))))
125 (if (and (zerop (length from)) query-replace-defaults)
126 (cons (car query-replace-defaults)
127 (query-replace-compile-replacement
128 (cdr query-replace-defaults) regexp-flag))
129 (add-to-history query-replace-from-history-variable from nil t)
130 ;; Warn if user types \n or \t, but don't reject the input.
131 (and regexp-flag
132 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
133 (let ((match (match-string 3 from)))
134 (cond
135 ((string= match "\\n")
136 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
137 ((string= match "\\t")
138 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
139 (sit-for 2)))
140 from))))
141
142 (defun query-replace-compile-replacement (to regexp-flag)
143 "Maybe convert a regexp replacement TO to Lisp.
144 Returns a list suitable for `perform-replace' if necessary,
145 the original string if not."
146 (if (and regexp-flag
147 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
148 (let (pos list char)
149 (while
150 (progn
151 (setq pos (match-end 0))
152 (push (substring to 0 (- pos 2)) list)
153 (setq char (aref to (1- pos))
154 to (substring to pos))
155 (cond ((eq char ?\#)
156 (push '(number-to-string replace-count) list))
157 ((eq char ?\,)
158 (setq pos (read-from-string to))
159 (push `(replace-quote ,(car pos)) list)
160 (let ((end
161 ;; Swallow a space after a symbol
162 ;; if there is a space.
163 (if (and (or (symbolp (car pos))
164 ;; Swallow a space after 'foo
165 ;; but not after (quote foo).
166 (and (eq (car-safe (car pos)) 'quote)
167 (not (= ?\( (aref to 0)))))
168 (eq (string-match " " to (cdr pos))
169 (cdr pos)))
170 (1+ (cdr pos))
171 (cdr pos))))
172 (setq to (substring to end)))))
173 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
174 (setq to (nreverse (delete "" (cons to list))))
175 (replace-match-string-symbols to)
176 (cons 'replace-eval-replacement
177 (if (cdr to)
178 (cons 'concat to)
179 (car to))))
180 to))
181
182
183 (defun query-replace-read-to (from prompt regexp-flag)
184 "Query and return the `to' argument of a query-replace operation."
185 (query-replace-compile-replacement
186 (save-excursion
187 (let* ((history-add-new-input nil)
188 (to (read-from-minibuffer
189 (format "%s %s with: " prompt (query-replace-descr from))
190 nil nil nil
191 query-replace-to-history-variable from t)))
192 (add-to-history query-replace-to-history-variable to nil t)
193 (setq query-replace-defaults (cons from to))
194 to))
195 regexp-flag))
196
197 (defun query-replace-read-args (prompt regexp-flag &optional noerror)
198 (unless noerror
199 (barf-if-buffer-read-only))
200 (let* ((from (query-replace-read-from prompt regexp-flag))
201 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
202 (query-replace-read-to from prompt regexp-flag))))
203 (list from to current-prefix-arg)))
204
205 (defun query-replace (from-string to-string &optional delimited start end)
206 "Replace some occurrences of FROM-STRING with TO-STRING.
207 As each match is found, the user must type a character saying
208 what to do with it. For directions, type \\[help-command] at that time.
209
210 In Transient Mark mode, if the mark is active, operate on the contents
211 of the region. Otherwise, operate from point to the end of the buffer.
212
213 If `query-replace-interactive' is non-nil, the last incremental search
214 string is used as FROM-STRING--you don't have to specify it with the
215 minibuffer.
216
217 Matching is independent of case if `case-fold-search' is non-nil and
218 FROM-STRING has no uppercase letters. Replacement transfers the case
219 pattern of the old text to the new text, if `case-replace' and
220 `case-fold-search' are non-nil and FROM-STRING has no uppercase
221 letters. \(Transferring the case pattern means that if the old text
222 matched is all caps, or capitalized, then its replacement is upcased
223 or capitalized.)
224
225 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
226 only matches surrounded by word boundaries.
227 Fourth and fifth arg START and END specify the region to operate on.
228
229 To customize possible responses, change the \"bindings\" in `query-replace-map'."
230 (interactive
231 (let ((common
232 (query-replace-read-args
233 (concat "Query replace"
234 (if current-prefix-arg " word" "")
235 (if (and transient-mark-mode mark-active) " in region" ""))
236 nil)))
237 (list (nth 0 common) (nth 1 common) (nth 2 common)
238 ;; These are done separately here
239 ;; so that command-history will record these expressions
240 ;; rather than the values they had this time.
241 (if (and transient-mark-mode mark-active)
242 (region-beginning))
243 (if (and transient-mark-mode mark-active)
244 (region-end)))))
245 (perform-replace from-string to-string t nil delimited nil nil start end))
246
247 (define-key esc-map "%" 'query-replace)
248
249 (defun query-replace-regexp (regexp to-string &optional delimited start end)
250 "Replace some things after point matching REGEXP with TO-STRING.
251 As each match is found, the user must type a character saying
252 what to do with it. For directions, type \\[help-command] at that time.
253
254 In Transient Mark mode, if the mark is active, operate on the contents
255 of the region. Otherwise, operate from point to the end of the buffer.
256
257 If `query-replace-interactive' is non-nil, the last incremental search
258 regexp is used as REGEXP--you don't have to specify it with the
259 minibuffer.
260
261 Matching is independent of case if `case-fold-search' is non-nil and
262 REGEXP has no uppercase letters. Replacement transfers the case
263 pattern of the old text to the new text, if `case-replace' and
264 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
265 \(Transferring the case pattern means that if the old text matched is
266 all caps, or capitalized, then its replacement is upcased or
267 capitalized.)
268
269 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
270 only matches surrounded by word boundaries.
271 Fourth and fifth arg START and END specify the region to operate on.
272
273 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
274 and `\\=\\N' (where N is a digit) stands for
275 whatever what matched the Nth `\\(...\\)' in REGEXP.
276 `\\?' lets you edit the replacement text in the minibuffer
277 at the given position for each replacement.
278
279 In interactive calls, the replacement text can contain `\\,'
280 followed by a Lisp expression. Each
281 replacement evaluates that expression to compute the replacement
282 string. Inside of that expression, `\\&' is a string denoting the
283 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
284 for the whole or a partial match converted to a number with
285 `string-to-number', and `\\#' itself for the number of replacements
286 done so far (starting with zero).
287
288 If the replacement expression is a symbol, write a space after it
289 to terminate it. One space there, if any, will be discarded.
290
291 When using those Lisp features interactively in the replacement
292 text, TO-STRING is actually made a list instead of a string.
293 Use \\[repeat-complex-command] after this command for details."
294 (interactive
295 (let ((common
296 (query-replace-read-args
297 (concat "Query replace"
298 (if current-prefix-arg " word" "")
299 " regexp"
300 (if (and transient-mark-mode mark-active) " in region" ""))
301 t)))
302 (list (nth 0 common) (nth 1 common) (nth 2 common)
303 ;; These are done separately here
304 ;; so that command-history will record these expressions
305 ;; rather than the values they had this time.
306 (if (and transient-mark-mode mark-active)
307 (region-beginning))
308 (if (and transient-mark-mode mark-active)
309 (region-end)))))
310 (perform-replace regexp to-string t t delimited nil nil start end))
311
312 (define-key esc-map [?\C-%] 'query-replace-regexp)
313
314 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
315 "Replace some things after point matching REGEXP with the result of TO-EXPR.
316
317 Interactive use of this function is deprecated in favor of the
318 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
319 using `search-forward-regexp' and `replace-match' is preferred.
320
321 As each match is found, the user must type a character saying
322 what to do with it. For directions, type \\[help-command] at that time.
323
324 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
325 reference `replace-count' to get the number of replacements already made.
326 If the result of TO-EXPR is not a string, it is converted to one using
327 `prin1-to-string' with the NOESCAPE argument (which see).
328
329 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
330 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
331 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
332 Use `\\#&' or `\\#N' if you want a number instead of a string.
333 In interactive use, `\\#' in itself stands for `replace-count'.
334
335 In Transient Mark mode, if the mark is active, operate on the contents
336 of the region. Otherwise, operate from point to the end of the buffer.
337
338 If `query-replace-interactive' is non-nil, the last incremental search
339 regexp is used as REGEXP--you don't have to specify it with the
340 minibuffer.
341
342 Preserves case in each replacement if `case-replace' and `case-fold-search'
343 are non-nil and REGEXP has no uppercase letters.
344
345 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
346 only matches that are surrounded by word boundaries.
347 Fourth and fifth arg START and END specify the region to operate on."
348 (interactive
349 (progn
350 (barf-if-buffer-read-only)
351 (let* ((from
352 ;; Let-bind the history var to disable the "foo -> bar" default.
353 ;; Maybe we shouldn't disable this default, but for now I'll
354 ;; leave it off. --Stef
355 (let ((query-replace-to-history-variable nil))
356 (query-replace-read-from "Query replace regexp" t)))
357 (to (list (read-from-minibuffer
358 (format "Query replace regexp %s with eval: "
359 (query-replace-descr from))
360 nil nil t query-replace-to-history-variable from t))))
361 ;; We make TO a list because replace-match-string-symbols requires one,
362 ;; and the user might enter a single token.
363 (replace-match-string-symbols to)
364 (list from (car to) current-prefix-arg
365 (if (and transient-mark-mode mark-active)
366 (region-beginning))
367 (if (and transient-mark-mode mark-active)
368 (region-end))))))
369 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
370 t 'literal delimited nil nil start end))
371
372 (make-obsolete 'query-replace-regexp-eval
373 "for interactive use, use the special `\\,' feature of
374 `query-replace-regexp' instead. Non-interactively, a loop
375 using `search-forward-regexp' and `replace-match' is preferred." "22.1")
376
377 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
378 "Replace some matches for REGEXP with various strings, in rotation.
379 The second argument TO-STRINGS contains the replacement strings, separated
380 by spaces. This command works like `query-replace-regexp' except that
381 each successive replacement uses the next successive replacement string,
382 wrapping around from the last such string to the first.
383
384 In Transient Mark mode, if the mark is active, operate on the contents
385 of the region. Otherwise, operate from point to the end of the buffer.
386
387 Non-interactively, TO-STRINGS may be a list of replacement strings.
388
389 If `query-replace-interactive' is non-nil, the last incremental search
390 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
391
392 A prefix argument N says to use each replacement string N times
393 before rotating to the next.
394 Fourth and fifth arg START and END specify the region to operate on."
395 (interactive
396 (let* ((from (if query-replace-interactive
397 (car regexp-search-ring)
398 (read-from-minibuffer "Map query replace (regexp): "
399 nil nil nil
400 query-replace-from-history-variable
401 nil t)))
402 (to (read-from-minibuffer
403 (format "Query replace %s with (space-separated strings): "
404 (query-replace-descr from))
405 nil nil nil
406 query-replace-to-history-variable from t)))
407 (list from to
408 (and current-prefix-arg
409 (prefix-numeric-value current-prefix-arg))
410 (if (and transient-mark-mode mark-active)
411 (region-beginning))
412 (if (and transient-mark-mode mark-active)
413 (region-end)))))
414 (let (replacements)
415 (if (listp to-strings)
416 (setq replacements to-strings)
417 (while (/= (length to-strings) 0)
418 (if (string-match " " to-strings)
419 (setq replacements
420 (append replacements
421 (list (substring to-strings 0
422 (string-match " " to-strings))))
423 to-strings (substring to-strings
424 (1+ (string-match " " to-strings))))
425 (setq replacements (append replacements (list to-strings))
426 to-strings ""))))
427 (perform-replace regexp replacements t t nil n nil start end)))
428
429 (defun replace-string (from-string to-string &optional delimited start end)
430 "Replace occurrences of FROM-STRING with TO-STRING.
431 Preserve case in each match if `case-replace' and `case-fold-search'
432 are non-nil and FROM-STRING has no uppercase letters.
433 \(Preserving case means that if the string matched is all caps, or capitalized,
434 then its replacement is upcased or capitalized.)
435
436 In Transient Mark mode, if the mark is active, operate on the contents
437 of the region. Otherwise, operate from point to the end of the buffer.
438
439 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
440 only matches surrounded by word boundaries.
441 Fourth and fifth arg START and END specify the region to operate on.
442
443 If `query-replace-interactive' is non-nil, the last incremental search
444 string is used as FROM-STRING--you don't have to specify it with the
445 minibuffer.
446
447 This function is usually the wrong thing to use in a Lisp program.
448 What you probably want is a loop like this:
449 (while (search-forward FROM-STRING nil t)
450 (replace-match TO-STRING nil t))
451 which will run faster and will not set the mark or print anything.
452 \(You may need a more complex loop if FROM-STRING can match the null string
453 and TO-STRING is also null.)"
454 (interactive
455 (let ((common
456 (query-replace-read-args
457 (concat "Replace"
458 (if current-prefix-arg " word" "")
459 " string"
460 (if (and transient-mark-mode mark-active) " in region" ""))
461 nil)))
462 (list (nth 0 common) (nth 1 common) (nth 2 common)
463 (if (and transient-mark-mode mark-active)
464 (region-beginning))
465 (if (and transient-mark-mode mark-active)
466 (region-end)))))
467 (perform-replace from-string to-string nil nil delimited nil nil start end))
468
469 (defun replace-regexp (regexp to-string &optional delimited start end)
470 "Replace things after point matching REGEXP with TO-STRING.
471 Preserve case in each match if `case-replace' and `case-fold-search'
472 are non-nil and REGEXP has no uppercase letters.
473
474 In Transient Mark mode, if the mark is active, operate on the contents
475 of the region. Otherwise, operate from point to the end of the buffer.
476
477 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
478 only matches surrounded by word boundaries.
479 Fourth and fifth arg START and END specify the region to operate on.
480
481 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
482 and `\\=\\N' (where N is a digit) stands for
483 whatever what matched the Nth `\\(...\\)' in REGEXP.
484 `\\?' lets you edit the replacement text in the minibuffer
485 at the given position for each replacement.
486
487 In interactive calls, the replacement text may contain `\\,'
488 followed by a Lisp expression used as part of the replacement
489 text. Inside of that expression, `\\&' is a string denoting the
490 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
491 numeric values from `string-to-number', and `\\#' itself for
492 `replace-count', the number of replacements occurred so far.
493
494 If your Lisp expression is an identifier and the next letter in
495 the replacement string would be interpreted as part of it, you
496 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
497 for this particular case you may also enter `\\#' in the
498 replacement text directly.
499
500 When using those Lisp features interactively in the replacement
501 text, TO-STRING is actually made a list instead of a string.
502 Use \\[repeat-complex-command] after this command for details.
503
504 If `query-replace-interactive' is non-nil, the last incremental search
505 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
506
507 This function is usually the wrong thing to use in a Lisp program.
508 What you probably want is a loop like this:
509 (while (re-search-forward REGEXP nil t)
510 (replace-match TO-STRING nil nil))
511 which will run faster and will not set the mark or print anything."
512 (interactive
513 (let ((common
514 (query-replace-read-args
515 (concat "Replace"
516 (if current-prefix-arg " word" "")
517 " regexp"
518 (if (and transient-mark-mode mark-active) " in region" ""))
519 t)))
520 (list (nth 0 common) (nth 1 common) (nth 2 common)
521 (if (and transient-mark-mode mark-active)
522 (region-beginning))
523 (if (and transient-mark-mode mark-active)
524 (region-end)))))
525 (perform-replace regexp to-string nil t delimited nil nil start end))
526
527 \f
528 (defvar regexp-history nil
529 "History list for some commands that read regular expressions.
530
531 Maximum length of the history list is determined by the value
532 of `history-length', which see.")
533
534 (defun read-regexp (prompt &optional default-value)
535 "Read regexp as a string using the regexp history and some useful defaults.
536 Prompt for a regular expression with PROMPT (without a colon and
537 space) in the minibuffer. The optional argument DEFAULT-VALUE
538 provides the value to display in the minibuffer prompt that is
539 returned if the user just types RET.
540 Values available via M-n are the string at point, the last isearch
541 regexp, the last isearch string, and the last replacement regexp."
542 (let* ((defaults
543 (list (regexp-quote
544 (or (funcall (or find-tag-default-function
545 (get major-mode 'find-tag-default-function)
546 'find-tag-default))
547 ""))
548 (car regexp-search-ring)
549 (regexp-quote (or (car search-ring) ""))
550 (car (symbol-value
551 query-replace-from-history-variable))))
552 (defaults (delete-dups (delq nil (delete "" defaults))))
553 ;; Don't add automatically the car of defaults for empty input
554 (history-add-new-input nil)
555 (input
556 (read-from-minibuffer
557 (if default-value
558 (format "%s (default %s): " prompt
559 (query-replace-descr default-value))
560 (format "%s: " prompt))
561 nil nil nil 'regexp-history defaults t)))
562 (if (equal input "")
563 (or default-value input)
564 (prog1 input
565 (add-to-history 'regexp-history input)))))
566
567
568 (defalias 'delete-non-matching-lines 'keep-lines)
569 (defalias 'delete-matching-lines 'flush-lines)
570 (defalias 'count-matches 'how-many)
571
572
573 (defun keep-lines-read-args (prompt)
574 "Read arguments for `keep-lines' and friends.
575 Prompt for a regexp with PROMPT.
576 Value is a list, (REGEXP)."
577 (list (read-regexp prompt) nil nil t))
578
579 (defun keep-lines (regexp &optional rstart rend interactive)
580 "Delete all lines except those containing matches for REGEXP.
581 A match split across lines preserves all the lines it lies in.
582 When called from Lisp (and usually interactively as well, see below)
583 applies to all lines starting after point.
584
585 If REGEXP contains upper case characters (excluding those preceded by `\\')
586 and `search-upper-case' is non-nil, the matching is case-sensitive.
587
588 Second and third arg RSTART and REND specify the region to operate on.
589 This command operates on (the accessible part of) all lines whose
590 accessible part is entirely contained in the region determined by RSTART
591 and REND. (A newline ending a line counts as part of that line.)
592
593 Interactively, in Transient Mark mode when the mark is active, operate
594 on all lines whose accessible part is entirely contained in the region.
595 Otherwise, the command applies to all lines starting after point.
596 When calling this function from Lisp, you can pretend that it was
597 called interactively by passing a non-nil INTERACTIVE argument.
598
599 This function starts looking for the next match from the end of
600 the previous match. Hence, it ignores matches that overlap
601 a previously found match."
602
603 (interactive
604 (progn
605 (barf-if-buffer-read-only)
606 (keep-lines-read-args "Keep lines containing match for regexp")))
607 (if rstart
608 (progn
609 (goto-char (min rstart rend))
610 (setq rend
611 (progn
612 (save-excursion
613 (goto-char (max rstart rend))
614 (unless (or (bolp) (eobp))
615 (forward-line 0))
616 (point-marker)))))
617 (if (and interactive transient-mark-mode mark-active)
618 (setq rstart (region-beginning)
619 rend (progn
620 (goto-char (region-end))
621 (unless (or (bolp) (eobp))
622 (forward-line 0))
623 (point-marker)))
624 (setq rstart (point)
625 rend (point-max-marker)))
626 (goto-char rstart))
627 (save-excursion
628 (or (bolp) (forward-line 1))
629 (let ((start (point))
630 (case-fold-search
631 (if (and case-fold-search search-upper-case)
632 (isearch-no-upper-case-p regexp t)
633 case-fold-search)))
634 (while (< (point) rend)
635 ;; Start is first char not preserved by previous match.
636 (if (not (re-search-forward regexp rend 'move))
637 (delete-region start rend)
638 (let ((end (save-excursion (goto-char (match-beginning 0))
639 (forward-line 0)
640 (point))))
641 ;; Now end is first char preserved by the new match.
642 (if (< start end)
643 (delete-region start end))))
644
645 (setq start (save-excursion (forward-line 1) (point)))
646 ;; If the match was empty, avoid matching again at same place.
647 (and (< (point) rend)
648 (= (match-beginning 0) (match-end 0))
649 (forward-char 1)))))
650 (set-marker rend nil)
651 nil)
652
653
654 (defun flush-lines (regexp &optional rstart rend interactive)
655 "Delete lines containing matches for REGEXP.
656 When called from Lisp (and usually when called interactively as
657 well, see below), applies to the part of the buffer after point.
658 The line point is in is deleted if and only if it contains a
659 match for regexp starting after point.
660
661 If REGEXP contains upper case characters (excluding those preceded by `\\')
662 and `search-upper-case' is non-nil, the matching is case-sensitive.
663
664 Second and third arg RSTART and REND specify the region to operate on.
665 Lines partially contained in this region are deleted if and only if
666 they contain a match entirely contained in it.
667
668 Interactively, in Transient Mark mode when the mark is active, operate
669 on the contents of the region. Otherwise, operate from point to the
670 end of (the accessible portion of) the buffer. When calling this function
671 from Lisp, you can pretend that it was called interactively by passing
672 a non-nil INTERACTIVE argument.
673
674 If a match is split across lines, all the lines it lies in are deleted.
675 They are deleted _before_ looking for the next match. Hence, a match
676 starting on the same line at which another match ended is ignored."
677
678 (interactive
679 (progn
680 (barf-if-buffer-read-only)
681 (keep-lines-read-args "Flush lines containing match for regexp")))
682 (if rstart
683 (progn
684 (goto-char (min rstart rend))
685 (setq rend (copy-marker (max rstart rend))))
686 (if (and interactive transient-mark-mode mark-active)
687 (setq rstart (region-beginning)
688 rend (copy-marker (region-end)))
689 (setq rstart (point)
690 rend (point-max-marker)))
691 (goto-char rstart))
692 (let ((case-fold-search
693 (if (and case-fold-search search-upper-case)
694 (isearch-no-upper-case-p regexp t)
695 case-fold-search)))
696 (save-excursion
697 (while (and (< (point) rend)
698 (re-search-forward regexp rend t))
699 (delete-region (save-excursion (goto-char (match-beginning 0))
700 (forward-line 0)
701 (point))
702 (progn (forward-line 1) (point))))))
703 (set-marker rend nil)
704 nil)
705
706
707 (defun how-many (regexp &optional rstart rend interactive)
708 "Print and return number of matches for REGEXP following point.
709 When called from Lisp and INTERACTIVE is omitted or nil, just return
710 the number, do not print it; if INTERACTIVE is t, the function behaves
711 in all respects as if it had been called interactively.
712
713 If REGEXP contains upper case characters (excluding those preceded by `\\')
714 and `search-upper-case' is non-nil, the matching is case-sensitive.
715
716 Second and third arg RSTART and REND specify the region to operate on.
717
718 Interactively, in Transient Mark mode when the mark is active, operate
719 on the contents of the region. Otherwise, operate from point to the
720 end of (the accessible portion of) the buffer.
721
722 This function starts looking for the next match from the end of
723 the previous match. Hence, it ignores matches that overlap
724 a previously found match."
725
726 (interactive
727 (keep-lines-read-args "How many matches for regexp"))
728 (save-excursion
729 (if rstart
730 (progn
731 (goto-char (min rstart rend))
732 (setq rend (max rstart rend)))
733 (if (and interactive transient-mark-mode mark-active)
734 (setq rstart (region-beginning)
735 rend (region-end))
736 (setq rstart (point)
737 rend (point-max)))
738 (goto-char rstart))
739 (let ((count 0)
740 opoint
741 (case-fold-search
742 (if (and case-fold-search search-upper-case)
743 (isearch-no-upper-case-p regexp t)
744 case-fold-search)))
745 (while (and (< (point) rend)
746 (progn (setq opoint (point))
747 (re-search-forward regexp rend t)))
748 (if (= opoint (point))
749 (forward-char 1)
750 (setq count (1+ count))))
751 (when interactive (message "%d occurrence%s"
752 count
753 (if (= count 1) "" "s")))
754 count)))
755
756 \f
757 (defvar occur-mode-map
758 (let ((map (make-sparse-keymap)))
759 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
760 (define-key map [mouse-2] 'occur-mode-mouse-goto)
761 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
762 (define-key map "\C-m" 'occur-mode-goto-occurrence)
763 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
764 (define-key map "\C-o" 'occur-mode-display-occurrence)
765 (define-key map "\M-n" 'occur-next)
766 (define-key map "\M-p" 'occur-prev)
767 (define-key map "r" 'occur-rename-buffer)
768 (define-key map "c" 'clone-buffer)
769 (define-key map "g" 'revert-buffer)
770 (define-key map "q" 'quit-window)
771 (define-key map "z" 'kill-this-buffer)
772 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
773 (define-key map [menu-bar] (make-sparse-keymap))
774 (define-key map [menu-bar occur]
775 `(cons ,(purecopy "Occur") map))
776 (define-key map [next-error-follow-minor-mode]
777 (menu-bar-make-mm-toggle next-error-follow-minor-mode
778 "Auto Occurrence Display"
779 "Display another occurrence when moving the cursor"))
780 (define-key map [separator-1] menu-bar-separator)
781 (define-key map [kill-this-buffer]
782 `(menu-item ,(purecopy "Kill occur buffer") kill-this-buffer
783 :help ,(purecopy "Kill the current *Occur* buffer")))
784 (define-key map [quit-window]
785 `(menu-item ,(purecopy "Quit occur window") quit-window
786 :help ,(purecopy "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame")))
787 (define-key map [revert-buffer]
788 `(menu-item ,(purecopy "Revert occur buffer") revert-buffer
789 :help ,(purecopy "Replace the text in the *Occur* buffer with the results of rerunning occur")))
790 (define-key map [clone-buffer]
791 `(menu-item ,(purecopy "Clone occur buffer") clone-buffer
792 :help ,(purecopy "Create and return a twin copy of the current *Occur* buffer")))
793 (define-key map [occur-rename-buffer]
794 `(menu-item ,(purecopy "Rename occur buffer") occur-rename-buffer
795 :help ,(purecopy "Rename the current *Occur* buffer to *Occur: original-buffer-name*.")))
796 (define-key map [separator-2] menu-bar-separator)
797 (define-key map [occur-mode-goto-occurrence-other-window]
798 `(menu-item ,(purecopy "Go To Occurrence Other Window") occur-mode-goto-occurrence-other-window
799 :help ,(purecopy "Go to the occurrence the current line describes, in another window")))
800 (define-key map [occur-mode-goto-occurrence]
801 `(menu-item ,(purecopy "Go To Occurrence") occur-mode-goto-occurrence
802 :help ,(purecopy "Go to the occurrence the current line describes")))
803 (define-key map [occur-mode-display-occurrence]
804 `(menu-item ,(purecopy "Display Occurrence") occur-mode-display-occurrence
805 :help ,(purecopy "Display in another window the occurrence the current line describes")))
806 (define-key map [occur-next]
807 `(menu-item ,(purecopy "Move to next match") occur-next
808 :help ,(purecopy "Move to the Nth (default 1) next match in an Occur mode buffer")))
809 (define-key map [occur-prev]
810 `(menu-item ,(purecopy "Move to previous match") occur-prev
811 :help ,(purecopy "Move to the Nth (default 1) previous match in an Occur mode buffer")))
812 map)
813 "Keymap for `occur-mode'.")
814
815 (defvar occur-revert-arguments nil
816 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
817 See `occur-revert-function'.")
818
819 (defcustom occur-mode-hook '(turn-on-font-lock)
820 "Hook run when entering Occur mode."
821 :type 'hook
822 :group 'matching)
823
824 (defcustom occur-hook nil
825 "Hook run by Occur when there are any matches."
826 :type 'hook
827 :group 'matching)
828
829 (defcustom occur-mode-find-occurrence-hook nil
830 "Hook run by Occur after locating an occurrence.
831 This will be called with the cursor position at the occurrence. An application
832 for this is to reveal context in an outline-mode when the occurrence is hidden."
833 :type 'hook
834 :group 'matching)
835
836 (put 'occur-mode 'mode-class 'special)
837 (defun occur-mode ()
838 "Major mode for output from \\[occur].
839 \\<occur-mode-map>Move point to one of the items in this buffer, then use
840 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
841 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
842
843 \\{occur-mode-map}"
844 (interactive)
845 (kill-all-local-variables)
846 (use-local-map occur-mode-map)
847 (setq major-mode 'occur-mode)
848 (setq mode-name "Occur")
849 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
850 (make-local-variable 'occur-revert-arguments)
851 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
852 (setq next-error-function 'occur-next-error)
853 (run-mode-hooks 'occur-mode-hook))
854
855 (defun occur-revert-function (ignore1 ignore2)
856 "Handle `revert-buffer' for Occur mode buffers."
857 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
858
859 (defun occur-mode-find-occurrence ()
860 (let ((pos (get-text-property (point) 'occur-target)))
861 (unless pos
862 (error "No occurrence on this line"))
863 (unless (buffer-live-p (marker-buffer pos))
864 (error "Buffer for this occurrence was killed"))
865 pos))
866
867 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
868 (defun occur-mode-goto-occurrence (&optional event)
869 "Go to the occurrence the current line describes."
870 (interactive (list last-nonmenu-event))
871 (let ((pos
872 (if (null event)
873 ;; Actually `event-end' works correctly with a nil argument as
874 ;; well, so we could dispense with this test, but let's not
875 ;; rely on this undocumented behavior.
876 (occur-mode-find-occurrence)
877 (with-current-buffer (window-buffer (posn-window (event-end event)))
878 (save-excursion
879 (goto-char (posn-point (event-end event)))
880 (occur-mode-find-occurrence)))))
881 same-window-buffer-names
882 same-window-regexps)
883 (pop-to-buffer (marker-buffer pos))
884 (goto-char pos)
885 (run-hooks 'occur-mode-find-occurrence-hook)))
886
887 (defun occur-mode-goto-occurrence-other-window ()
888 "Go to the occurrence the current line describes, in another window."
889 (interactive)
890 (let ((pos (occur-mode-find-occurrence)))
891 (switch-to-buffer-other-window (marker-buffer pos))
892 (goto-char pos)
893 (run-hooks 'occur-mode-find-occurrence-hook)))
894
895 (defun occur-mode-display-occurrence ()
896 "Display in another window the occurrence the current line describes."
897 (interactive)
898 (let ((pos (occur-mode-find-occurrence))
899 window
900 ;; Bind these to ensure `display-buffer' puts it in another window.
901 same-window-buffer-names
902 same-window-regexps)
903 (setq window (display-buffer (marker-buffer pos)))
904 ;; This is the way to set point in the proper window.
905 (save-selected-window
906 (select-window window)
907 (goto-char pos)
908 (run-hooks 'occur-mode-find-occurrence-hook))))
909
910 (defun occur-find-match (n search message)
911 (if (not n) (setq n 1))
912 (let ((r))
913 (while (> n 0)
914 (setq r (funcall search (point) 'occur-match))
915 (and r
916 (get-text-property r 'occur-match)
917 (setq r (funcall search r 'occur-match)))
918 (if r
919 (goto-char r)
920 (error message))
921 (setq n (1- n)))))
922
923 (defun occur-next (&optional n)
924 "Move to the Nth (default 1) next match in an Occur mode buffer."
925 (interactive "p")
926 (occur-find-match n #'next-single-property-change "No more matches"))
927
928 (defun occur-prev (&optional n)
929 "Move to the Nth (default 1) previous match in an Occur mode buffer."
930 (interactive "p")
931 (occur-find-match n #'previous-single-property-change "No earlier matches"))
932
933 (defun occur-next-error (&optional argp reset)
934 "Move to the Nth (default 1) next match in an Occur mode buffer.
935 Compatibility function for \\[next-error] invocations."
936 (interactive "p")
937 ;; we need to run occur-find-match from within the Occur buffer
938 (with-current-buffer
939 ;; Choose the buffer and make it current.
940 (if (next-error-buffer-p (current-buffer))
941 (current-buffer)
942 (next-error-find-buffer nil nil
943 (lambda ()
944 (eq major-mode 'occur-mode))))
945
946 (goto-char (cond (reset (point-min))
947 ((< argp 0) (line-beginning-position))
948 ((> argp 0) (line-end-position))
949 ((point))))
950 (occur-find-match
951 (abs argp)
952 (if (> 0 argp)
953 #'previous-single-property-change
954 #'next-single-property-change)
955 "No more matches")
956 ;; In case the *Occur* buffer is visible in a nonselected window.
957 (let ((win (get-buffer-window (current-buffer) t)))
958 (if win (set-window-point win (point))))
959 (occur-mode-goto-occurrence)))
960 \f
961 (defface match
962 '((((class color) (min-colors 88) (background light))
963 :background "yellow1")
964 (((class color) (min-colors 88) (background dark))
965 :background "RoyalBlue3")
966 (((class color) (min-colors 8) (background light))
967 :background "yellow" :foreground "black")
968 (((class color) (min-colors 8) (background dark))
969 :background "blue" :foreground "white")
970 (((type tty) (class mono))
971 :inverse-video t)
972 (t :background "gray"))
973 "Face used to highlight matches permanently."
974 :group 'matching
975 :version "22.1")
976
977 (defcustom list-matching-lines-default-context-lines 0
978 "Default number of context lines included around `list-matching-lines' matches.
979 A negative number means to include that many lines before the match.
980 A positive number means to include that many lines both before and after."
981 :type 'integer
982 :group 'matching)
983
984 (defalias 'list-matching-lines 'occur)
985
986 (defcustom list-matching-lines-face 'match
987 "Face used by \\[list-matching-lines] to show the text that matches.
988 If the value is nil, don't highlight the matching portions specially."
989 :type 'face
990 :group 'matching)
991
992 (defcustom list-matching-lines-buffer-name-face 'underline
993 "Face used by \\[list-matching-lines] to show the names of buffers.
994 If the value is nil, don't highlight the buffer names specially."
995 :type 'face
996 :group 'matching)
997
998 (defcustom occur-excluded-properties
999 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1000 yank-handler follow-link)
1001 "Text properties to discard when copying lines to the *Occur* buffer.
1002 The value should be a list of text properties to discard or t,
1003 which means to discard all text properties."
1004 :type '(choice (const :tag "All" t) (repeat symbol))
1005 :group 'matching
1006 :version "22.1")
1007
1008 (defun occur-accumulate-lines (count &optional keep-props)
1009 (save-excursion
1010 (let ((forwardp (> count 0))
1011 result beg end)
1012 (while (not (or (zerop count)
1013 (if forwardp
1014 (eobp)
1015 (bobp))))
1016 (setq count (+ count (if forwardp -1 1)))
1017 (setq beg (line-beginning-position)
1018 end (line-end-position))
1019 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1020 (text-property-not-all beg end 'fontified t))
1021 (if (fboundp 'jit-lock-fontify-now)
1022 (jit-lock-fontify-now beg end)))
1023 (push
1024 (if (and keep-props (not (eq occur-excluded-properties t)))
1025 (let ((str (buffer-substring beg end)))
1026 (remove-list-of-text-properties
1027 0 (length str) occur-excluded-properties str)
1028 str)
1029 (buffer-substring-no-properties beg end))
1030 result)
1031 (forward-line (if forwardp 1 -1)))
1032 (nreverse result))))
1033
1034 (defun occur-read-primary-args ()
1035 (list (read-regexp "List lines matching regexp"
1036 (car regexp-history))
1037 (when current-prefix-arg
1038 (prefix-numeric-value current-prefix-arg))))
1039
1040 (defun occur-rename-buffer (&optional unique-p interactive-p)
1041 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1042 Here `original-buffer-name' is the buffer name were Occur was originally run.
1043 When given the prefix argument, or called non-interactively, the renaming
1044 will not clobber the existing buffer(s) of that name, but use
1045 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1046 if you always want a separate *Occur* buffer for each buffer where you
1047 invoke `occur'."
1048 (interactive "P\np")
1049 (with-current-buffer
1050 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1051 (rename-buffer (concat "*Occur: "
1052 (mapconcat #'buffer-name
1053 (car (cddr occur-revert-arguments)) "/")
1054 "*")
1055 (or unique-p (not interactive-p)))))
1056
1057 (defun occur (regexp &optional nlines)
1058 "Show all lines in the current buffer containing a match for REGEXP.
1059 This function can not handle matches that span more than one line.
1060
1061 Each line is displayed with NLINES lines before and after, or -NLINES
1062 before if NLINES is negative.
1063 NLINES defaults to `list-matching-lines-default-context-lines'.
1064 Interactively it is the prefix arg.
1065
1066 The lines are shown in a buffer named `*Occur*'.
1067 It serves as a menu to find any of the occurrences in this buffer.
1068 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1069
1070 If REGEXP contains upper case characters (excluding those preceded by `\\')
1071 and `search-upper-case' is non-nil, the matching is case-sensitive."
1072 (interactive (occur-read-primary-args))
1073 (occur-1 regexp nlines (list (current-buffer))))
1074
1075 (defun multi-occur (bufs regexp &optional nlines)
1076 "Show all lines in buffers BUFS containing a match for REGEXP.
1077 This function acts on multiple buffers; otherwise, it is exactly like
1078 `occur'. When you invoke this command interactively, you must specify
1079 the buffer names that you want, one by one."
1080 (interactive
1081 (cons
1082 (let* ((bufs (list (read-buffer "First buffer to search: "
1083 (current-buffer) t)))
1084 (buf nil)
1085 (ido-ignore-item-temp-list bufs))
1086 (while (not (string-equal
1087 (setq buf (read-buffer
1088 (if (eq read-buffer-function 'ido-read-buffer)
1089 "Next buffer to search (C-j to end): "
1090 "Next buffer to search (RET to end): ")
1091 nil t))
1092 ""))
1093 (add-to-list 'bufs buf)
1094 (setq ido-ignore-item-temp-list bufs))
1095 (nreverse (mapcar #'get-buffer bufs)))
1096 (occur-read-primary-args)))
1097 (occur-1 regexp nlines bufs))
1098
1099 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1100 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1101 Normally BUFREGEXP matches against each buffer's visited file name,
1102 but if you specify a prefix argument, it matches against the buffer name.
1103 See also `multi-occur'."
1104 (interactive
1105 (cons
1106 (let* ((default (car regexp-history))
1107 (input
1108 (read-from-minibuffer
1109 (if current-prefix-arg
1110 "List lines in buffers whose names match regexp: "
1111 "List lines in buffers whose filenames match regexp: ")
1112 nil
1113 nil
1114 nil
1115 'regexp-history)))
1116 (if (equal input "")
1117 default
1118 input))
1119 (occur-read-primary-args)))
1120 (when bufregexp
1121 (occur-1 regexp nil
1122 (delq nil
1123 (mapcar (lambda (buf)
1124 (when (if allbufs
1125 (string-match bufregexp
1126 (buffer-name buf))
1127 (and (buffer-file-name buf)
1128 (string-match bufregexp
1129 (buffer-file-name buf))))
1130 buf))
1131 (buffer-list))))))
1132
1133 (defun occur-1 (regexp nlines bufs &optional buf-name)
1134 (unless (and regexp (not (equal regexp "")))
1135 (error "Occur doesn't work with the empty regexp"))
1136 (unless buf-name
1137 (setq buf-name "*Occur*"))
1138 (let (occur-buf
1139 (active-bufs (delq nil (mapcar #'(lambda (buf)
1140 (when (buffer-live-p buf) buf))
1141 bufs))))
1142 ;; Handle the case where one of the buffers we're searching is the
1143 ;; output buffer. Just rename it.
1144 (when (member buf-name (mapcar 'buffer-name active-bufs))
1145 (with-current-buffer (get-buffer buf-name)
1146 (rename-uniquely)))
1147
1148 ;; Now find or create the output buffer.
1149 ;; If we just renamed that buffer, we will make a new one here.
1150 (setq occur-buf (get-buffer-create buf-name))
1151
1152 (with-current-buffer occur-buf
1153 (occur-mode)
1154 (let ((inhibit-read-only t)
1155 ;; Don't generate undo entries for creation of the initial contents.
1156 (buffer-undo-list t))
1157 (erase-buffer)
1158 (let ((count (occur-engine
1159 regexp active-bufs occur-buf
1160 (or nlines list-matching-lines-default-context-lines)
1161 (if (and case-fold-search search-upper-case)
1162 (isearch-no-upper-case-p regexp t)
1163 case-fold-search)
1164 list-matching-lines-buffer-name-face
1165 nil list-matching-lines-face
1166 (not (eq occur-excluded-properties t)))))
1167 (let* ((bufcount (length active-bufs))
1168 (diff (- (length bufs) bufcount)))
1169 (message "Searched %d buffer%s%s; %s match%s for `%s'"
1170 bufcount (if (= bufcount 1) "" "s")
1171 (if (zerop diff) "" (format " (%d killed)" diff))
1172 (if (zerop count) "no" (format "%d" count))
1173 (if (= count 1) "" "es")
1174 regexp))
1175 (setq occur-revert-arguments (list regexp nlines bufs))
1176 (if (= count 0)
1177 (kill-buffer occur-buf)
1178 (display-buffer occur-buf)
1179 (setq next-error-last-buffer occur-buf)
1180 (setq buffer-read-only t)
1181 (set-buffer-modified-p nil)
1182 (run-hooks 'occur-hook)))))))
1183
1184 (defun occur-engine-add-prefix (lines)
1185 (mapcar
1186 #'(lambda (line)
1187 (concat " :" line "\n"))
1188 lines))
1189
1190 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
1191 title-face prefix-face match-face keep-props)
1192 (with-current-buffer out-buf
1193 (let ((globalcount 0)
1194 (coding nil))
1195 ;; Map over all the buffers
1196 (dolist (buf buffers)
1197 (when (buffer-live-p buf)
1198 (let ((matches 0) ;; count of matched lines
1199 (lines 1) ;; line count
1200 (matchbeg 0)
1201 (origpt nil)
1202 (begpt nil)
1203 (endpt nil)
1204 (marker nil)
1205 (curstring "")
1206 (inhibit-field-text-motion t)
1207 (headerpt (with-current-buffer out-buf (point))))
1208 (with-current-buffer buf
1209 (or coding
1210 ;; Set CODING only if the current buffer locally
1211 ;; binds buffer-file-coding-system.
1212 (not (local-variable-p 'buffer-file-coding-system))
1213 (setq coding buffer-file-coding-system))
1214 (save-excursion
1215 (goto-char (point-min)) ;; begin searching in the buffer
1216 (while (not (eobp))
1217 (setq origpt (point))
1218 (when (setq endpt (re-search-forward regexp nil t))
1219 (setq matches (1+ matches)) ;; increment match count
1220 (setq matchbeg (match-beginning 0))
1221 (setq lines (+ lines (1- (count-lines origpt endpt))))
1222 (save-excursion
1223 (goto-char matchbeg)
1224 (setq begpt (line-beginning-position)
1225 endpt (line-end-position)))
1226 (setq marker (make-marker))
1227 (set-marker marker matchbeg)
1228 (if (and keep-props
1229 (if (boundp 'jit-lock-mode) jit-lock-mode)
1230 (text-property-not-all begpt endpt 'fontified t))
1231 (if (fboundp 'jit-lock-fontify-now)
1232 (jit-lock-fontify-now begpt endpt)))
1233 (if (and keep-props (not (eq occur-excluded-properties t)))
1234 (progn
1235 (setq curstring (buffer-substring begpt endpt))
1236 (remove-list-of-text-properties
1237 0 (length curstring) occur-excluded-properties curstring))
1238 (setq curstring (buffer-substring-no-properties begpt endpt)))
1239 ;; Highlight the matches
1240 (let ((len (length curstring))
1241 (start 0))
1242 (while (and (< start len)
1243 (string-match regexp curstring start))
1244 (add-text-properties
1245 (match-beginning 0) (match-end 0)
1246 (append
1247 `(occur-match t)
1248 (when match-face
1249 ;; Use `face' rather than `font-lock-face' here
1250 ;; so as to override faces copied from the buffer.
1251 `(face ,match-face)))
1252 curstring)
1253 (setq start (match-end 0))))
1254 ;; Generate the string to insert for this match
1255 (let* ((out-line
1256 (concat
1257 ;; Using 7 digits aligns tabs properly.
1258 (apply #'propertize (format "%7d:" lines)
1259 (append
1260 (when prefix-face
1261 `(font-lock-face prefix-face))
1262 `(occur-prefix t mouse-face (highlight)
1263 occur-target ,marker follow-link t
1264 help-echo "mouse-2: go to this occurrence")))
1265 ;; We don't put `mouse-face' on the newline,
1266 ;; because that loses. And don't put it
1267 ;; on context lines to reduce flicker.
1268 (propertize curstring 'mouse-face (list 'highlight)
1269 'occur-target marker
1270 'follow-link t
1271 'help-echo
1272 "mouse-2: go to this occurrence")
1273 ;; Add marker at eol, but no mouse props.
1274 (propertize "\n" 'occur-target marker)))
1275 (data
1276 (if (= nlines 0)
1277 ;; The simple display style
1278 out-line
1279 ;; The complex multi-line display style.
1280 (occur-context-lines out-line nlines keep-props)
1281 )))
1282 ;; Actually insert the match display data
1283 (with-current-buffer out-buf
1284 (let ((beg (point))
1285 (end (progn (insert data) (point))))
1286 (unless (= nlines 0)
1287 (insert "-------\n")))))
1288 (goto-char endpt))
1289 (if endpt
1290 (progn
1291 (setq lines (1+ lines))
1292 ;; On to the next match...
1293 (forward-line 1))
1294 (goto-char (point-max))))))
1295 (when (not (zerop matches)) ;; is the count zero?
1296 (setq globalcount (+ globalcount matches))
1297 (with-current-buffer out-buf
1298 (goto-char headerpt)
1299 (let ((beg (point))
1300 end)
1301 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1302 matches (if (= matches 1) "" "es")
1303 regexp (buffer-name buf)))
1304 (setq end (point))
1305 (add-text-properties beg end
1306 (append
1307 (when title-face
1308 `(font-lock-face ,title-face))
1309 `(occur-title ,buf))))
1310 (goto-char (point-min)))))))
1311 (if coding
1312 ;; CODING is buffer-file-coding-system of the first buffer
1313 ;; that locally binds it. Let's use it also for the output
1314 ;; buffer.
1315 (set-buffer-file-coding-system coding))
1316 ;; Return the number of matches
1317 globalcount)))
1318
1319 ;; Generate context display for occur.
1320 ;; OUT-LINE is the line where the match is.
1321 ;; NLINES and KEEP-PROPS are args to occur-engine.
1322 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1323 ;; then concatenate them all together.
1324 (defun occur-context-lines (out-line nlines keep-props)
1325 (apply #'concat
1326 (nconc
1327 (occur-engine-add-prefix
1328 (nreverse (cdr (occur-accumulate-lines
1329 (- (1+ (abs nlines))) keep-props))))
1330 (list out-line)
1331 (if (> nlines 0)
1332 (occur-engine-add-prefix
1333 (cdr (occur-accumulate-lines (1+ nlines) keep-props)))))))
1334 \f
1335 ;; It would be nice to use \\[...], but there is no reasonable way
1336 ;; to make that display both SPC and Y.
1337 (defconst query-replace-help
1338 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1339 RET or `q' to exit, Period to replace one match and exit,
1340 Comma to replace but not move point immediately,
1341 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1342 C-w to delete match and recursive edit,
1343 C-l to clear the screen, redisplay, and offer same replacement again,
1344 ! to replace all remaining matches with no more questions,
1345 ^ to move point back to previous match,
1346 E to edit the replacement string"
1347 "Help message while in `query-replace'.")
1348
1349 (defvar query-replace-map
1350 (let ((map (make-sparse-keymap)))
1351 (define-key map " " 'act)
1352 (define-key map "\d" 'skip)
1353 (define-key map [delete] 'skip)
1354 (define-key map [backspace] 'skip)
1355 (define-key map "y" 'act)
1356 (define-key map "n" 'skip)
1357 (define-key map "Y" 'act)
1358 (define-key map "N" 'skip)
1359 (define-key map "e" 'edit-replacement)
1360 (define-key map "E" 'edit-replacement)
1361 (define-key map "," 'act-and-show)
1362 (define-key map "q" 'exit)
1363 (define-key map "\r" 'exit)
1364 (define-key map [return] 'exit)
1365 (define-key map "." 'act-and-exit)
1366 (define-key map "\C-r" 'edit)
1367 (define-key map "\C-w" 'delete-and-edit)
1368 (define-key map "\C-l" 'recenter)
1369 (define-key map "!" 'automatic)
1370 (define-key map "^" 'backup)
1371 (define-key map "\C-h" 'help)
1372 (define-key map [f1] 'help)
1373 (define-key map [help] 'help)
1374 (define-key map "?" 'help)
1375 (define-key map "\C-g" 'quit)
1376 (define-key map "\C-]" 'quit)
1377 (define-key map "\e" 'exit-prefix)
1378 (define-key map [escape] 'exit-prefix)
1379 map)
1380 "Keymap that defines the responses to questions in `query-replace'.
1381 The \"bindings\" in this map are not commands; they are answers.
1382 The valid answers include `act', `skip', `act-and-show',
1383 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1384 `automatic', `backup', `exit-prefix', and `help'.")
1385
1386 (defvar multi-query-replace-map
1387 (let ((map (make-sparse-keymap)))
1388 (set-keymap-parent map query-replace-map)
1389 (define-key map "Y" 'automatic-all)
1390 (define-key map "N" 'exit-current)
1391 map)
1392 "Keymap that defines additional bindings for multi-buffer replacements.
1393 It extends its parent map `query-replace-map' with new bindings to
1394 operate on a set of buffers/files. The difference with its parent map
1395 is the additional answers `automatic-all' to replace all remaining
1396 matches in all remaining buffers with no more questions, and
1397 `exit-current' to skip remaining matches in the current buffer
1398 and to continue with the next buffer in the sequence.")
1399
1400 (defun replace-match-string-symbols (n)
1401 "Process a list (and any sub-lists), expanding certain symbols.
1402 Symbol Expands To
1403 N (match-string N) (where N is a string of digits)
1404 #N (string-to-number (match-string N))
1405 & (match-string 0)
1406 #& (string-to-number (match-string 0))
1407 # replace-count
1408
1409 Note that these symbols must be preceeded by a backslash in order to
1410 type them using Lisp syntax."
1411 (while (consp n)
1412 (cond
1413 ((consp (car n))
1414 (replace-match-string-symbols (car n))) ;Process sub-list
1415 ((symbolp (car n))
1416 (let ((name (symbol-name (car n))))
1417 (cond
1418 ((string-match "^[0-9]+$" name)
1419 (setcar n (list 'match-string (string-to-number name))))
1420 ((string-match "^#[0-9]+$" name)
1421 (setcar n (list 'string-to-number
1422 (list 'match-string
1423 (string-to-number (substring name 1))))))
1424 ((string= "&" name)
1425 (setcar n '(match-string 0)))
1426 ((string= "#&" name)
1427 (setcar n '(string-to-number (match-string 0))))
1428 ((string= "#" name)
1429 (setcar n 'replace-count))))))
1430 (setq n (cdr n))))
1431
1432 (defun replace-eval-replacement (expression replace-count)
1433 (let ((replacement (eval expression)))
1434 (if (stringp replacement)
1435 replacement
1436 (prin1-to-string replacement t))))
1437
1438 (defun replace-quote (replacement)
1439 "Quote a replacement string.
1440 This just doubles all backslashes in REPLACEMENT and
1441 returns the resulting string. If REPLACEMENT is not
1442 a string, it is first passed through `prin1-to-string'
1443 with the `noescape' argument set.
1444
1445 `match-data' is preserved across the call."
1446 (save-match-data
1447 (replace-regexp-in-string "\\\\" "\\\\"
1448 (if (stringp replacement)
1449 replacement
1450 (prin1-to-string replacement t))
1451 t t)))
1452
1453 (defun replace-loop-through-replacements (data replace-count)
1454 ;; DATA is a vector contaning the following values:
1455 ;; 0 next-rotate-count
1456 ;; 1 repeat-count
1457 ;; 2 next-replacement
1458 ;; 3 replacements
1459 (if (= (aref data 0) replace-count)
1460 (progn
1461 (aset data 0 (+ replace-count (aref data 1)))
1462 (let ((next (cdr (aref data 2))))
1463 (aset data 2 (if (consp next) next (aref data 3))))))
1464 (car (aref data 2)))
1465
1466 (defun replace-match-data (integers reuse &optional new)
1467 "Like `match-data', but markers in REUSE get invalidated.
1468 If NEW is non-nil, it is set and returned instead of fresh data,
1469 but coerced to the correct value of INTEGERS."
1470 (or (and new
1471 (progn
1472 (set-match-data new)
1473 (and (eq new reuse)
1474 (eq (null integers) (markerp (car reuse)))
1475 new)))
1476 (match-data integers reuse t)))
1477
1478 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1479 "Make a replacement with `replace-match', editing `\\?'.
1480 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1481 check for `\\?' is made to save time. MATCH-DATA is used for the
1482 replacement. In case editing is done, it is changed to use markers.
1483
1484 The return value is non-nil if there has been no `\\?' or NOEDIT was
1485 passed in. If LITERAL is set, no checking is done, anyway."
1486 (unless (or literal noedit)
1487 (setq noedit t)
1488 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1489 newtext)
1490 (setq newtext
1491 (read-string "Edit replacement string: "
1492 (prog1
1493 (cons
1494 (replace-match "" t t newtext 3)
1495 (1+ (match-beginning 3)))
1496 (setq match-data
1497 (replace-match-data
1498 nil match-data match-data))))
1499 noedit nil)))
1500 (set-match-data match-data)
1501 (replace-match newtext fixedcase literal)
1502 noedit)
1503
1504 (defvar replace-search-function 'search-forward
1505 "Function to use when searching for strings to replace.
1506 It is used by `query-replace' and `replace-string', and is called
1507 with three arguments, as if it were `search-forward'.")
1508
1509 (defvar replace-re-search-function 're-search-forward
1510 "Function to use when searching for regexps to replace.
1511 It is used by `query-replace-regexp', `replace-regexp',
1512 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1513 It is called with three arguments, as if it were
1514 `re-search-forward'.")
1515
1516 (defun perform-replace (from-string replacements
1517 query-flag regexp-flag delimited-flag
1518 &optional repeat-count map start end)
1519 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1520 Don't use this in your own program unless you want to query and set the mark
1521 just as `query-replace' does. Instead, write a simple loop like this:
1522
1523 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1524 (replace-match \"foobar\" nil nil))
1525
1526 which will run faster and probably do exactly what you want. Please
1527 see the documentation of `replace-match' to find out how to simulate
1528 `case-replace'.
1529
1530 This function returns nil if and only if there were no matches to
1531 make, or the user didn't cancel the call."
1532 (or map (setq map query-replace-map))
1533 (and query-flag minibuffer-auto-raise
1534 (raise-frame (window-frame (minibuffer-window))))
1535 (let* ((case-fold-search
1536 (if (and case-fold-search search-upper-case)
1537 (isearch-no-upper-case-p from-string regexp-flag)
1538 case-fold-search))
1539 (nocasify (not (and case-replace case-fold-search)))
1540 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1541 (search-function
1542 (if regexp-flag
1543 replace-re-search-function
1544 replace-search-function))
1545 (search-string from-string)
1546 (real-match-data nil) ; The match data for the current match.
1547 (next-replacement nil)
1548 ;; This is non-nil if we know there is nothing for the user
1549 ;; to edit in the replacement.
1550 (noedit nil)
1551 (keep-going t)
1552 (stack nil)
1553 (replace-count 0)
1554 (nonempty-match nil)
1555 (multi-buffer nil)
1556 (recenter-last-op nil) ; Start cycling order with initial position.
1557
1558 ;; If non-nil, it is marker saying where in the buffer to stop.
1559 (limit nil)
1560
1561 ;; Data for the next match. If a cons, it has the same format as
1562 ;; (match-data); otherwise it is t if a match is possible at point.
1563 (match-again t)
1564
1565 (message
1566 (if query-flag
1567 (apply 'propertize
1568 (substitute-command-keys
1569 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1570 minibuffer-prompt-properties))))
1571
1572 ;; If region is active, in Transient Mark mode, operate on region.
1573 (when start
1574 (setq limit (copy-marker (max start end)))
1575 (goto-char (min start end))
1576 (deactivate-mark))
1577
1578 ;; If last typed key in previous call of multi-buffer perform-replace
1579 ;; was `automatic-all', don't ask more questions in next files
1580 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
1581 (setq query-flag nil multi-buffer t))
1582
1583 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1584 ;; containing a function and its first argument. The function is
1585 ;; called to generate each replacement like this:
1586 ;; (funcall (car replacements) (cdr replacements) replace-count)
1587 ;; It must return a string.
1588 (cond
1589 ((stringp replacements)
1590 (setq next-replacement replacements
1591 replacements nil))
1592 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1593 (or repeat-count (setq repeat-count 1))
1594 (setq replacements (cons 'replace-loop-through-replacements
1595 (vector repeat-count repeat-count
1596 replacements replacements)))))
1597
1598 (if delimited-flag
1599 (setq search-function 're-search-forward
1600 search-string (concat "\\b"
1601 (if regexp-flag from-string
1602 (regexp-quote from-string))
1603 "\\b")))
1604 (when query-replace-lazy-highlight
1605 (setq isearch-lazy-highlight-last-string nil))
1606
1607 (push-mark)
1608 (undo-boundary)
1609 (unwind-protect
1610 ;; Loop finding occurrences that perhaps should be replaced.
1611 (while (and keep-going
1612 (not (or (eobp) (and limit (>= (point) limit))))
1613 ;; Use the next match if it is already known;
1614 ;; otherwise, search for a match after moving forward
1615 ;; one char if progress is required.
1616 (setq real-match-data
1617 (cond ((consp match-again)
1618 (goto-char (nth 1 match-again))
1619 (replace-match-data
1620 t real-match-data match-again))
1621 ;; MATCH-AGAIN non-nil means accept an
1622 ;; adjacent match.
1623 (match-again
1624 (and
1625 (funcall search-function search-string
1626 limit t)
1627 ;; For speed, use only integers and
1628 ;; reuse the list used last time.
1629 (replace-match-data t real-match-data)))
1630 ((and (< (1+ (point)) (point-max))
1631 (or (null limit)
1632 (< (1+ (point)) limit)))
1633 ;; If not accepting adjacent matches,
1634 ;; move one char to the right before
1635 ;; searching again. Undo the motion
1636 ;; if the search fails.
1637 (let ((opoint (point)))
1638 (forward-char 1)
1639 (if (funcall
1640 search-function search-string
1641 limit t)
1642 (replace-match-data
1643 t real-match-data)
1644 (goto-char opoint)
1645 nil))))))
1646
1647 ;; Record whether the match is nonempty, to avoid an infinite loop
1648 ;; repeatedly matching the same empty string.
1649 (setq nonempty-match
1650 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1651
1652 ;; If the match is empty, record that the next one can't be
1653 ;; adjacent.
1654
1655 ;; Otherwise, if matching a regular expression, do the next
1656 ;; match now, since the replacement for this match may
1657 ;; affect whether the next match is adjacent to this one.
1658 ;; If that match is empty, don't use it.
1659 (setq match-again
1660 (and nonempty-match
1661 (or (not regexp-flag)
1662 (and (looking-at search-string)
1663 (let ((match (match-data)))
1664 (and (/= (nth 0 match) (nth 1 match))
1665 match))))))
1666
1667 ;; Optionally ignore matches that have a read-only property.
1668 (unless (and query-replace-skip-read-only
1669 (text-property-not-all
1670 (nth 0 real-match-data) (nth 1 real-match-data)
1671 'read-only nil))
1672
1673 ;; Calculate the replacement string, if necessary.
1674 (when replacements
1675 (set-match-data real-match-data)
1676 (setq next-replacement
1677 (funcall (car replacements) (cdr replacements)
1678 replace-count)))
1679 (if (not query-flag)
1680 (progn
1681 (unless (or literal noedit)
1682 (replace-highlight
1683 (nth 0 real-match-data) (nth 1 real-match-data)
1684 start end search-string
1685 (or delimited-flag regexp-flag) case-fold-search))
1686 (setq noedit
1687 (replace-match-maybe-edit
1688 next-replacement nocasify literal
1689 noedit real-match-data)
1690 replace-count (1+ replace-count)))
1691 (undo-boundary)
1692 (let (done replaced key def)
1693 ;; Loop reading commands until one of them sets done,
1694 ;; which means it has finished handling this
1695 ;; occurrence. Any command that sets `done' should
1696 ;; leave behind proper match data for the stack.
1697 ;; Commands not setting `done' need to adjust
1698 ;; `real-match-data'.
1699 (while (not done)
1700 (set-match-data real-match-data)
1701 (replace-highlight
1702 (match-beginning 0) (match-end 0)
1703 start end search-string
1704 (or delimited-flag regexp-flag) case-fold-search)
1705 ;; Bind message-log-max so we don't fill up the message log
1706 ;; with a bunch of identical messages.
1707 (let ((message-log-max nil)
1708 (replacement-presentation
1709 (if query-replace-show-replacement
1710 (save-match-data
1711 (set-match-data real-match-data)
1712 (match-substitute-replacement next-replacement
1713 nocasify literal))
1714 next-replacement)))
1715 (message message
1716 (query-replace-descr from-string)
1717 (query-replace-descr replacement-presentation)))
1718 (setq key (read-event))
1719 ;; Necessary in case something happens during read-event
1720 ;; that clobbers the match data.
1721 (set-match-data real-match-data)
1722 (setq key (vector key))
1723 (setq def (lookup-key map key))
1724 ;; Restore the match data while we process the command.
1725 (cond ((eq def 'help)
1726 (with-output-to-temp-buffer "*Help*"
1727 (princ
1728 (concat "Query replacing "
1729 (if delimited-flag "word " "")
1730 (if regexp-flag "regexp " "")
1731 from-string " with "
1732 next-replacement ".\n\n"
1733 (substitute-command-keys
1734 query-replace-help)))
1735 (with-current-buffer standard-output
1736 (help-mode))))
1737 ((eq def 'exit)
1738 (setq keep-going nil)
1739 (setq done t))
1740 ((eq def 'exit-current)
1741 (setq multi-buffer t keep-going nil done t))
1742 ((eq def 'backup)
1743 (if stack
1744 (let ((elt (pop stack)))
1745 (goto-char (nth 0 elt))
1746 (setq replaced (nth 1 elt)
1747 real-match-data
1748 (replace-match-data
1749 t real-match-data
1750 (nth 2 elt))))
1751 (message "No previous match")
1752 (ding 'no-terminate)
1753 (sit-for 1)))
1754 ((eq def 'act)
1755 (or replaced
1756 (setq noedit
1757 (replace-match-maybe-edit
1758 next-replacement nocasify literal
1759 noedit real-match-data)
1760 replace-count (1+ replace-count)))
1761 (setq done t replaced t))
1762 ((eq def 'act-and-exit)
1763 (or replaced
1764 (setq noedit
1765 (replace-match-maybe-edit
1766 next-replacement nocasify literal
1767 noedit real-match-data)
1768 replace-count (1+ replace-count)))
1769 (setq keep-going nil)
1770 (setq done t replaced t))
1771 ((eq def 'act-and-show)
1772 (if (not replaced)
1773 (setq noedit
1774 (replace-match-maybe-edit
1775 next-replacement nocasify literal
1776 noedit real-match-data)
1777 replace-count (1+ replace-count)
1778 real-match-data (replace-match-data
1779 t real-match-data)
1780 replaced t)))
1781 ((or (eq def 'automatic) (eq def 'automatic-all))
1782 (or replaced
1783 (setq noedit
1784 (replace-match-maybe-edit
1785 next-replacement nocasify literal
1786 noedit real-match-data)
1787 replace-count (1+ replace-count)))
1788 (setq done t query-flag nil replaced t)
1789 (if (eq def 'automatic-all) (setq multi-buffer t)))
1790 ((eq def 'skip)
1791 (setq done t))
1792 ((eq def 'recenter)
1793 ;; `this-command' has the value `query-replace',
1794 ;; so we need to bind it to `recenter-top-bottom'
1795 ;; to allow it to detect a sequence of `C-l'.
1796 (let ((this-command 'recenter-top-bottom)
1797 (last-command 'recenter-top-bottom))
1798 (recenter-top-bottom)))
1799 ((eq def 'edit)
1800 (let ((opos (point-marker)))
1801 (setq real-match-data (replace-match-data
1802 nil real-match-data
1803 real-match-data))
1804 (goto-char (match-beginning 0))
1805 (save-excursion
1806 (save-window-excursion
1807 (recursive-edit)))
1808 (goto-char opos)
1809 (set-marker opos nil))
1810 ;; Before we make the replacement,
1811 ;; decide whether the search string
1812 ;; can match again just after this match.
1813 (if (and regexp-flag nonempty-match)
1814 (setq match-again (and (looking-at search-string)
1815 (match-data)))))
1816 ;; Edit replacement.
1817 ((eq def 'edit-replacement)
1818 (setq real-match-data (replace-match-data
1819 nil real-match-data
1820 real-match-data)
1821 next-replacement
1822 (read-string "Edit replacement string: "
1823 next-replacement)
1824 noedit nil)
1825 (if replaced
1826 (set-match-data real-match-data)
1827 (setq noedit
1828 (replace-match-maybe-edit
1829 next-replacement nocasify literal noedit
1830 real-match-data)
1831 replaced t))
1832 (setq done t))
1833
1834 ((eq def 'delete-and-edit)
1835 (replace-match "" t t)
1836 (setq real-match-data (replace-match-data
1837 nil real-match-data))
1838 (replace-dehighlight)
1839 (save-excursion (recursive-edit))
1840 (setq replaced t))
1841 ;; Note: we do not need to treat `exit-prefix'
1842 ;; specially here, since we reread
1843 ;; any unrecognized character.
1844 (t
1845 (setq this-command 'mode-exited)
1846 (setq keep-going nil)
1847 (setq unread-command-events
1848 (append (listify-key-sequence key)
1849 unread-command-events))
1850 (setq done t)))
1851 (when query-replace-lazy-highlight
1852 ;; Force lazy rehighlighting only after replacements.
1853 (if (not (memq def '(skip backup)))
1854 (setq isearch-lazy-highlight-last-string nil)))
1855 (unless (eq def 'recenter)
1856 ;; Reset recenter cycling order to initial position.
1857 (setq recenter-last-op nil)))
1858 ;; Record previous position for ^ when we move on.
1859 ;; Change markers to numbers in the match data
1860 ;; since lots of markers slow down editing.
1861 (push (list (point) replaced
1862 ;;; If the replacement has already happened, all we need is the
1863 ;;; current match start and end. We could get this with a trivial
1864 ;;; match like
1865 ;;; (save-excursion (goto-char (match-beginning 0))
1866 ;;; (search-forward (match-string 0))
1867 ;;; (match-data t))
1868 ;;; if we really wanted to avoid manually constructing match data.
1869 ;;; Adding current-buffer is necessary so that match-data calls can
1870 ;;; return markers which are appropriate for editing.
1871 (if replaced
1872 (list
1873 (match-beginning 0)
1874 (match-end 0)
1875 (current-buffer))
1876 (match-data t)))
1877 stack)))))
1878
1879 (replace-dehighlight))
1880 (or unread-command-events
1881 (message "Replaced %d occurrence%s"
1882 replace-count
1883 (if (= replace-count 1) "" "s")))
1884 (or (and keep-going stack) multi-buffer)))
1885
1886 (defvar replace-overlay nil)
1887
1888 (defun replace-highlight (match-beg match-end range-beg range-end
1889 string regexp case-fold)
1890 (if query-replace-highlight
1891 (if replace-overlay
1892 (move-overlay replace-overlay match-beg match-end (current-buffer))
1893 (setq replace-overlay (make-overlay match-beg match-end))
1894 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
1895 (overlay-put replace-overlay 'face 'query-replace)))
1896 (if query-replace-lazy-highlight
1897 (let ((isearch-string string)
1898 (isearch-regexp regexp)
1899 (search-whitespace-regexp nil)
1900 (isearch-case-fold-search case-fold))
1901 (isearch-lazy-highlight-new-loop range-beg range-end))))
1902
1903 (defun replace-dehighlight ()
1904 (when replace-overlay
1905 (delete-overlay replace-overlay))
1906 (when query-replace-lazy-highlight
1907 (lazy-highlight-cleanup lazy-highlight-cleanup)
1908 (setq isearch-lazy-highlight-last-string nil)))
1909
1910 ;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1911 ;;; replace.el ends here