1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2012
4 ;; Free Software Foundation, Inc.
9 ;; This file is part of GNU Emacs.
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.
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.
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/>.
26 ;; This package supplies the string and regular-expression replace functions
27 ;; documented in the Emacs user's manual.
31 (defcustom case-replace t
32 "Non-nil means `query-replace' should preserve case in replacements."
36 (defcustom replace-lax-whitespace nil
37 "Non-nil means `query-replace' matches a sequence of whitespace chars.
38 When you enter a space or spaces in the strings to be replaced,
39 it will match any sequence matched by the regexp `search-whitespace-regexp'."
44 (defcustom replace-regexp-lax-whitespace nil
45 "Non-nil means `query-replace-regexp' matches a sequence of whitespace chars.
46 When you enter a space or spaces in the regexps to be replaced,
47 it will match any sequence matched by the regexp `search-whitespace-regexp'."
52 (defvar query-replace-history nil
53 "Default history list for query-replace commands.
54 See `query-replace-from-history-variable' and
55 `query-replace-to-history-variable'.")
57 (defvar query-replace-defaults nil
58 "Default values of FROM-STRING and TO-STRING for `query-replace'.
59 This is a cons cell (FROM-STRING . TO-STRING), or nil if there is
62 (defvar query-replace-interactive nil
63 "Non-nil means `query-replace' uses the last search string.
64 That becomes the \"string to replace\".")
66 (defcustom query-replace-from-history-variable
'query-replace-history
67 "History list to use for the FROM argument of `query-replace' commands.
68 The value of this variable should be a symbol; that symbol
69 is used as a variable to hold a history list for the strings
70 or patterns to be replaced."
75 (defcustom query-replace-to-history-variable
'query-replace-history
76 "History list to use for the TO argument of `query-replace' commands.
77 The value of this variable should be a symbol; that symbol
78 is used as a variable to hold a history list for replacement
84 (defcustom query-replace-skip-read-only nil
85 "Non-nil means `query-replace' and friends ignore read-only matches."
90 (defcustom query-replace-show-replacement t
91 "Non-nil means to show what actual replacement text will be."
96 (defcustom query-replace-highlight t
97 "Non-nil means to highlight matches during query replacement."
101 (defcustom query-replace-lazy-highlight t
102 "Controls the lazy-highlighting during query replacements.
103 When non-nil, all text in the buffer matching the current match
104 is highlighted lazily using isearch lazy highlighting (see
105 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
107 :group
'lazy-highlight
111 (defface query-replace
112 '((t (:inherit isearch
)))
113 "Face for highlighting query replacement matches."
117 (defvar replace-count
0
118 "Number of replacements done so far.
119 See `replace-regexp' and `query-replace-regexp-eval'.")
121 (defun query-replace-descr (string)
122 (mapconcat 'isearch-text-char-description string
""))
124 (defun query-replace-read-from (prompt regexp-flag
)
125 "Query and return the `from' argument of a query-replace operation.
126 The return value can also be a pair (FROM . TO) indicating that the user
127 wants to replace FROM with TO."
128 (if query-replace-interactive
129 (car (if regexp-flag regexp-search-ring search-ring
))
130 (let* ((history-add-new-input nil
)
132 ;; The save-excursion here is in case the user marks and copies
133 ;; a region in order to specify the minibuffer input.
134 ;; That should not clobber the region for the query-replace itself.
136 (read-from-minibuffer
137 (if query-replace-defaults
138 (format "%s (default %s -> %s): " prompt
139 (query-replace-descr (car query-replace-defaults
))
140 (query-replace-descr (cdr query-replace-defaults
)))
141 (format "%s: " prompt
))
143 query-replace-from-history-variable
145 (if (and (zerop (length from
)) query-replace-defaults
)
146 (cons (car query-replace-defaults
)
147 (query-replace-compile-replacement
148 (cdr query-replace-defaults
) regexp-flag
))
149 (add-to-history query-replace-from-history-variable from nil t
)
150 ;; Warn if user types \n or \t, but don't reject the input.
152 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
153 (let ((match (match-string 3 from
)))
155 ((string= match
"\\n")
156 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
157 ((string= match
"\\t")
158 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
162 (defun query-replace-compile-replacement (to regexp-flag
)
163 "Maybe convert a regexp replacement TO to Lisp.
164 Returns a list suitable for `perform-replace' if necessary,
165 the original string if not."
167 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
))
171 (setq pos
(match-end 0))
172 (push (substring to
0 (- pos
2)) list
)
173 (setq char
(aref to
(1- pos
))
174 to
(substring to pos
))
176 (push '(number-to-string replace-count
) list
))
178 (setq pos
(read-from-string to
))
179 (push `(replace-quote ,(car pos
)) list
)
181 ;; Swallow a space after a symbol
182 ;; if there is a space.
183 (if (and (or (symbolp (car pos
))
184 ;; Swallow a space after 'foo
185 ;; but not after (quote foo).
186 (and (eq (car-safe (car pos
)) 'quote
)
187 (not (= ?\
( (aref to
0)))))
188 (eq (string-match " " to
(cdr pos
))
192 (setq to
(substring to end
)))))
193 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
)))
194 (setq to
(nreverse (delete "" (cons to list
))))
195 (replace-match-string-symbols to
)
196 (cons 'replace-eval-replacement
203 (defun query-replace-read-to (from prompt regexp-flag
)
204 "Query and return the `to' argument of a query-replace operation."
205 (query-replace-compile-replacement
207 (let* ((history-add-new-input nil
)
208 (to (read-from-minibuffer
209 (format "%s %s with: " prompt
(query-replace-descr from
))
211 query-replace-to-history-variable from t
)))
212 (add-to-history query-replace-to-history-variable to nil t
)
213 (setq query-replace-defaults
(cons from to
))
217 (defun query-replace-read-args (prompt regexp-flag
&optional noerror
)
219 (barf-if-buffer-read-only))
220 (let* ((from (query-replace-read-from prompt regexp-flag
))
221 (to (if (consp from
) (prog1 (cdr from
) (setq from
(car from
)))
222 (query-replace-read-to from prompt regexp-flag
))))
223 (list from to current-prefix-arg
)))
225 (defun query-replace (from-string to-string
&optional delimited start end
)
226 "Replace some occurrences of FROM-STRING with TO-STRING.
227 As each match is found, the user must type a character saying
228 what to do with it. For directions, type \\[help-command] at that time.
230 In Transient Mark mode, if the mark is active, operate on the contents
231 of the region. Otherwise, operate from point to the end of the buffer.
233 If `query-replace-interactive' is non-nil, the last incremental search
234 string is used as FROM-STRING--you don't have to specify it with the
237 Matching is independent of case if `case-fold-search' is non-nil and
238 FROM-STRING has no uppercase letters. Replacement transfers the case
239 pattern of the old text to the new text, if `case-replace' and
240 `case-fold-search' are non-nil and FROM-STRING has no uppercase
241 letters. \(Transferring the case pattern means that if the old text
242 matched is all caps, or capitalized, then its replacement is upcased
245 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
246 to be replaced will match a sequence of whitespace chars defined by the
247 regexp in `search-whitespace-regexp'.
249 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
250 only matches surrounded by word boundaries.
251 Fourth and fifth arg START and END specify the region to operate on.
253 To customize possible responses, change the \"bindings\" in `query-replace-map'."
256 (query-replace-read-args
257 (concat "Query replace"
258 (if current-prefix-arg
" word" "")
259 (if (and transient-mark-mode mark-active
) " in region" ""))
261 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
262 ;; These are done separately here
263 ;; so that command-history will record these expressions
264 ;; rather than the values they had this time.
265 (if (and transient-mark-mode mark-active
)
267 (if (and transient-mark-mode mark-active
)
269 (perform-replace from-string to-string t nil delimited nil nil start end
))
271 (define-key esc-map
"%" 'query-replace
)
273 (defun query-replace-regexp (regexp to-string
&optional delimited start end
)
274 "Replace some things after point matching REGEXP with TO-STRING.
275 As each match is found, the user must type a character saying
276 what to do with it. For directions, type \\[help-command] at that time.
278 In Transient Mark mode, if the mark is active, operate on the contents
279 of the region. Otherwise, operate from point to the end of the buffer.
281 If `query-replace-interactive' is non-nil, the last incremental search
282 regexp is used as REGEXP--you don't have to specify it with the
285 Matching is independent of case if `case-fold-search' is non-nil and
286 REGEXP has no uppercase letters. Replacement transfers the case
287 pattern of the old text to the new text, if `case-replace' and
288 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
289 \(Transferring the case pattern means that if the old text matched is
290 all caps, or capitalized, then its replacement is upcased or
293 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
294 to be replaced will match a sequence of whitespace chars defined by the
295 regexp in `search-whitespace-regexp'.
297 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
298 only matches surrounded by word boundaries.
299 Fourth and fifth arg START and END specify the region to operate on.
301 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
302 and `\\=\\N' (where N is a digit) stands for
303 whatever what matched the Nth `\\(...\\)' in REGEXP.
304 `\\?' lets you edit the replacement text in the minibuffer
305 at the given position for each replacement.
307 In interactive calls, the replacement text can contain `\\,'
308 followed by a Lisp expression. Each
309 replacement evaluates that expression to compute the replacement
310 string. Inside of that expression, `\\&' is a string denoting the
311 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
312 for the whole or a partial match converted to a number with
313 `string-to-number', and `\\#' itself for the number of replacements
314 done so far (starting with zero).
316 If the replacement expression is a symbol, write a space after it
317 to terminate it. One space there, if any, will be discarded.
319 When using those Lisp features interactively in the replacement
320 text, TO-STRING is actually made a list instead of a string.
321 Use \\[repeat-complex-command] after this command for details."
324 (query-replace-read-args
325 (concat "Query replace"
326 (if current-prefix-arg
" word" "")
328 (if (and transient-mark-mode mark-active
) " in region" ""))
330 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
331 ;; These are done separately here
332 ;; so that command-history will record these expressions
333 ;; rather than the values they had this time.
334 (if (and transient-mark-mode mark-active
)
336 (if (and transient-mark-mode mark-active
)
338 (perform-replace regexp to-string t t delimited nil nil start end
))
340 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
342 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
343 "Replace some things after point matching REGEXP with the result of TO-EXPR.
345 Interactive use of this function is deprecated in favor of the
346 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
347 using `search-forward-regexp' and `replace-match' is preferred.
349 As each match is found, the user must type a character saying
350 what to do with it. For directions, type \\[help-command] at that time.
352 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
353 reference `replace-count' to get the number of replacements already made.
354 If the result of TO-EXPR is not a string, it is converted to one using
355 `prin1-to-string' with the NOESCAPE argument (which see).
357 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
358 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
359 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
360 Use `\\#&' or `\\#N' if you want a number instead of a string.
361 In interactive use, `\\#' in itself stands for `replace-count'.
363 In Transient Mark mode, if the mark is active, operate on the contents
364 of the region. Otherwise, operate from point to the end of the buffer.
366 If `query-replace-interactive' is non-nil, the last incremental search
367 regexp is used as REGEXP--you don't have to specify it with the
370 Preserves case in each replacement if `case-replace' and `case-fold-search'
371 are non-nil and REGEXP has no uppercase letters.
373 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
374 to be replaced will match a sequence of whitespace chars defined by the
375 regexp in `search-whitespace-regexp'.
377 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
378 only matches that are surrounded by word boundaries.
379 Fourth and fifth arg START and END specify the region to operate on."
382 (barf-if-buffer-read-only)
384 ;; Let-bind the history var to disable the "foo -> bar" default.
385 ;; Maybe we shouldn't disable this default, but for now I'll
386 ;; leave it off. --Stef
387 (let ((query-replace-to-history-variable nil
))
388 (query-replace-read-from "Query replace regexp" t
)))
389 (to (list (read-from-minibuffer
390 (format "Query replace regexp %s with eval: "
391 (query-replace-descr from
))
392 nil nil t query-replace-to-history-variable from t
))))
393 ;; We make TO a list because replace-match-string-symbols requires one,
394 ;; and the user might enter a single token.
395 (replace-match-string-symbols to
)
396 (list from
(car to
) current-prefix-arg
397 (if (and transient-mark-mode mark-active
)
399 (if (and transient-mark-mode mark-active
)
401 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
402 t
'literal delimited nil nil start end
))
404 (make-obsolete 'query-replace-regexp-eval
405 "for interactive use, use the special `\\,' feature of
406 `query-replace-regexp' instead. Non-interactively, a loop
407 using `search-forward-regexp' and `replace-match' is preferred." "22.1")
409 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
410 "Replace some matches for REGEXP with various strings, in rotation.
411 The second argument TO-STRINGS contains the replacement strings, separated
412 by spaces. This command works like `query-replace-regexp' except that
413 each successive replacement uses the next successive replacement string,
414 wrapping around from the last such string to the first.
416 In Transient Mark mode, if the mark is active, operate on the contents
417 of the region. Otherwise, operate from point to the end of the buffer.
419 Non-interactively, TO-STRINGS may be a list of replacement strings.
421 If `query-replace-interactive' is non-nil, the last incremental search
422 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
424 A prefix argument N says to use each replacement string N times
425 before rotating to the next.
426 Fourth and fifth arg START and END specify the region to operate on."
428 (let* ((from (if query-replace-interactive
429 (car regexp-search-ring
)
430 (read-from-minibuffer "Map query replace (regexp): "
432 query-replace-from-history-variable
434 (to (read-from-minibuffer
435 (format "Query replace %s with (space-separated strings): "
436 (query-replace-descr from
))
438 query-replace-to-history-variable from t
)))
440 (and current-prefix-arg
441 (prefix-numeric-value current-prefix-arg
))
442 (if (and transient-mark-mode mark-active
)
444 (if (and transient-mark-mode mark-active
)
447 (if (listp to-strings
)
448 (setq replacements to-strings
)
449 (while (/= (length to-strings
) 0)
450 (if (string-match " " to-strings
)
453 (list (substring to-strings
0
454 (string-match " " to-strings
))))
455 to-strings
(substring to-strings
456 (1+ (string-match " " to-strings
))))
457 (setq replacements
(append replacements
(list to-strings
))
459 (perform-replace regexp replacements t t nil n nil start end
)))
461 (defun replace-string (from-string to-string
&optional delimited start end
)
462 "Replace occurrences of FROM-STRING with TO-STRING.
463 Preserve case in each match if `case-replace' and `case-fold-search'
464 are non-nil and FROM-STRING has no uppercase letters.
465 \(Preserving case means that if the string matched is all caps, or capitalized,
466 then its replacement is upcased or capitalized.)
468 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
469 to be replaced will match a sequence of whitespace chars defined by the
470 regexp in `search-whitespace-regexp'.
472 In Transient Mark mode, if the mark is active, operate on the contents
473 of the region. Otherwise, operate from point to the end of the buffer.
475 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
476 only matches surrounded by word boundaries.
477 Fourth and fifth arg START and END specify the region to operate on.
479 If `query-replace-interactive' is non-nil, the last incremental search
480 string is used as FROM-STRING--you don't have to specify it with the
483 This function is usually the wrong thing to use in a Lisp program.
484 What you probably want is a loop like this:
485 (while (search-forward FROM-STRING nil t)
486 (replace-match TO-STRING nil t))
487 which will run faster and will not set the mark or print anything.
488 \(You may need a more complex loop if FROM-STRING can match the null string
489 and TO-STRING is also null.)"
492 (query-replace-read-args
494 (if current-prefix-arg
" word" "")
496 (if (and transient-mark-mode mark-active
) " in region" ""))
498 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
499 (if (and transient-mark-mode mark-active
)
501 (if (and transient-mark-mode mark-active
)
503 (perform-replace from-string to-string nil nil delimited nil nil start end
))
505 (defun replace-regexp (regexp to-string
&optional delimited start end
)
506 "Replace things after point matching REGEXP with TO-STRING.
507 Preserve case in each match if `case-replace' and `case-fold-search'
508 are non-nil and REGEXP has no uppercase letters.
510 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
511 to be replaced will match a sequence of whitespace chars defined by the
512 regexp in `search-whitespace-regexp'.
514 In Transient Mark mode, if the mark is active, operate on the contents
515 of the region. Otherwise, operate from point to the end of the buffer.
517 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
518 only matches surrounded by word boundaries.
519 Fourth and fifth arg START and END specify the region to operate on.
521 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
522 and `\\=\\N' (where N is a digit) stands for
523 whatever what matched the Nth `\\(...\\)' in REGEXP.
524 `\\?' lets you edit the replacement text in the minibuffer
525 at the given position for each replacement.
527 In interactive calls, the replacement text may contain `\\,'
528 followed by a Lisp expression used as part of the replacement
529 text. Inside of that expression, `\\&' is a string denoting the
530 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
531 numeric values from `string-to-number', and `\\#' itself for
532 `replace-count', the number of replacements occurred so far.
534 If your Lisp expression is an identifier and the next letter in
535 the replacement string would be interpreted as part of it, you
536 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
537 for this particular case you may also enter `\\#' in the
538 replacement text directly.
540 When using those Lisp features interactively in the replacement
541 text, TO-STRING is actually made a list instead of a string.
542 Use \\[repeat-complex-command] after this command for details.
544 If `query-replace-interactive' is non-nil, the last incremental search
545 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
547 This function is usually the wrong thing to use in a Lisp program.
548 What you probably want is a loop like this:
549 (while (re-search-forward REGEXP nil t)
550 (replace-match TO-STRING nil nil))
551 which will run faster and will not set the mark or print anything."
554 (query-replace-read-args
556 (if current-prefix-arg
" word" "")
558 (if (and transient-mark-mode mark-active
) " in region" ""))
560 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
561 (if (and transient-mark-mode mark-active
)
563 (if (and transient-mark-mode mark-active
)
565 (perform-replace regexp to-string nil t delimited nil nil start end
))
568 (defvar regexp-history nil
569 "History list for some commands that read regular expressions.
571 Maximum length of the history list is determined by the value
572 of `history-length', which see.")
574 (defvar occur-collect-regexp-history
'("\\1")
575 "History of regexp for occur's collect operation")
577 (defun read-regexp (prompt &optional default-value
)
578 "Read regexp as a string using the regexp history and some useful defaults.
579 Prompt for a regular expression with PROMPT (without a colon and
580 space) in the minibuffer. The optional argument DEFAULT-VALUE
581 provides the value to display in the minibuffer prompt that is
582 returned if the user just types RET.
583 Values available via M-n are the string at point, the last isearch
584 regexp, the last isearch string, and the last replacement regexp."
587 (or (funcall (or find-tag-default-function
588 (get major-mode
'find-tag-default-function
)
591 (car regexp-search-ring
)
592 (regexp-quote (or (car search-ring
) ""))
594 query-replace-from-history-variable
))))
595 (defaults (delete-dups (delq nil
(delete "" defaults
))))
596 ;; Don't add automatically the car of defaults for empty input
597 (history-add-new-input nil
)
599 (read-from-minibuffer
601 (format "%s (default %s): " prompt
602 (query-replace-descr default-value
))
603 (format "%s: " prompt
))
604 nil nil nil
'regexp-history defaults t
)))
606 (or default-value input
)
608 (add-to-history 'regexp-history input
)))))
611 (defalias 'delete-non-matching-lines
'keep-lines
)
612 (defalias 'delete-matching-lines
'flush-lines
)
613 (defalias 'count-matches
'how-many
)
616 (defun keep-lines-read-args (prompt)
617 "Read arguments for `keep-lines' and friends.
618 Prompt for a regexp with PROMPT.
619 Value is a list, (REGEXP)."
620 (list (read-regexp prompt
) nil nil t
))
622 (defun keep-lines (regexp &optional rstart rend interactive
)
623 "Delete all lines except those containing matches for REGEXP.
624 A match split across lines preserves all the lines it lies in.
625 When called from Lisp (and usually interactively as well, see below)
626 applies to all lines starting after point.
628 If REGEXP contains upper case characters (excluding those preceded by `\\')
629 and `search-upper-case' is non-nil, the matching is case-sensitive.
631 Second and third arg RSTART and REND specify the region to operate on.
632 This command operates on (the accessible part of) all lines whose
633 accessible part is entirely contained in the region determined by RSTART
634 and REND. (A newline ending a line counts as part of that line.)
636 Interactively, in Transient Mark mode when the mark is active, operate
637 on all lines whose accessible part is entirely contained in the region.
638 Otherwise, the command applies to all lines starting after point.
639 When calling this function from Lisp, you can pretend that it was
640 called interactively by passing a non-nil INTERACTIVE argument.
642 This function starts looking for the next match from the end of
643 the previous match. Hence, it ignores matches that overlap
644 a previously found match."
648 (barf-if-buffer-read-only)
649 (keep-lines-read-args "Keep lines containing match for regexp")))
652 (goto-char (min rstart rend
))
656 (goto-char (max rstart rend
))
657 (unless (or (bolp) (eobp))
660 (if (and interactive transient-mark-mode mark-active
)
661 (setq rstart
(region-beginning)
663 (goto-char (region-end))
664 (unless (or (bolp) (eobp))
668 rend
(point-max-marker)))
671 (or (bolp) (forward-line 1))
672 (let ((start (point))
674 (if (and case-fold-search search-upper-case
)
675 (isearch-no-upper-case-p regexp t
)
677 (while (< (point) rend
)
678 ;; Start is first char not preserved by previous match.
679 (if (not (re-search-forward regexp rend
'move
))
680 (delete-region start rend
)
681 (let ((end (save-excursion (goto-char (match-beginning 0))
684 ;; Now end is first char preserved by the new match.
686 (delete-region start end
))))
688 (setq start
(save-excursion (forward-line 1) (point)))
689 ;; If the match was empty, avoid matching again at same place.
690 (and (< (point) rend
)
691 (= (match-beginning 0) (match-end 0))
693 (set-marker rend nil
)
697 (defun flush-lines (regexp &optional rstart rend interactive
)
698 "Delete lines containing matches for REGEXP.
699 When called from Lisp (and usually when called interactively as
700 well, see below), applies to the part of the buffer after point.
701 The line point is in is deleted if and only if it contains a
702 match for regexp starting after point.
704 If REGEXP contains upper case characters (excluding those preceded by `\\')
705 and `search-upper-case' is non-nil, the matching is case-sensitive.
707 Second and third arg RSTART and REND specify the region to operate on.
708 Lines partially contained in this region are deleted if and only if
709 they contain a match entirely contained in it.
711 Interactively, in Transient Mark mode when the mark is active, operate
712 on the contents of the region. Otherwise, operate from point to the
713 end of (the accessible portion of) the buffer. When calling this function
714 from Lisp, you can pretend that it was called interactively by passing
715 a non-nil INTERACTIVE argument.
717 If a match is split across lines, all the lines it lies in are deleted.
718 They are deleted _before_ looking for the next match. Hence, a match
719 starting on the same line at which another match ended is ignored."
723 (barf-if-buffer-read-only)
724 (keep-lines-read-args "Flush lines containing match for regexp")))
727 (goto-char (min rstart rend
))
728 (setq rend
(copy-marker (max rstart rend
))))
729 (if (and interactive transient-mark-mode mark-active
)
730 (setq rstart
(region-beginning)
731 rend
(copy-marker (region-end)))
733 rend
(point-max-marker)))
735 (let ((case-fold-search
736 (if (and case-fold-search search-upper-case
)
737 (isearch-no-upper-case-p regexp t
)
740 (while (and (< (point) rend
)
741 (re-search-forward regexp rend t
))
742 (delete-region (save-excursion (goto-char (match-beginning 0))
745 (progn (forward-line 1) (point))))))
746 (set-marker rend nil
)
750 (defun how-many (regexp &optional rstart rend interactive
)
751 "Print and return number of matches for REGEXP following point.
752 When called from Lisp and INTERACTIVE is omitted or nil, just return
753 the number, do not print it; if INTERACTIVE is t, the function behaves
754 in all respects as if it had been called interactively.
756 If REGEXP contains upper case characters (excluding those preceded by `\\')
757 and `search-upper-case' is non-nil, the matching is case-sensitive.
759 Second and third arg RSTART and REND specify the region to operate on.
761 Interactively, in Transient Mark mode when the mark is active, operate
762 on the contents of the region. Otherwise, operate from point to the
763 end of (the accessible portion of) the buffer.
765 This function starts looking for the next match from the end of
766 the previous match. Hence, it ignores matches that overlap
767 a previously found match."
770 (keep-lines-read-args "How many matches for regexp"))
774 (goto-char (min rstart rend
))
775 (setq rend
(max rstart rend
)))
776 (if (and interactive transient-mark-mode mark-active
)
777 (setq rstart
(region-beginning)
785 (if (and case-fold-search search-upper-case
)
786 (isearch-no-upper-case-p regexp t
)
788 (while (and (< (point) rend
)
789 (progn (setq opoint
(point))
790 (re-search-forward regexp rend t
)))
791 (if (= opoint
(point))
793 (setq count
(1+ count
))))
794 (when interactive
(message "%d occurrence%s"
796 (if (= count
1) "" "s")))
800 (defvar occur-menu-map
801 (let ((map (make-sparse-keymap)))
802 (bindings--define-key map
[next-error-follow-minor-mode
]
803 '(menu-item "Auto Occurrence Display"
804 next-error-follow-minor-mode
805 :help
"Display another occurrence when moving the cursor"
806 :button
(:toggle .
(and (boundp 'next-error-follow-minor-mode
)
807 next-error-follow-minor-mode
))))
808 (bindings--define-key map
[separator-1
] menu-bar-separator
)
809 (bindings--define-key map
[kill-this-buffer
]
810 '(menu-item "Kill Occur Buffer" kill-this-buffer
811 :help
"Kill the current *Occur* buffer"))
812 (bindings--define-key map
[quit-window
]
813 '(menu-item "Quit Occur Window" quit-window
814 :help
"Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
815 (bindings--define-key map
[revert-buffer
]
816 '(menu-item "Revert Occur Buffer" revert-buffer
817 :help
"Replace the text in the *Occur* buffer with the results of rerunning occur"))
818 (bindings--define-key map
[clone-buffer
]
819 '(menu-item "Clone Occur Buffer" clone-buffer
820 :help
"Create and return a twin copy of the current *Occur* buffer"))
821 (bindings--define-key map
[occur-rename-buffer
]
822 '(menu-item "Rename Occur Buffer" occur-rename-buffer
823 :help
"Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
824 (bindings--define-key map
[occur-edit-buffer
]
825 '(menu-item "Edit Occur Buffer" occur-edit-mode
826 :help
"Edit the *Occur* buffer and apply changes to the original buffers."))
827 (bindings--define-key map
[separator-2
] menu-bar-separator
)
828 (bindings--define-key map
[occur-mode-goto-occurrence-other-window
]
829 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
830 :help
"Go to the occurrence the current line describes, in another window"))
831 (bindings--define-key map
[occur-mode-goto-occurrence
]
832 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
833 :help
"Go to the occurrence the current line describes"))
834 (bindings--define-key map
[occur-mode-display-occurrence
]
835 '(menu-item "Display Occurrence" occur-mode-display-occurrence
836 :help
"Display in another window the occurrence the current line describes"))
837 (bindings--define-key map
[occur-next
]
838 '(menu-item "Move to Next Match" occur-next
839 :help
"Move to the Nth (default 1) next match in an Occur mode buffer"))
840 (bindings--define-key map
[occur-prev
]
841 '(menu-item "Move to Previous Match" occur-prev
842 :help
"Move to the Nth (default 1) previous match in an Occur mode buffer"))
844 "Menu keymap for `occur-mode'.")
846 (defvar occur-mode-map
847 (let ((map (make-sparse-keymap)))
848 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
849 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
850 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
851 (define-key map
"e" 'occur-edit-mode
)
852 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
853 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
854 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
855 (define-key map
"\M-n" 'occur-next
)
856 (define-key map
"\M-p" 'occur-prev
)
857 (define-key map
"r" 'occur-rename-buffer
)
858 (define-key map
"c" 'clone-buffer
)
859 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
860 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
862 "Keymap for `occur-mode'.")
864 (defvar occur-revert-arguments nil
865 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
866 See `occur-revert-function'.")
867 (make-variable-buffer-local 'occur-revert-arguments
)
868 (put 'occur-revert-arguments
'permanent-local t
)
870 (defcustom occur-mode-hook
'(turn-on-font-lock)
871 "Hook run when entering Occur mode."
875 (defcustom occur-hook nil
876 "Hook run by Occur when there are any matches."
880 (defcustom occur-mode-find-occurrence-hook nil
881 "Hook run by Occur after locating an occurrence.
882 This will be called with the cursor position at the occurrence. An application
883 for this is to reveal context in an outline-mode when the occurrence is hidden."
887 (put 'occur-mode
'mode-class
'special
)
888 (define-derived-mode occur-mode special-mode
"Occur"
889 "Major mode for output from \\[occur].
890 \\<occur-mode-map>Move point to one of the items in this buffer, then use
891 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
892 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
895 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
896 (setq next-error-function
'occur-next-error
))
901 (defvar occur-edit-mode-map
902 (let ((map (make-sparse-keymap)))
903 (set-keymap-parent map text-mode-map
)
904 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
905 (define-key map
"\C-c\C-c" 'occur-cease-edit
)
906 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
907 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
908 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
910 "Keymap for `occur-edit-mode'.")
912 (define-derived-mode occur-edit-mode occur-mode
"Occur-Edit"
913 "Major mode for editing *Occur* buffers.
914 In this mode, changes to the *Occur* buffer are also applied to
915 the originating buffer.
917 To return to ordinary Occur mode, use \\[occur-cease-edit]."
918 (setq buffer-read-only nil
)
919 (add-hook 'after-change-functions
'occur-after-change-function nil t
)
920 (message (substitute-command-keys
921 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
923 (defun occur-cease-edit ()
924 "Switch from Occur Edit mode to Occur mode."
926 (when (derived-mode-p 'occur-edit-mode
)
928 (message "Switching to Occur mode.")))
930 (defun occur-after-change-function (beg end length
)
933 (let* ((line-beg (line-beginning-position))
934 (m (get-text-property line-beg
'occur-target
))
935 (buf (marker-buffer m
))
937 (when (and (get-text-property line-beg
'occur-prefix
)
938 (not (get-text-property end
'occur-prefix
)))
940 ;; Apply occur-target property to inserted (e.g. yanked) text.
941 (put-text-property beg end
'occur-target m
)
942 ;; Did we insert a newline? Occur Edit mode can't create new
943 ;; Occur entries; just discard everything after the newline.
945 (and (search-forward "\n" end t
)
946 (delete-region (1- (point)) end
))))
947 (let* ((line (- (line-number-at-pos)
948 (line-number-at-pos (window-start))))
949 (readonly (with-current-buffer buf buffer-read-only
))
950 (win (or (get-buffer-window buf
)
952 '(nil (inhibit-same-window . t
)
953 (inhibit-switch-frame . t
)))))
954 (line-end (line-end-position))
955 (text (save-excursion
956 (goto-char (next-single-property-change
957 line-beg
'occur-prefix nil
959 (setq col
(- (point) line-beg
))
960 (buffer-substring-no-properties (point) line-end
))))
961 (with-selected-window win
965 (message "Buffer `%s' is read only." buf
)
966 (delete-region (line-beginning-position) (line-end-position))
968 (move-to-column col
)))))))
971 (defun occur-revert-function (_ignore1 _ignore2
)
972 "Handle `revert-buffer' for Occur mode buffers."
973 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
975 (defun occur-mode-find-occurrence ()
976 (let ((pos (get-text-property (point) 'occur-target
)))
978 (error "No occurrence on this line"))
979 (unless (buffer-live-p (marker-buffer pos
))
980 (error "Buffer for this occurrence was killed"))
983 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
984 (defun occur-mode-goto-occurrence (&optional event
)
985 "Go to the occurrence on the current line."
986 (interactive (list last-nonmenu-event
))
989 ;; Actually `event-end' works correctly with a nil argument as
990 ;; well, so we could dispense with this test, but let's not
991 ;; rely on this undocumented behavior.
992 (occur-mode-find-occurrence)
993 (with-current-buffer (window-buffer (posn-window (event-end event
)))
995 (goto-char (posn-point (event-end event
)))
996 (occur-mode-find-occurrence))))))
997 (pop-to-buffer (marker-buffer pos
))
999 (run-hooks 'occur-mode-find-occurrence-hook
)))
1001 (defun occur-mode-goto-occurrence-other-window ()
1002 "Go to the occurrence the current line describes, in another window."
1004 (let ((pos (occur-mode-find-occurrence)))
1005 (switch-to-buffer-other-window (marker-buffer pos
))
1007 (run-hooks 'occur-mode-find-occurrence-hook
)))
1009 (defun occur-mode-display-occurrence ()
1010 "Display in another window the occurrence the current line describes."
1012 (let ((pos (occur-mode-find-occurrence))
1014 (setq window
(display-buffer (marker-buffer pos
) t
))
1015 ;; This is the way to set point in the proper window.
1016 (save-selected-window
1017 (select-window window
)
1019 (run-hooks 'occur-mode-find-occurrence-hook
))))
1021 (defun occur-find-match (n search message
)
1022 (if (not n
) (setq n
1))
1025 (setq r
(funcall search
(point) 'occur-match
))
1027 (get-text-property r
'occur-match
)
1028 (setq r
(funcall search r
'occur-match
)))
1034 (defun occur-next (&optional n
)
1035 "Move to the Nth (default 1) next match in an Occur mode buffer."
1037 (occur-find-match n
#'next-single-property-change
"No more matches"))
1039 (defun occur-prev (&optional n
)
1040 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1042 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
1044 (defun occur-next-error (&optional argp reset
)
1045 "Move to the Nth (default 1) next match in an Occur mode buffer.
1046 Compatibility function for \\[next-error] invocations."
1048 ;; we need to run occur-find-match from within the Occur buffer
1049 (with-current-buffer
1050 ;; Choose the buffer and make it current.
1051 (if (next-error-buffer-p (current-buffer))
1053 (next-error-find-buffer nil nil
1055 (eq major-mode
'occur-mode
))))
1057 (goto-char (cond (reset (point-min))
1058 ((< argp
0) (line-beginning-position))
1059 ((> argp
0) (line-end-position))
1064 #'previous-single-property-change
1065 #'next-single-property-change
)
1067 ;; In case the *Occur* buffer is visible in a nonselected window.
1068 (let ((win (get-buffer-window (current-buffer) t
)))
1069 (if win
(set-window-point win
(point))))
1070 (occur-mode-goto-occurrence)))
1073 '((((class color
) (min-colors 88) (background light
))
1074 :background
"yellow1")
1075 (((class color
) (min-colors 88) (background dark
))
1076 :background
"RoyalBlue3")
1077 (((class color
) (min-colors 8) (background light
))
1078 :background
"yellow" :foreground
"black")
1079 (((class color
) (min-colors 8) (background dark
))
1080 :background
"blue" :foreground
"white")
1081 (((type tty
) (class mono
))
1083 (t :background
"gray"))
1084 "Face used to highlight matches permanently."
1088 (defcustom list-matching-lines-default-context-lines
0
1089 "Default number of context lines included around `list-matching-lines' matches.
1090 A negative number means to include that many lines before the match.
1091 A positive number means to include that many lines both before and after."
1095 (defalias 'list-matching-lines
'occur
)
1097 (defcustom list-matching-lines-face
'match
1098 "Face used by \\[list-matching-lines] to show the text that matches.
1099 If the value is nil, don't highlight the matching portions specially."
1103 (defcustom list-matching-lines-buffer-name-face
'underline
1104 "Face used by \\[list-matching-lines] to show the names of buffers.
1105 If the value is nil, don't highlight the buffer names specially."
1109 (defcustom occur-excluded-properties
1110 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1111 yank-handler follow-link
)
1112 "Text properties to discard when copying lines to the *Occur* buffer.
1113 The value should be a list of text properties to discard or t,
1114 which means to discard all text properties."
1115 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
1119 (defun occur-read-primary-args ()
1120 (let* ((perform-collect (consp current-prefix-arg
))
1121 (regexp (read-regexp (if perform-collect
1122 "Collect strings matching regexp"
1123 "List lines matching regexp")
1124 (car regexp-history
))))
1127 ;; Perform collect operation
1128 (if (zerop (regexp-opt-depth regexp
))
1129 ;; No subexpression so collect the entire match.
1131 ;; Get the regexp for collection pattern.
1132 (let ((default (car occur-collect-regexp-history
)))
1134 (format "Regexp to collect (default %s): " default
)
1135 nil
'occur-collect-regexp-history default
)))
1136 ;; Otherwise normal occur takes numerical prefix argument.
1137 (when current-prefix-arg
1138 (prefix-numeric-value current-prefix-arg
))))))
1140 (defun occur-rename-buffer (&optional unique-p interactive-p
)
1141 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1142 Here `original-buffer-name' is the buffer name where Occur was originally run.
1143 When given the prefix argument, or called non-interactively, the renaming
1144 will not clobber the existing buffer(s) of that name, but use
1145 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1146 if you always want a separate *Occur* buffer for each buffer where you
1148 (interactive "P\np")
1149 (with-current-buffer
1150 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
1151 (rename-buffer (concat "*Occur: "
1152 (mapconcat #'buffer-name
1153 (car (cddr occur-revert-arguments
)) "/")
1155 (or unique-p
(not interactive-p
)))))
1157 (defun occur (regexp &optional nlines
)
1158 "Show all lines in the current buffer containing a match for REGEXP.
1159 If a match spreads across multiple lines, all those lines are shown.
1161 Each line is displayed with NLINES lines before and after, or -NLINES
1162 before if NLINES is negative.
1163 NLINES defaults to `list-matching-lines-default-context-lines'.
1164 Interactively it is the prefix arg.
1166 The lines are shown in a buffer named `*Occur*'.
1167 It serves as a menu to find any of the occurrences in this buffer.
1168 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1170 If REGEXP contains upper case characters (excluding those preceded by `\\')
1171 and `search-upper-case' is non-nil, the matching is case-sensitive.
1173 When NLINES is a string or when the function is called
1174 interactively with prefix argument without a number (`C-u' alone
1175 as prefix) the matching strings are collected into the `*Occur*'
1176 buffer by using NLINES as a replacement regexp. NLINES may
1177 contain \\& and \\N which convention follows `replace-match'.
1178 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1179 \"\\1\" for NLINES collects all the function names in a lisp
1180 program. When there is no parenthesized subexpressions in REGEXP
1181 the entire match is collected. In any case the searched buffer
1183 (interactive (occur-read-primary-args))
1184 (occur-1 regexp nlines
(list (current-buffer))))
1186 (defvar ido-ignore-item-temp-list
)
1188 (defun multi-occur (bufs regexp
&optional nlines
)
1189 "Show all lines in buffers BUFS containing a match for REGEXP.
1190 This function acts on multiple buffers; otherwise, it is exactly like
1191 `occur'. When you invoke this command interactively, you must specify
1192 the buffer names that you want, one by one.
1193 See also `multi-occur-in-matching-buffers'."
1196 (let* ((bufs (list (read-buffer "First buffer to search: "
1197 (current-buffer) t
)))
1199 (ido-ignore-item-temp-list bufs
))
1200 (while (not (string-equal
1201 (setq buf
(read-buffer
1202 (if (eq read-buffer-function
'ido-read-buffer
)
1203 "Next buffer to search (C-j to end): "
1204 "Next buffer to search (RET to end): ")
1207 (add-to-list 'bufs buf
)
1208 (setq ido-ignore-item-temp-list bufs
))
1209 (nreverse (mapcar #'get-buffer bufs
)))
1210 (occur-read-primary-args)))
1211 (occur-1 regexp nlines bufs
))
1213 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1214 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1215 Normally BUFREGEXP matches against each buffer's visited file name,
1216 but if you specify a prefix argument, it matches against the buffer name.
1217 See also `multi-occur'."
1220 (let* ((default (car regexp-history
))
1222 (read-from-minibuffer
1223 (if current-prefix-arg
1224 "List lines in buffers whose names match regexp: "
1225 "List lines in buffers whose filenames match regexp: ")
1230 (if (equal input
"")
1233 (occur-read-primary-args)))
1237 (mapcar (lambda (buf)
1239 (string-match bufregexp
1241 (and (buffer-file-name buf
)
1242 (string-match bufregexp
1243 (buffer-file-name buf
))))
1247 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1248 (unless (and regexp
(not (equal regexp
"")))
1249 (error "Occur doesn't work with the empty regexp"))
1251 (setq buf-name
"*Occur*"))
1253 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1254 (when (buffer-live-p buf
) buf
))
1256 ;; Handle the case where one of the buffers we're searching is the
1257 ;; output buffer. Just rename it.
1258 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1259 (with-current-buffer (get-buffer buf-name
)
1262 ;; Now find or create the output buffer.
1263 ;; If we just renamed that buffer, we will make a new one here.
1264 (setq occur-buf
(get-buffer-create buf-name
))
1266 (with-current-buffer occur-buf
1267 (if (stringp nlines
)
1268 (fundamental-mode) ;; This is for collect operation.
1270 (let ((inhibit-read-only t
)
1271 ;; Don't generate undo entries for creation of the initial contents.
1272 (buffer-undo-list t
))
1275 (if (stringp nlines
)
1276 ;; Treat nlines as a regexp to collect.
1277 (let ((bufs active-bufs
)
1280 (with-current-buffer (car bufs
)
1282 (goto-char (point-min))
1283 (while (re-search-forward regexp nil t
)
1284 ;; Insert the replacement regexp.
1285 (let ((str (match-substitute-replacement nlines
)))
1287 (with-current-buffer occur-buf
1289 (setq count
(1+ count
))
1290 (or (zerop (current-column))
1291 (insert "\n"))))))))
1292 (setq bufs
(cdr bufs
)))
1294 ;; Perform normal occur.
1296 regexp active-bufs occur-buf
1297 (or nlines list-matching-lines-default-context-lines
)
1298 (if (and case-fold-search search-upper-case
)
1299 (isearch-no-upper-case-p regexp t
)
1301 list-matching-lines-buffer-name-face
1302 nil list-matching-lines-face
1303 (not (eq occur-excluded-properties t
))))))
1304 (let* ((bufcount (length active-bufs
))
1305 (diff (- (length bufs
) bufcount
)))
1306 (message "Searched %d buffer%s%s; %s match%s%s"
1307 bufcount
(if (= bufcount
1) "" "s")
1308 (if (zerop diff
) "" (format " (%d killed)" diff
))
1309 (if (zerop count
) "no" (format "%d" count
))
1310 (if (= count
1) "" "es")
1311 ;; Don't display regexp if with remaining text
1312 ;; it is longer than window-width.
1313 (if (> (+ (length regexp
) 42) (window-width))
1314 "" (format " for `%s'" (query-replace-descr regexp
)))))
1315 (setq occur-revert-arguments
(list regexp nlines bufs
))
1317 (kill-buffer occur-buf
)
1318 (display-buffer occur-buf
)
1319 (setq next-error-last-buffer occur-buf
)
1320 (setq buffer-read-only t
)
1321 (set-buffer-modified-p nil
)
1322 (run-hooks 'occur-hook
)))))))
1324 (defun occur-engine (regexp buffers out-buf nlines case-fold
1325 title-face prefix-face match-face keep-props
)
1326 (with-current-buffer out-buf
1327 (let ((globalcount 0)
1329 (case-fold-search case-fold
))
1330 ;; Map over all the buffers
1331 (dolist (buf buffers
)
1332 (when (buffer-live-p buf
)
1333 (let ((matches 0) ;; count of matched lines
1334 (lines 1) ;; line count
1335 (prev-after-lines nil
) ;; context lines of prev match
1336 (prev-lines nil
) ;; line number of prev match endpt
1344 (inhibit-field-text-motion t
)
1345 (headerpt (with-current-buffer out-buf
(point))))
1346 (with-current-buffer buf
1348 ;; Set CODING only if the current buffer locally
1349 ;; binds buffer-file-coding-system.
1350 (not (local-variable-p 'buffer-file-coding-system
))
1351 (setq coding buffer-file-coding-system
))
1353 (goto-char (point-min)) ;; begin searching in the buffer
1355 (setq origpt
(point))
1356 (when (setq endpt
(re-search-forward regexp nil t
))
1357 (setq matches
(1+ matches
)) ;; increment match count
1358 (setq matchbeg
(match-beginning 0))
1359 ;; Get beginning of first match line and end of the last.
1361 (goto-char matchbeg
)
1362 (setq begpt
(line-beginning-position))
1364 (setq endpt
(line-end-position)))
1365 ;; Sum line numbers up to the first match line.
1366 (setq lines
(+ lines
(count-lines origpt begpt
)))
1367 (setq marker
(make-marker))
1368 (set-marker marker matchbeg
)
1369 (setq curstring
(occur-engine-line begpt endpt keep-props
))
1370 ;; Highlight the matches
1371 (let ((len (length curstring
))
1373 (while (and (< start len
)
1374 (string-match regexp curstring start
))
1375 (add-text-properties
1376 (match-beginning 0) (match-end 0)
1380 ;; Use `face' rather than `font-lock-face' here
1381 ;; so as to override faces copied from the buffer.
1382 `(face ,match-face
)))
1384 (setq start
(match-end 0))))
1385 ;; Generate the string to insert for this match
1386 (let* ((match-prefix
1387 ;; Using 7 digits aligns tabs properly.
1388 (apply #'propertize
(format "%7d:" lines
)
1391 `(font-lock-face prefix-face
))
1392 `(occur-prefix t mouse-face
(highlight)
1393 ;; Allow insertion of text at
1394 ;; the end of the prefix (for
1395 ;; Occur Edit mode).
1396 front-sticky t rear-nonsticky t
1397 occur-target
,marker follow-link t
1398 help-echo
"mouse-2: go to this occurrence"))))
1400 ;; We don't put `mouse-face' on the newline,
1401 ;; because that loses. And don't put it
1402 ;; on context lines to reduce flicker.
1403 (propertize curstring
'mouse-face
(list 'highlight
)
1404 'occur-target marker
1407 "mouse-2: go to this occurrence"))
1411 ;; Add non-numeric prefix to all non-first lines
1412 ;; of multi-line matches.
1413 (replace-regexp-in-string
1417 ;; Add marker at eol, but no mouse props.
1418 (propertize "\n" 'occur-target marker
)))
1421 ;; The simple display style
1423 ;; The complex multi-line display style.
1424 (setq ret
(occur-context-lines
1425 out-line nlines keep-props begpt endpt
1426 lines prev-lines prev-after-lines
))
1427 ;; Set first elem of the returned list to `data',
1428 ;; and the second elem to `prev-after-lines'.
1429 (setq prev-after-lines
(nth 1 ret
))
1431 ;; Actually insert the match display data
1432 (with-current-buffer out-buf
1437 ;; Sum line numbers between first and last match lines.
1438 (setq lines
(+ lines
(count-lines begpt endpt
)
1439 ;; Add 1 for empty last match line since
1440 ;; count-lines returns 1 line less.
1441 (if (and (bolp) (eolp)) 1 0)))
1442 ;; On to the next match...
1444 (goto-char (point-max)))
1445 (setq prev-lines
(1- lines
)))
1446 ;; Flush remaining context after-lines.
1447 (when prev-after-lines
1448 (with-current-buffer out-buf
1449 (insert (apply #'concat
(occur-engine-add-prefix
1450 prev-after-lines
)))))))
1451 (when (not (zerop matches
)) ;; is the count zero?
1452 (setq globalcount
(+ globalcount matches
))
1453 (with-current-buffer out-buf
1454 (goto-char headerpt
)
1458 (format "%d match%s%s in buffer: %s\n"
1459 matches
(if (= matches
1) "" "es")
1460 ;; Don't display regexp for multi-buffer.
1461 (if (> (length buffers
) 1)
1462 "" (format " for \"%s\""
1463 (query-replace-descr regexp
)))
1467 (add-text-properties beg end
1470 `(font-lock-face ,title-face
))
1471 `(occur-title ,buf
))))
1472 (goto-char (point-min)))))))
1473 ;; Display total match count and regexp for multi-buffer.
1474 (when (and (not (zerop globalcount
)) (> (length buffers
) 1))
1475 (goto-char (point-min))
1478 (insert (format "%d match%s total for \"%s\":\n"
1479 globalcount
(if (= globalcount
1) "" "es")
1480 (query-replace-descr regexp
)))
1482 (add-text-properties beg end
(when title-face
1483 `(font-lock-face ,title-face
))))
1484 (goto-char (point-min)))
1486 ;; CODING is buffer-file-coding-system of the first buffer
1487 ;; that locally binds it. Let's use it also for the output
1489 (set-buffer-file-coding-system coding
))
1490 ;; Return the number of matches
1493 (defun occur-engine-line (beg end
&optional keep-props
)
1494 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
1495 (text-property-not-all beg end
'fontified t
))
1496 (if (fboundp 'jit-lock-fontify-now
)
1497 (jit-lock-fontify-now beg end
)))
1498 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1499 (let ((str (buffer-substring beg end
)))
1500 (remove-list-of-text-properties
1501 0 (length str
) occur-excluded-properties str
)
1503 (buffer-substring-no-properties beg end
)))
1505 (defun occur-engine-add-prefix (lines)
1508 (concat " :" line
"\n"))
1511 (defun occur-accumulate-lines (count &optional keep-props pt
)
1515 (let ((forwardp (> count
0))
1516 result beg end moved
)
1517 (while (not (or (zerop count
)
1520 (and (bobp) (not moved
)))))
1521 (setq count
(+ count
(if forwardp -
1 1)))
1522 (setq beg
(line-beginning-position)
1523 end
(line-end-position))
1524 (push (occur-engine-line beg end keep-props
) result
)
1525 (setq moved
(= 0 (forward-line (if forwardp
1 -
1)))))
1526 (nreverse result
))))
1528 ;; Generate context display for occur.
1529 ;; OUT-LINE is the line where the match is.
1530 ;; NLINES and KEEP-PROPS are args to occur-engine.
1531 ;; LINES is line count of the current match,
1532 ;; PREV-LINES is line count of the previous match,
1533 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1534 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1535 ;; then concatenate them all together.
1536 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1537 lines prev-lines prev-after-lines
)
1538 ;; Find after- and before-context lines of the current match.
1540 (nreverse (cdr (occur-accumulate-lines
1541 (- (1+ (abs nlines
))) keep-props begpt
))))
1543 (cdr (occur-accumulate-lines
1544 (1+ nlines
) keep-props endpt
)))
1547 ;; Combine after-lines of the previous match
1548 ;; with before-lines of the current match.
1550 (when prev-after-lines
1551 ;; Don't overlap prev after-lines with current before-lines.
1552 (if (>= (+ prev-lines
(length prev-after-lines
))
1553 (- lines
(length before-lines
)))
1554 (setq prev-after-lines
1555 (butlast prev-after-lines
1556 (- (length prev-after-lines
)
1557 (- lines prev-lines
(length before-lines
) 1))))
1558 ;; Separate non-overlapping context lines with a dashed line.
1559 (setq separator
"-------\n")))
1562 ;; Don't overlap current before-lines with previous match line.
1563 (if (<= (- lines
(length before-lines
))
1566 (nthcdr (- (length before-lines
)
1567 (- lines prev-lines
1))
1569 ;; Separate non-overlapping before-context lines.
1570 (unless (> nlines
0)
1571 (setq separator
"-------\n"))))
1574 ;; Return a list where the first element is the output line.
1577 (and prev-after-lines
1578 (occur-engine-add-prefix prev-after-lines
))
1579 (and separator
(list separator
))
1580 (occur-engine-add-prefix before-lines
)
1582 ;; And the second element is the list of context after-lines.
1583 (if (> nlines
0) after-lines
))))
1586 ;; It would be nice to use \\[...], but there is no reasonable way
1587 ;; to make that display both SPC and Y.
1588 (defconst query-replace-help
1589 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1590 RET or `q' to exit, Period to replace one match and exit,
1591 Comma to replace but not move point immediately,
1592 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1593 C-w to delete match and recursive edit,
1594 C-l to clear the screen, redisplay, and offer same replacement again,
1595 ! to replace all remaining matches with no more questions,
1596 ^ to move point back to previous match,
1597 E to edit the replacement string"
1598 "Help message while in `query-replace'.")
1600 (defvar query-replace-map
1601 (let ((map (make-sparse-keymap)))
1602 (define-key map
" " 'act
)
1603 (define-key map
"\d" 'skip
)
1604 (define-key map
[delete] 'skip)
1605 (define-key map [backspace] 'skip)
1606 (define-key map "y" 'act)
1607 (define-key map "n" 'skip)
1608 (define-key map "Y" 'act)
1609 (define-key map "N" 'skip)
1610 (define-key map "e" 'edit-replacement)
1611 (define-key map "E" 'edit-replacement)
1612 (define-key map "," 'act-and-show)
1613 (define-key map "q" 'exit)
1614 (define-key map "\r" 'exit)
1615 (define-key map [return] 'exit)
1616 (define-key map "." 'act-and-exit)
1617 (define-key map "\C-r" 'edit)
1618 (define-key map "\C-w" 'delete-and-edit)
1619 (define-key map "\C-l" 'recenter)
1620 (define-key map "!" 'automatic)
1621 (define-key map "^" 'backup)
1622 (define-key map "\C-h" 'help)
1623 (define-key map [f1] 'help)
1624 (define-key map [help] 'help)
1625 (define-key map "?" 'help)
1626 (define-key map "\C-g" 'quit)
1627 (define-key map "\C-]" 'quit)
1628 (define-key map "\C-v" 'scroll-up)
1629 (define-key map "\M-v" 'scroll-down)
1630 (define-key map [next] 'scroll-up)
1631 (define-key map [prior] 'scroll-down)
1632 (define-key map [?\C-\M-v] 'scroll-other-window)
1633 (define-key map [M-next] 'scroll-other-window)
1634 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1635 (define-key map [M-prior] 'scroll-other-window-down)
1636 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1637 ;; should check for ESC specially.
1638 ;; (define-key map "\e" 'exit-prefix)
1639 (define-key map [escape] 'exit-prefix)
1641 "Keymap of responses to questions posed by commands like `query-replace'.
1642 The \"bindings\" in this map are not commands; they are answers.
1643 The valid answers include `act', `skip', `act-and-show',
1644 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1645 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1646 `edit', `edit-replacement', `delete-and-edit', `automatic',
1647 `backup', `quit', and `help'.
1649 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1651 (defvar multi-query-replace-map
1652 (let ((map (make-sparse-keymap)))
1653 (set-keymap-parent map query-replace-map)
1654 (define-key map "Y" 'automatic-all)
1655 (define-key map "N" 'exit-current)
1657 "Keymap that defines additional bindings for multi-buffer replacements.
1658 It extends its parent map `query-replace-map' with new bindings to
1659 operate on a set of buffers/files. The difference with its parent map
1660 is the additional answers `automatic-all' to replace all remaining
1661 matches in all remaining buffers with no more questions, and
1662 `exit-current' to skip remaining matches in the current buffer
1663 and to continue with the next buffer in the sequence.")
1665 (defun replace-match-string-symbols (n)
1666 "Process a list (and any sub-lists), expanding certain symbols.
1668 N (match-string N) (where N is a string of digits)
1669 #N (string-to-number (match-string N))
1671 #& (string-to-number (match-string 0))
1674 Note that these symbols must be preceded by a backslash in order to
1675 type them using Lisp syntax."
1679 (replace-match-string-symbols (car n))) ;Process sub-list
1681 (let ((name (symbol-name (car n))))
1683 ((string-match "^[0-9]+$" name)
1684 (setcar n (list 'match-string (string-to-number name))))
1685 ((string-match "^#[0-9]+$" name)
1686 (setcar n (list 'string-to-number
1688 (string-to-number (substring name 1))))))
1690 (setcar n '(match-string 0)))
1691 ((string= "#&" name)
1692 (setcar n '(string-to-number (match-string 0))))
1694 (setcar n 'replace-count))))))
1697 (defun replace-eval-replacement (expression count)
1698 (let* ((replace-count count)
1699 (replacement (eval expression)))
1700 (if (stringp replacement)
1702 (prin1-to-string replacement t))))
1704 (defun replace-quote (replacement)
1705 "Quote a replacement string.
1706 This just doubles all backslashes in REPLACEMENT and
1707 returns the resulting string. If REPLACEMENT is not
1708 a string, it is first passed through `prin1-to-string'
1709 with the `noescape' argument set.
1711 `match-data' is preserved across the call."
1713 (replace-regexp-in-string "\\\\" "\\\\"
1714 (if (stringp replacement)
1716 (prin1-to-string replacement t))
1719 (defun replace-loop-through-replacements (data count)
1720 ;; DATA is a vector containing the following values:
1721 ;; 0 next-rotate-count
1723 ;; 2 next-replacement
1725 (if (= (aref data 0) count)
1727 (aset data 0 (+ count (aref data 1)))
1728 (let ((next (cdr (aref data 2))))
1729 (aset data 2 (if (consp next) next (aref data 3))))))
1730 (car (aref data 2)))
1732 (defun replace-match-data (integers reuse &optional new)
1733 "Like `match-data', but markers in REUSE get invalidated.
1734 If NEW is non-nil, it is set and returned instead of fresh data,
1735 but coerced to the correct value of INTEGERS."
1738 (set-match-data new)
1740 (eq (null integers) (markerp (car reuse)))
1742 (match-data integers reuse t)))
1744 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1745 "Make a replacement with `replace-match', editing `\\?'.
1746 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1747 check for `\\?' is made to save time. MATCH-DATA is used for the
1748 replacement. In case editing is done, it is changed to use markers.
1750 The return value is non-nil if there has been no `\\?' or NOEDIT was
1751 passed in. If LITERAL is set, no checking is done, anyway."
1752 (unless (or literal noedit)
1754 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1757 (read-string "Edit replacement string: "
1760 (replace-match "" t t newtext 3)
1761 (1+ (match-beginning 3)))
1764 nil match-data match-data))))
1766 (set-match-data match-data)
1767 (replace-match newtext fixedcase literal)
1770 (defvar replace-search-function nil
1771 "Function to use when searching for strings to replace.
1772 It is used by `query-replace' and `replace-string', and is called
1773 with three arguments, as if it were `search-forward'.")
1775 (defvar replace-re-search-function nil
1776 "Function to use when searching for regexps to replace.
1777 It is used by `query-replace-regexp', `replace-regexp',
1778 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1779 It is called with three arguments, as if it were
1780 `re-search-forward'.")
1782 (defun perform-replace (from-string replacements
1783 query-flag regexp-flag delimited-flag
1784 &optional repeat-count map start end)
1785 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1786 Don't use this in your own program unless you want to query and set the mark
1787 just as `query-replace' does. Instead, write a simple loop like this:
1789 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1790 (replace-match \"foobar\" nil nil))
1792 which will run faster and probably do exactly what you want. Please
1793 see the documentation of `replace-match' to find out how to simulate
1796 This function returns nil if and only if there were no matches to
1797 make, or the user didn't cancel the call."
1798 (or map (setq map query-replace-map))
1799 (and query-flag minibuffer-auto-raise
1800 (raise-frame (window-frame (minibuffer-window))))
1801 (let* ((case-fold-search
1802 (if (and case-fold-search search-upper-case)
1803 (isearch-no-upper-case-p from-string regexp-flag)
1805 (nocasify (not (and case-replace case-fold-search)))
1806 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1809 replace-re-search-function
1810 replace-search-function)
1811 (let ((isearch-regexp regexp-flag)
1812 (isearch-word delimited-flag)
1813 (isearch-lax-whitespace
1814 replace-lax-whitespace)
1815 (isearch-regexp-lax-whitespace
1816 replace-regexp-lax-whitespace)
1817 (isearch-case-fold-search case-fold-search)
1818 (isearch-forward t))
1819 (isearch-search-fun))))
1820 (search-string from-string)
1821 (real-match-data nil) ; The match data for the current match.
1822 (next-replacement nil)
1823 ;; This is non-nil if we know there is nothing for the user
1824 ;; to edit in the replacement.
1829 (nonempty-match nil)
1831 (recenter-last-op nil) ; Start cycling order with initial position.
1833 ;; If non-nil, it is marker saying where in the buffer to stop.
1836 ;; Data for the next match. If a cons, it has the same format as
1837 ;; (match-data); otherwise it is t if a match is possible at point.
1843 (substitute-command-keys
1844 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1845 minibuffer-prompt-properties))))
1847 ;; If region is active, in Transient Mark mode, operate on region.
1849 (setq limit (copy-marker (max start end)))
1850 (goto-char (min start end))
1853 ;; If last typed key in previous call of multi-buffer perform-replace
1854 ;; was `automatic-all', don't ask more questions in next files
1855 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
1856 (setq query-flag nil multi-buffer t))
1858 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1859 ;; containing a function and its first argument. The function is
1860 ;; called to generate each replacement like this:
1861 ;; (funcall (car replacements) (cdr replacements) replace-count)
1862 ;; It must return a string.
1864 ((stringp replacements)
1865 (setq next-replacement replacements
1867 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1868 (or repeat-count (setq repeat-count 1))
1869 (setq replacements (cons 'replace-loop-through-replacements
1870 (vector repeat-count repeat-count
1871 replacements replacements)))))
1873 (when query-replace-lazy-highlight
1874 (setq isearch-lazy-highlight-last-string nil))
1879 ;; Loop finding occurrences that perhaps should be replaced.
1880 (while (and keep-going
1881 (not (or (eobp) (and limit (>= (point) limit))))
1882 ;; Use the next match if it is already known;
1883 ;; otherwise, search for a match after moving forward
1884 ;; one char if progress is required.
1885 (setq real-match-data
1886 (cond ((consp match-again)
1887 (goto-char (nth 1 match-again))
1889 t real-match-data match-again))
1890 ;; MATCH-AGAIN non-nil means accept an
1894 (funcall search-function search-string
1896 ;; For speed, use only integers and
1897 ;; reuse the list used last time.
1898 (replace-match-data t real-match-data)))
1899 ((and (< (1+ (point)) (point-max))
1901 (< (1+ (point)) limit)))
1902 ;; If not accepting adjacent matches,
1903 ;; move one char to the right before
1904 ;; searching again. Undo the motion
1905 ;; if the search fails.
1906 (let ((opoint (point)))
1909 search-function search-string
1916 ;; Record whether the match is nonempty, to avoid an infinite loop
1917 ;; repeatedly matching the same empty string.
1918 (setq nonempty-match
1919 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1921 ;; If the match is empty, record that the next one can't be
1924 ;; Otherwise, if matching a regular expression, do the next
1925 ;; match now, since the replacement for this match may
1926 ;; affect whether the next match is adjacent to this one.
1927 ;; If that match is empty, don't use it.
1930 (or (not regexp-flag)
1931 (and (looking-at search-string)
1932 (let ((match (match-data)))
1933 (and (/= (nth 0 match) (nth 1 match))
1936 ;; Optionally ignore matches that have a read-only property.
1937 (unless (and query-replace-skip-read-only
1938 (text-property-not-all
1939 (nth 0 real-match-data) (nth 1 real-match-data)
1942 ;; Calculate the replacement string, if necessary.
1944 (set-match-data real-match-data)
1945 (setq next-replacement
1946 (funcall (car replacements) (cdr replacements)
1948 (if (not query-flag)
1950 (unless (or literal noedit)
1952 (nth 0 real-match-data) (nth 1 real-match-data)
1953 start end search-string
1954 regexp-flag delimited-flag case-fold-search))
1956 (replace-match-maybe-edit
1957 next-replacement nocasify literal
1958 noedit real-match-data)
1959 replace-count (1+ replace-count)))
1961 (let (done replaced key def)
1962 ;; Loop reading commands until one of them sets done,
1963 ;; which means it has finished handling this
1964 ;; occurrence. Any command that sets `done' should
1965 ;; leave behind proper match data for the stack.
1966 ;; Commands not setting `done' need to adjust
1967 ;; `real-match-data'.
1969 (set-match-data real-match-data)
1971 (match-beginning 0) (match-end 0)
1972 start end search-string
1973 regexp-flag delimited-flag case-fold-search)
1974 ;; Bind message-log-max so we don't fill up the message log
1975 ;; with a bunch of identical messages.
1976 (let ((message-log-max nil)
1977 (replacement-presentation
1978 (if query-replace-show-replacement
1980 (set-match-data real-match-data)
1981 (match-substitute-replacement next-replacement
1985 (query-replace-descr from-string)
1986 (query-replace-descr replacement-presentation)))
1987 (setq key (read-event))
1988 ;; Necessary in case something happens during read-event
1989 ;; that clobbers the match data.
1990 (set-match-data real-match-data)
1991 (setq key (vector key))
1992 (setq def (lookup-key map key))
1993 ;; Restore the match data while we process the command.
1994 (cond ((eq def 'help)
1995 (with-output-to-temp-buffer "*Help*"
1997 (concat "Query replacing "
1998 (if delimited-flag "word " "")
1999 (if regexp-flag "regexp " "")
2000 from-string " with "
2001 next-replacement ".\n\n"
2002 (substitute-command-keys
2003 query-replace-help)))
2004 (with-current-buffer standard-output
2007 (setq keep-going nil)
2009 ((eq def 'exit-current)
2010 (setq multi-buffer t keep-going nil done t))
2013 (let ((elt (pop stack)))
2014 (goto-char (nth 0 elt))
2015 (setq replaced (nth 1 elt)
2020 (message "No previous match")
2021 (ding 'no-terminate)
2026 (replace-match-maybe-edit
2027 next-replacement nocasify literal
2028 noedit real-match-data)
2029 replace-count (1+ replace-count)))
2030 (setq done t replaced t))
2031 ((eq def 'act-and-exit)
2034 (replace-match-maybe-edit
2035 next-replacement nocasify literal
2036 noedit real-match-data)
2037 replace-count (1+ replace-count)))
2038 (setq keep-going nil)
2039 (setq done t replaced t))
2040 ((eq def 'act-and-show)
2043 (replace-match-maybe-edit
2044 next-replacement nocasify literal
2045 noedit real-match-data)
2046 replace-count (1+ replace-count)
2047 real-match-data (replace-match-data
2050 ((or (eq def 'automatic) (eq def 'automatic-all))
2053 (replace-match-maybe-edit
2054 next-replacement nocasify literal
2055 noedit real-match-data)
2056 replace-count (1+ replace-count)))
2057 (setq done t query-flag nil replaced t)
2058 (if (eq def 'automatic-all) (setq multi-buffer t)))
2062 ;; `this-command' has the value `query-replace',
2063 ;; so we need to bind it to `recenter-top-bottom'
2064 ;; to allow it to detect a sequence of `C-l'.
2065 (let ((this-command 'recenter-top-bottom)
2066 (last-command 'recenter-top-bottom))
2067 (recenter-top-bottom)))
2069 (let ((opos (point-marker)))
2070 (setq real-match-data (replace-match-data
2073 (goto-char (match-beginning 0))
2075 (save-window-excursion
2078 (set-marker opos nil))
2079 ;; Before we make the replacement,
2080 ;; decide whether the search string
2081 ;; can match again just after this match.
2082 (if (and regexp-flag nonempty-match)
2083 (setq match-again (and (looking-at search-string)
2085 ;; Edit replacement.
2086 ((eq def 'edit-replacement)
2087 (setq real-match-data (replace-match-data
2091 (read-string "Edit replacement string: "
2095 (set-match-data real-match-data)
2097 (replace-match-maybe-edit
2098 next-replacement nocasify literal noedit
2103 ((eq def 'delete-and-edit)
2104 (replace-match "" t t)
2105 (setq real-match-data (replace-match-data
2106 nil real-match-data))
2107 (replace-dehighlight)
2108 (save-excursion (recursive-edit))
2110 ;; Note: we do not need to treat `exit-prefix'
2111 ;; specially here, since we reread
2112 ;; any unrecognized character.
2114 (setq this-command 'mode-exited)
2115 (setq keep-going nil)
2116 (setq unread-command-events
2117 (append (listify-key-sequence key)
2118 unread-command-events))
2120 (when query-replace-lazy-highlight
2121 ;; Force lazy rehighlighting only after replacements.
2122 (if (not (memq def '(skip backup)))
2123 (setq isearch-lazy-highlight-last-string nil)))
2124 (unless (eq def 'recenter)
2125 ;; Reset recenter cycling order to initial position.
2126 (setq recenter-last-op nil)))
2127 ;; Record previous position for ^ when we move on.
2128 ;; Change markers to numbers in the match data
2129 ;; since lots of markers slow down editing.
2130 (push (list (point) replaced
2131 ;;; If the replacement has already happened, all we need is the
2132 ;;; current match start and end. We could get this with a trivial
2134 ;;; (save-excursion (goto-char (match-beginning 0))
2135 ;;; (search-forward (match-string 0))
2137 ;;; if we really wanted to avoid manually constructing match data.
2138 ;;; Adding current-buffer is necessary so that match-data calls can
2139 ;;; return markers which are appropriate for editing.
2148 (replace-dehighlight))
2149 (or unread-command-events
2150 (message "Replaced %d occurrence%s"
2152 (if (= replace-count 1) "" "s")))
2153 (or (and keep-going stack) multi-buffer)))
2155 (defvar replace-overlay nil)
2157 (defun replace-highlight (match-beg match-end range-beg range-end
2158 search-string regexp-flag delimited-flag
2160 (if query-replace-highlight
2162 (move-overlay replace-overlay match-beg match-end (current-buffer))
2163 (setq replace-overlay (make-overlay match-beg match-end))
2164 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2165 (overlay-put replace-overlay 'face 'query-replace)))
2166 (if query-replace-lazy-highlight
2167 (let ((isearch-string search-string)
2168 (isearch-regexp regexp-flag)
2169 (isearch-word delimited-flag)
2170 (isearch-lax-whitespace
2171 replace-lax-whitespace)
2172 (isearch-regexp-lax-whitespace
2173 replace-regexp-lax-whitespace)
2174 (isearch-case-fold-search case-fold-search)
2176 (isearch-error nil))
2177 (isearch-lazy-highlight-new-loop range-beg range-end))))
2179 (defun replace-dehighlight ()
2180 (when replace-overlay
2181 (delete-overlay replace-overlay))
2182 (when query-replace-lazy-highlight
2183 (lazy-highlight-cleanup lazy-highlight-cleanup)
2184 (setq isearch-lazy-highlight-last-string nil)))
2186 ;;; replace.el ends here