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\".")
65 (make-obsolete-variable 'query-replace-interactive
66 "use `M-n' to pull the last incremental search string
67 to the minibuffer that reads the string to replace, or invoke replacements
68 from Isearch by using a key sequence like `C-s C-s M-%'." "24.3")
70 (defcustom query-replace-from-history-variable
'query-replace-history
71 "History list to use for the FROM argument of `query-replace' commands.
72 The value of this variable should be a symbol; that symbol
73 is used as a variable to hold a history list for the strings
74 or patterns to be replaced."
79 (defcustom query-replace-to-history-variable
'query-replace-history
80 "History list to use for the TO argument of `query-replace' commands.
81 The value of this variable should be a symbol; that symbol
82 is used as a variable to hold a history list for replacement
88 (defcustom query-replace-skip-read-only nil
89 "Non-nil means `query-replace' and friends ignore read-only matches."
94 (defcustom query-replace-show-replacement t
95 "Non-nil means to show what actual replacement text will be."
100 (defcustom query-replace-highlight t
101 "Non-nil means to highlight matches during query replacement."
105 (defcustom query-replace-lazy-highlight t
106 "Controls the lazy-highlighting during query replacements.
107 When non-nil, all text in the buffer matching the current match
108 is highlighted lazily using isearch lazy highlighting (see
109 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
111 :group
'lazy-highlight
115 (defface query-replace
116 '((t (:inherit isearch
)))
117 "Face for highlighting query replacement matches."
121 (defvar replace-count
0
122 "Number of replacements done so far.
123 See `replace-regexp' and `query-replace-regexp-eval'.")
125 (defun query-replace-descr (string)
126 (mapconcat 'isearch-text-char-description string
""))
128 (defun query-replace-read-from (prompt regexp-flag
)
129 "Query and return the `from' argument of a query-replace operation.
130 The return value can also be a pair (FROM . TO) indicating that the user
131 wants to replace FROM with TO."
132 (if query-replace-interactive
133 (car (if regexp-flag regexp-search-ring search-ring
))
134 (let* ((history-add-new-input nil
)
136 (if query-replace-defaults
137 (format "%s (default %s -> %s): " prompt
138 (query-replace-descr (car query-replace-defaults
))
139 (query-replace-descr (cdr query-replace-defaults
)))
140 (format "%s: " prompt
)))
142 ;; The save-excursion here is in case the user marks and copies
143 ;; a region in order to specify the minibuffer input.
144 ;; That should not clobber the region for the query-replace itself.
147 (read-regexp prompt nil query-replace-from-history-variable
)
148 (read-from-minibuffer
149 prompt nil nil nil query-replace-from-history-variable
150 (car (if regexp-flag regexp-search-ring search-ring
)) t
)))))
151 (if (and (zerop (length from
)) query-replace-defaults
)
152 (cons (car query-replace-defaults
)
153 (query-replace-compile-replacement
154 (cdr query-replace-defaults
) regexp-flag
))
155 (add-to-history query-replace-from-history-variable from nil t
)
156 ;; Warn if user types \n or \t, but don't reject the input.
158 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
159 (let ((match (match-string 3 from
)))
161 ((string= match
"\\n")
162 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
163 ((string= match
"\\t")
164 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
168 (defun query-replace-compile-replacement (to regexp-flag
)
169 "Maybe convert a regexp replacement TO to Lisp.
170 Returns a list suitable for `perform-replace' if necessary,
171 the original string if not."
173 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
))
177 (setq pos
(match-end 0))
178 (push (substring to
0 (- pos
2)) list
)
179 (setq char
(aref to
(1- pos
))
180 to
(substring to pos
))
182 (push '(number-to-string replace-count
) list
))
184 (setq pos
(read-from-string to
))
185 (push `(replace-quote ,(car pos
)) list
)
187 ;; Swallow a space after a symbol
188 ;; if there is a space.
189 (if (and (or (symbolp (car pos
))
190 ;; Swallow a space after 'foo
191 ;; but not after (quote foo).
192 (and (eq (car-safe (car pos
)) 'quote
)
193 (not (= ?\
( (aref to
0)))))
194 (eq (string-match " " to
(cdr pos
))
198 (setq to
(substring to end
)))))
199 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
)))
200 (setq to
(nreverse (delete "" (cons to list
))))
201 (replace-match-string-symbols to
)
202 (cons 'replace-eval-replacement
209 (defun query-replace-read-to (from prompt regexp-flag
)
210 "Query and return the `to' argument of a query-replace operation."
211 (query-replace-compile-replacement
213 (let* ((history-add-new-input nil
)
214 (to (read-from-minibuffer
215 (format "%s %s with: " prompt
(query-replace-descr from
))
217 query-replace-to-history-variable from t
)))
218 (add-to-history query-replace-to-history-variable to nil t
)
219 (setq query-replace-defaults
(cons from to
))
223 (defun query-replace-read-args (prompt regexp-flag
&optional noerror
)
225 (barf-if-buffer-read-only))
226 (let* ((from (query-replace-read-from prompt regexp-flag
))
227 (to (if (consp from
) (prog1 (cdr from
) (setq from
(car from
)))
228 (query-replace-read-to from prompt regexp-flag
))))
229 (list from to current-prefix-arg
)))
231 (defun query-replace (from-string to-string
&optional delimited start end
)
232 "Replace some occurrences of FROM-STRING with TO-STRING.
233 As each match is found, the user must type a character saying
234 what to do with it. For directions, type \\[help-command] at that time.
236 In Transient Mark mode, if the mark is active, operate on the contents
237 of the region. Otherwise, operate from point to the end of the buffer.
239 Use \\<minibuffer-local-map>\\[next-history-element] \
240 to pull the last incremental search string to the minibuffer
241 that reads FROM-STRING, or invoke replacements from
242 incremental search with a key sequence like `C-s C-s M-%'
243 to use its current search string as the string to replace.
245 Matching is independent of case if `case-fold-search' is non-nil and
246 FROM-STRING has no uppercase letters. Replacement transfers the case
247 pattern of the old text to the new text, if `case-replace' and
248 `case-fold-search' are non-nil and FROM-STRING has no uppercase
249 letters. \(Transferring the case pattern means that if the old text
250 matched is all caps, or capitalized, then its replacement is upcased
253 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
254 to be replaced will match a sequence of whitespace chars defined by the
255 regexp in `search-whitespace-regexp'.
257 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
258 only matches surrounded by word boundaries.
259 Fourth and fifth arg START and END specify the region to operate on.
261 To customize possible responses, change the \"bindings\" in `query-replace-map'."
264 (query-replace-read-args
265 (concat "Query replace"
266 (if current-prefix-arg
" word" "")
267 (if (and transient-mark-mode mark-active
) " in region" ""))
269 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
270 ;; These are done separately here
271 ;; so that command-history will record these expressions
272 ;; rather than the values they had this time.
273 (if (and transient-mark-mode mark-active
)
275 (if (and transient-mark-mode mark-active
)
277 (perform-replace from-string to-string t nil delimited nil nil start end
))
279 (define-key esc-map
"%" 'query-replace
)
281 (defun query-replace-regexp (regexp to-string
&optional delimited start end
)
282 "Replace some things after point matching REGEXP with TO-STRING.
283 As each match is found, the user must type a character saying
284 what to do with it. For directions, type \\[help-command] at that time.
286 In Transient Mark mode, if the mark is active, operate on the contents
287 of the region. Otherwise, operate from point to the end of the buffer.
289 Use \\<minibuffer-local-map>\\[next-history-element] \
290 to pull the last incremental search regexp to the minibuffer
291 that reads REGEXP, or invoke replacements from
292 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
293 to use its current search regexp as the regexp to replace.
295 Matching is independent of case if `case-fold-search' is non-nil and
296 REGEXP has no uppercase letters. Replacement transfers the case
297 pattern of the old text to the new text, if `case-replace' and
298 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
299 \(Transferring the case pattern means that if the old text matched is
300 all caps, or capitalized, then its replacement is upcased or
303 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
304 to be replaced will match a sequence of whitespace chars defined by the
305 regexp in `search-whitespace-regexp'.
307 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
308 only matches surrounded by word boundaries.
309 Fourth and fifth arg START and END specify the region to operate on.
311 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
312 and `\\=\\N' (where N is a digit) stands for
313 whatever what matched the Nth `\\(...\\)' in REGEXP.
314 `\\?' lets you edit the replacement text in the minibuffer
315 at the given position for each replacement.
317 In interactive calls, the replacement text can contain `\\,'
318 followed by a Lisp expression. Each
319 replacement evaluates that expression to compute the replacement
320 string. Inside of that expression, `\\&' is a string denoting the
321 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
322 for the whole or a partial match converted to a number with
323 `string-to-number', and `\\#' itself for the number of replacements
324 done so far (starting with zero).
326 If the replacement expression is a symbol, write a space after it
327 to terminate it. One space there, if any, will be discarded.
329 When using those Lisp features interactively in the replacement
330 text, TO-STRING is actually made a list instead of a string.
331 Use \\[repeat-complex-command] after this command for details."
334 (query-replace-read-args
335 (concat "Query replace"
336 (if current-prefix-arg
" word" "")
338 (if (and transient-mark-mode mark-active
) " in region" ""))
340 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
341 ;; These are done separately here
342 ;; so that command-history will record these expressions
343 ;; rather than the values they had this time.
344 (if (and transient-mark-mode mark-active
)
346 (if (and transient-mark-mode mark-active
)
348 (perform-replace regexp to-string t t delimited nil nil start end
))
350 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
352 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
353 "Replace some things after point matching REGEXP with the result of TO-EXPR.
355 Interactive use of this function is deprecated in favor of the
356 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
357 using `search-forward-regexp' and `replace-match' is preferred.
359 As each match is found, the user must type a character saying
360 what to do with it. For directions, type \\[help-command] at that time.
362 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
363 reference `replace-count' to get the number of replacements already made.
364 If the result of TO-EXPR is not a string, it is converted to one using
365 `prin1-to-string' with the NOESCAPE argument (which see).
367 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
368 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
369 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
370 Use `\\#&' or `\\#N' if you want a number instead of a string.
371 In interactive use, `\\#' in itself stands for `replace-count'.
373 In Transient Mark mode, if the mark is active, operate on the contents
374 of the region. Otherwise, operate from point to the end of the buffer.
376 Use \\<minibuffer-local-map>\\[next-history-element] \
377 to pull the last incremental search regexp to the minibuffer
380 Preserves case in each replacement if `case-replace' and `case-fold-search'
381 are non-nil and REGEXP has no uppercase letters.
383 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
384 to be replaced will match a sequence of whitespace chars defined by the
385 regexp in `search-whitespace-regexp'.
387 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
388 only matches that are surrounded by word boundaries.
389 Fourth and fifth arg START and END specify the region to operate on."
390 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
391 for interactive calls, and `search-forward-regexp'/`replace-match'
392 for Lisp calls." "22.1"))
395 (barf-if-buffer-read-only)
397 ;; Let-bind the history var to disable the "foo -> bar"
398 ;; default. Maybe we shouldn't disable this default, but
399 ;; for now I'll leave it off. --Stef
400 (let ((query-replace-to-history-variable nil
))
401 (query-replace-read-from "Query replace regexp" t
)))
402 (to (list (read-from-minibuffer
403 (format "Query replace regexp %s with eval: "
404 (query-replace-descr from
))
405 nil nil t query-replace-to-history-variable from t
))))
406 ;; We make TO a list because replace-match-string-symbols requires one,
407 ;; and the user might enter a single token.
408 (replace-match-string-symbols to
)
409 (list from
(car to
) current-prefix-arg
410 (if (and transient-mark-mode mark-active
)
412 (if (and transient-mark-mode mark-active
)
414 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
415 t
'literal delimited nil nil start end
))
417 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
418 "Replace some matches for REGEXP with various strings, in rotation.
419 The second argument TO-STRINGS contains the replacement strings, separated
420 by spaces. This command works like `query-replace-regexp' except that
421 each successive replacement uses the next successive replacement string,
422 wrapping around from the last such string to the first.
424 In Transient Mark mode, if the mark is active, operate on the contents
425 of the region. Otherwise, operate from point to the end of the buffer.
427 Non-interactively, TO-STRINGS may be a list of replacement strings.
429 Use \\<minibuffer-local-map>\\[next-history-element] \
430 to pull the last incremental search regexp to the minibuffer
433 A prefix argument N says to use each replacement string N times
434 before rotating to the next.
435 Fourth and fifth arg START and END specify the region to operate on."
437 (let* ((from (read-regexp "Map query replace (regexp): " nil
438 query-replace-from-history-variable
))
439 (to (read-from-minibuffer
440 (format "Query replace %s with (space-separated strings): "
441 (query-replace-descr from
))
443 query-replace-to-history-variable from t
)))
445 (and current-prefix-arg
446 (prefix-numeric-value current-prefix-arg
))
447 (if (and transient-mark-mode mark-active
)
449 (if (and transient-mark-mode mark-active
)
452 (if (listp to-strings
)
453 (setq replacements to-strings
)
454 (while (/= (length to-strings
) 0)
455 (if (string-match " " to-strings
)
458 (list (substring to-strings
0
459 (string-match " " to-strings
))))
460 to-strings
(substring to-strings
461 (1+ (string-match " " to-strings
))))
462 (setq replacements
(append replacements
(list to-strings
))
464 (perform-replace regexp replacements t t nil n nil start end
)))
466 (defun replace-string (from-string to-string
&optional delimited start end
)
467 "Replace occurrences of FROM-STRING with TO-STRING.
468 Preserve case in each match if `case-replace' and `case-fold-search'
469 are non-nil and FROM-STRING has no uppercase letters.
470 \(Preserving case means that if the string matched is all caps, or capitalized,
471 then its replacement is upcased or capitalized.)
473 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
474 to be replaced will match a sequence of whitespace chars defined by the
475 regexp in `search-whitespace-regexp'.
477 In Transient Mark mode, if the mark is active, operate on the contents
478 of the region. Otherwise, operate from point to the end of the buffer.
480 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
481 only matches surrounded by word boundaries.
482 Fourth and fifth arg START and END specify the region to operate on.
484 Use \\<minibuffer-local-map>\\[next-history-element] \
485 to pull the last incremental search string to the minibuffer
486 that reads FROM-STRING.
488 This function is usually the wrong thing to use in a Lisp program.
489 What you probably want is a loop like this:
490 (while (search-forward FROM-STRING nil t)
491 (replace-match TO-STRING nil t))
492 which will run faster and will not set the mark or print anything.
493 \(You may need a more complex loop if FROM-STRING can match the null string
494 and TO-STRING is also null.)"
497 (query-replace-read-args
499 (if current-prefix-arg
" word" "")
501 (if (and transient-mark-mode mark-active
) " in region" ""))
503 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
504 (if (and transient-mark-mode mark-active
)
506 (if (and transient-mark-mode mark-active
)
508 (perform-replace from-string to-string nil nil delimited nil nil start end
))
510 (defun replace-regexp (regexp to-string
&optional delimited start end
)
511 "Replace things after point matching REGEXP with TO-STRING.
512 Preserve case in each match if `case-replace' and `case-fold-search'
513 are non-nil and REGEXP has no uppercase letters.
515 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
516 to be replaced will match a sequence of whitespace chars defined by the
517 regexp in `search-whitespace-regexp'.
519 In Transient Mark mode, if the mark is active, operate on the contents
520 of the region. Otherwise, operate from point to the end of the buffer.
522 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
523 only matches surrounded by word boundaries.
524 Fourth and fifth arg START and END specify the region to operate on.
526 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
527 and `\\=\\N' (where N is a digit) stands for
528 whatever what matched the Nth `\\(...\\)' in REGEXP.
529 `\\?' lets you edit the replacement text in the minibuffer
530 at the given position for each replacement.
532 In interactive calls, the replacement text may contain `\\,'
533 followed by a Lisp expression used as part of the replacement
534 text. Inside of that expression, `\\&' is a string denoting the
535 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
536 numeric values from `string-to-number', and `\\#' itself for
537 `replace-count', the number of replacements occurred so far.
539 If your Lisp expression is an identifier and the next letter in
540 the replacement string would be interpreted as part of it, you
541 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
542 for this particular case you may also enter `\\#' in the
543 replacement text directly.
545 When using those Lisp features interactively in the replacement
546 text, TO-STRING is actually made a list instead of a string.
547 Use \\[repeat-complex-command] after this command for details.
549 Use \\<minibuffer-local-map>\\[next-history-element] \
550 to pull the last incremental search regexp to the minibuffer
553 This function is usually the wrong thing to use in a Lisp program.
554 What you probably want is a loop like this:
555 (while (re-search-forward REGEXP nil t)
556 (replace-match TO-STRING nil nil))
557 which will run faster and will not set the mark or print anything."
560 (query-replace-read-args
562 (if current-prefix-arg
" word" "")
564 (if (and transient-mark-mode mark-active
) " in region" ""))
566 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
567 (if (and transient-mark-mode mark-active
)
569 (if (and transient-mark-mode mark-active
)
571 (perform-replace regexp to-string nil t delimited nil nil start end
))
574 (defvar regexp-history nil
575 "History list for some commands that read regular expressions.
577 Maximum length of the history list is determined by the value
578 of `history-length', which see.")
580 (defvar occur-collect-regexp-history
'("\\1")
581 "History of regexp for occur's collect operation")
583 (defun read-regexp (prompt &optional defaults history
)
584 "Read and return a regular expression as a string.
585 When PROMPT doesn't end with a colon and space, it adds a final \": \".
586 If DEFAULTS is non-nil, it displays the first default in the prompt.
588 Non-nil optional arg DEFAULTS is a string or a list of strings that
589 are prepended to a list of standard default values, which include the
590 string at point, the last isearch regexp, the last isearch string, and
591 the last replacement regexp.
593 Non-nil HISTORY is a symbol to use for the history list.
594 If HISTORY is nil, `regexp-history' is used."
595 (let* ((default (if (consp defaults
) (car defaults
) defaults
))
598 (if (listp defaults
) defaults
(list defaults
))
600 (or (funcall (or find-tag-default-function
601 (get major-mode
'find-tag-default-function
)
604 (car regexp-search-ring
)
605 (regexp-quote (or (car search-ring
) ""))
607 query-replace-from-history-variable
)))))
608 (defaults (delete-dups (delq nil
(delete "" defaults
))))
609 ;; Do not automatically add default to the history for empty input.
610 (history-add-new-input nil
)
611 (input (read-from-minibuffer
612 (cond ((string-match-p ":[ \t]*\\'" prompt
)
615 (format "%s (default %s): " prompt
616 (query-replace-descr default
)))
618 (format "%s: " prompt
)))
619 nil nil nil
(or history
'regexp-history
) defaults t
)))
623 (add-to-history (or history
'regexp-history
) input
)))))
626 (defalias 'delete-non-matching-lines
'keep-lines
)
627 (defalias 'delete-matching-lines
'flush-lines
)
628 (defalias 'count-matches
'how-many
)
631 (defun keep-lines-read-args (prompt)
632 "Read arguments for `keep-lines' and friends.
633 Prompt for a regexp with PROMPT.
634 Value is a list, (REGEXP)."
635 (list (read-regexp prompt
) nil nil t
))
637 (defun keep-lines (regexp &optional rstart rend interactive
)
638 "Delete all lines except those containing matches for REGEXP.
639 A match split across lines preserves all the lines it lies in.
640 When called from Lisp (and usually interactively as well, see below)
641 applies to all lines starting after point.
643 If REGEXP contains upper case characters (excluding those preceded by `\\')
644 and `search-upper-case' is non-nil, the matching is case-sensitive.
646 Second and third arg RSTART and REND specify the region to operate on.
647 This command operates on (the accessible part of) all lines whose
648 accessible part is entirely contained in the region determined by RSTART
649 and REND. (A newline ending a line counts as part of that line.)
651 Interactively, in Transient Mark mode when the mark is active, operate
652 on all lines whose accessible part is entirely contained in the region.
653 Otherwise, the command applies to all lines starting after point.
654 When calling this function from Lisp, you can pretend that it was
655 called interactively by passing a non-nil INTERACTIVE argument.
657 This function starts looking for the next match from the end of
658 the previous match. Hence, it ignores matches that overlap
659 a previously found match."
663 (barf-if-buffer-read-only)
664 (keep-lines-read-args "Keep lines containing match for regexp")))
667 (goto-char (min rstart rend
))
671 (goto-char (max rstart rend
))
672 (unless (or (bolp) (eobp))
675 (if (and interactive transient-mark-mode mark-active
)
676 (setq rstart
(region-beginning)
678 (goto-char (region-end))
679 (unless (or (bolp) (eobp))
683 rend
(point-max-marker)))
686 (or (bolp) (forward-line 1))
687 (let ((start (point))
689 (if (and case-fold-search search-upper-case
)
690 (isearch-no-upper-case-p regexp t
)
692 (while (< (point) rend
)
693 ;; Start is first char not preserved by previous match.
694 (if (not (re-search-forward regexp rend
'move
))
695 (delete-region start rend
)
696 (let ((end (save-excursion (goto-char (match-beginning 0))
699 ;; Now end is first char preserved by the new match.
701 (delete-region start end
))))
703 (setq start
(save-excursion (forward-line 1) (point)))
704 ;; If the match was empty, avoid matching again at same place.
705 (and (< (point) rend
)
706 (= (match-beginning 0) (match-end 0))
708 (set-marker rend nil
)
712 (defun flush-lines (regexp &optional rstart rend interactive
)
713 "Delete lines containing matches for REGEXP.
714 When called from Lisp (and usually when called interactively as
715 well, see below), applies to the part of the buffer after point.
716 The line point is in is deleted if and only if it contains a
717 match for regexp starting after point.
719 If REGEXP contains upper case characters (excluding those preceded by `\\')
720 and `search-upper-case' is non-nil, the matching is case-sensitive.
722 Second and third arg RSTART and REND specify the region to operate on.
723 Lines partially contained in this region are deleted if and only if
724 they contain a match entirely contained in it.
726 Interactively, in Transient Mark mode when the mark is active, operate
727 on the contents of the region. Otherwise, operate from point to the
728 end of (the accessible portion of) the buffer. When calling this function
729 from Lisp, you can pretend that it was called interactively by passing
730 a non-nil INTERACTIVE argument.
732 If a match is split across lines, all the lines it lies in are deleted.
733 They are deleted _before_ looking for the next match. Hence, a match
734 starting on the same line at which another match ended is ignored."
738 (barf-if-buffer-read-only)
739 (keep-lines-read-args "Flush lines containing match for regexp")))
742 (goto-char (min rstart rend
))
743 (setq rend
(copy-marker (max rstart rend
))))
744 (if (and interactive transient-mark-mode mark-active
)
745 (setq rstart
(region-beginning)
746 rend
(copy-marker (region-end)))
748 rend
(point-max-marker)))
750 (let ((case-fold-search
751 (if (and case-fold-search search-upper-case
)
752 (isearch-no-upper-case-p regexp t
)
755 (while (and (< (point) rend
)
756 (re-search-forward regexp rend t
))
757 (delete-region (save-excursion (goto-char (match-beginning 0))
760 (progn (forward-line 1) (point))))))
761 (set-marker rend nil
)
765 (defun how-many (regexp &optional rstart rend interactive
)
766 "Print and return number of matches for REGEXP following point.
767 When called from Lisp and INTERACTIVE is omitted or nil, just return
768 the number, do not print it; if INTERACTIVE is t, the function behaves
769 in all respects as if it had been called interactively.
771 If REGEXP contains upper case characters (excluding those preceded by `\\')
772 and `search-upper-case' is non-nil, the matching is case-sensitive.
774 Second and third arg RSTART and REND specify the region to operate on.
776 Interactively, in Transient Mark mode when the mark is active, operate
777 on the contents of the region. Otherwise, operate from point to the
778 end of (the accessible portion of) the buffer.
780 This function starts looking for the next match from the end of
781 the previous match. Hence, it ignores matches that overlap
782 a previously found match."
785 (keep-lines-read-args "How many matches for regexp"))
789 (goto-char (min rstart rend
))
790 (setq rend
(max rstart rend
)))
791 (if (and interactive transient-mark-mode mark-active
)
792 (setq rstart
(region-beginning)
800 (if (and case-fold-search search-upper-case
)
801 (isearch-no-upper-case-p regexp t
)
803 (while (and (< (point) rend
)
804 (progn (setq opoint
(point))
805 (re-search-forward regexp rend t
)))
806 (if (= opoint
(point))
808 (setq count
(1+ count
))))
809 (when interactive
(message "%d occurrence%s"
811 (if (= count
1) "" "s")))
815 (defvar occur-menu-map
816 (let ((map (make-sparse-keymap)))
817 (bindings--define-key map
[next-error-follow-minor-mode
]
818 '(menu-item "Auto Occurrence Display"
819 next-error-follow-minor-mode
820 :help
"Display another occurrence when moving the cursor"
821 :button
(:toggle .
(and (boundp 'next-error-follow-minor-mode
)
822 next-error-follow-minor-mode
))))
823 (bindings--define-key map
[separator-1
] menu-bar-separator
)
824 (bindings--define-key map
[kill-this-buffer
]
825 '(menu-item "Kill Occur Buffer" kill-this-buffer
826 :help
"Kill the current *Occur* buffer"))
827 (bindings--define-key map
[quit-window
]
828 '(menu-item "Quit Occur Window" quit-window
829 :help
"Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
830 (bindings--define-key map
[revert-buffer
]
831 '(menu-item "Revert Occur Buffer" revert-buffer
832 :help
"Replace the text in the *Occur* buffer with the results of rerunning occur"))
833 (bindings--define-key map
[clone-buffer
]
834 '(menu-item "Clone Occur Buffer" clone-buffer
835 :help
"Create and return a twin copy of the current *Occur* buffer"))
836 (bindings--define-key map
[occur-rename-buffer
]
837 '(menu-item "Rename Occur Buffer" occur-rename-buffer
838 :help
"Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
839 (bindings--define-key map
[occur-edit-buffer
]
840 '(menu-item "Edit Occur Buffer" occur-edit-mode
841 :help
"Edit the *Occur* buffer and apply changes to the original buffers."))
842 (bindings--define-key map
[separator-2
] menu-bar-separator
)
843 (bindings--define-key map
[occur-mode-goto-occurrence-other-window
]
844 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
845 :help
"Go to the occurrence the current line describes, in another window"))
846 (bindings--define-key map
[occur-mode-goto-occurrence
]
847 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
848 :help
"Go to the occurrence the current line describes"))
849 (bindings--define-key map
[occur-mode-display-occurrence
]
850 '(menu-item "Display Occurrence" occur-mode-display-occurrence
851 :help
"Display in another window the occurrence the current line describes"))
852 (bindings--define-key map
[occur-next
]
853 '(menu-item "Move to Next Match" occur-next
854 :help
"Move to the Nth (default 1) next match in an Occur mode buffer"))
855 (bindings--define-key map
[occur-prev
]
856 '(menu-item "Move to Previous Match" occur-prev
857 :help
"Move to the Nth (default 1) previous match in an Occur mode buffer"))
859 "Menu keymap for `occur-mode'.")
861 (defvar occur-mode-map
862 (let ((map (make-sparse-keymap)))
863 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
864 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
865 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
866 (define-key map
"e" 'occur-edit-mode
)
867 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
868 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
869 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
870 (define-key map
"\M-n" 'occur-next
)
871 (define-key map
"\M-p" 'occur-prev
)
872 (define-key map
"r" 'occur-rename-buffer
)
873 (define-key map
"c" 'clone-buffer
)
874 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
875 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
877 "Keymap for `occur-mode'.")
879 (defvar occur-revert-arguments nil
880 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
881 See `occur-revert-function'.")
882 (make-variable-buffer-local 'occur-revert-arguments
)
883 (put 'occur-revert-arguments
'permanent-local t
)
885 (defcustom occur-mode-hook
'(turn-on-font-lock)
886 "Hook run when entering Occur mode."
890 (defcustom occur-hook nil
891 "Hook run by Occur when there are any matches."
895 (defcustom occur-mode-find-occurrence-hook nil
896 "Hook run by Occur after locating an occurrence.
897 This will be called with the cursor position at the occurrence. An application
898 for this is to reveal context in an outline-mode when the occurrence is hidden."
902 (put 'occur-mode
'mode-class
'special
)
903 (define-derived-mode occur-mode special-mode
"Occur"
904 "Major mode for output from \\[occur].
905 \\<occur-mode-map>Move point to one of the items in this buffer, then use
906 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
907 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
910 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
911 (setq next-error-function
'occur-next-error
))
916 (defvar occur-edit-mode-map
917 (let ((map (make-sparse-keymap)))
918 (set-keymap-parent map text-mode-map
)
919 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
920 (define-key map
"\C-c\C-c" 'occur-cease-edit
)
921 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
922 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
923 (bindings--define-key map
[menu-bar occur
] (cons "Occur" occur-menu-map
))
925 "Keymap for `occur-edit-mode'.")
927 (define-derived-mode occur-edit-mode occur-mode
"Occur-Edit"
928 "Major mode for editing *Occur* buffers.
929 In this mode, changes to the *Occur* buffer are also applied to
930 the originating buffer.
932 To return to ordinary Occur mode, use \\[occur-cease-edit]."
933 (setq buffer-read-only nil
)
934 (add-hook 'after-change-functions
'occur-after-change-function nil t
)
935 (message (substitute-command-keys
936 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
938 (defun occur-cease-edit ()
939 "Switch from Occur Edit mode to Occur mode."
941 (when (derived-mode-p 'occur-edit-mode
)
943 (message "Switching to Occur mode.")))
945 (defun occur-after-change-function (beg end length
)
948 (let* ((line-beg (line-beginning-position))
949 (m (get-text-property line-beg
'occur-target
))
950 (buf (marker-buffer m
))
952 (when (and (get-text-property line-beg
'occur-prefix
)
953 (not (get-text-property end
'occur-prefix
)))
955 ;; Apply occur-target property to inserted (e.g. yanked) text.
956 (put-text-property beg end
'occur-target m
)
957 ;; Did we insert a newline? Occur Edit mode can't create new
958 ;; Occur entries; just discard everything after the newline.
960 (and (search-forward "\n" end t
)
961 (delete-region (1- (point)) end
))))
962 (let* ((line (- (line-number-at-pos)
963 (line-number-at-pos (window-start))))
964 (readonly (with-current-buffer buf buffer-read-only
))
965 (win (or (get-buffer-window buf
)
967 '(nil (inhibit-same-window . t
)
968 (inhibit-switch-frame . t
)))))
969 (line-end (line-end-position))
970 (text (save-excursion
971 (goto-char (next-single-property-change
972 line-beg
'occur-prefix nil
974 (setq col
(- (point) line-beg
))
975 (buffer-substring-no-properties (point) line-end
))))
976 (with-selected-window win
980 (message "Buffer `%s' is read only." buf
)
981 (delete-region (line-beginning-position) (line-end-position))
983 (move-to-column col
)))))))
986 (defun occur-revert-function (_ignore1 _ignore2
)
987 "Handle `revert-buffer' for Occur mode buffers."
988 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
990 (defun occur-mode-find-occurrence ()
991 (let ((pos (get-text-property (point) 'occur-target
)))
993 (error "No occurrence on this line"))
994 (unless (buffer-live-p (marker-buffer pos
))
995 (error "Buffer for this occurrence was killed"))
998 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
999 (defun occur-mode-goto-occurrence (&optional event
)
1000 "Go to the occurrence on the current line."
1001 (interactive (list last-nonmenu-event
))
1004 ;; Actually `event-end' works correctly with a nil argument as
1005 ;; well, so we could dispense with this test, but let's not
1006 ;; rely on this undocumented behavior.
1007 (occur-mode-find-occurrence)
1008 (with-current-buffer (window-buffer (posn-window (event-end event
)))
1010 (goto-char (posn-point (event-end event
)))
1011 (occur-mode-find-occurrence))))))
1012 (pop-to-buffer (marker-buffer pos
))
1014 (run-hooks 'occur-mode-find-occurrence-hook
)))
1016 (defun occur-mode-goto-occurrence-other-window ()
1017 "Go to the occurrence the current line describes, in another window."
1019 (let ((pos (occur-mode-find-occurrence)))
1020 (switch-to-buffer-other-window (marker-buffer pos
))
1022 (run-hooks 'occur-mode-find-occurrence-hook
)))
1024 (defun occur-mode-display-occurrence ()
1025 "Display in another window the occurrence the current line describes."
1027 (let ((pos (occur-mode-find-occurrence))
1029 (setq window
(display-buffer (marker-buffer pos
) t
))
1030 ;; This is the way to set point in the proper window.
1031 (save-selected-window
1032 (select-window window
)
1034 (run-hooks 'occur-mode-find-occurrence-hook
))))
1036 (defun occur-find-match (n search message
)
1037 (if (not n
) (setq n
1))
1040 (setq r
(funcall search
(point) 'occur-match
))
1042 (get-text-property r
'occur-match
)
1043 (setq r
(funcall search r
'occur-match
)))
1049 (defun occur-next (&optional n
)
1050 "Move to the Nth (default 1) next match in an Occur mode buffer."
1052 (occur-find-match n
#'next-single-property-change
"No more matches"))
1054 (defun occur-prev (&optional n
)
1055 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1057 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
1059 (defun occur-next-error (&optional argp reset
)
1060 "Move to the Nth (default 1) next match in an Occur mode buffer.
1061 Compatibility function for \\[next-error] invocations."
1063 ;; we need to run occur-find-match from within the Occur buffer
1064 (with-current-buffer
1065 ;; Choose the buffer and make it current.
1066 (if (next-error-buffer-p (current-buffer))
1068 (next-error-find-buffer nil nil
1070 (eq major-mode
'occur-mode
))))
1072 (goto-char (cond (reset (point-min))
1073 ((< argp
0) (line-beginning-position))
1074 ((> argp
0) (line-end-position))
1079 #'previous-single-property-change
1080 #'next-single-property-change
)
1082 ;; In case the *Occur* buffer is visible in a nonselected window.
1083 (let ((win (get-buffer-window (current-buffer) t
)))
1084 (if win
(set-window-point win
(point))))
1085 (occur-mode-goto-occurrence)))
1088 '((((class color
) (min-colors 88) (background light
))
1089 :background
"yellow1")
1090 (((class color
) (min-colors 88) (background dark
))
1091 :background
"RoyalBlue3")
1092 (((class color
) (min-colors 8) (background light
))
1093 :background
"yellow" :foreground
"black")
1094 (((class color
) (min-colors 8) (background dark
))
1095 :background
"blue" :foreground
"white")
1096 (((type tty
) (class mono
))
1098 (t :background
"gray"))
1099 "Face used to highlight matches permanently."
1103 (defcustom list-matching-lines-default-context-lines
0
1104 "Default number of context lines included around `list-matching-lines' matches.
1105 A negative number means to include that many lines before the match.
1106 A positive number means to include that many lines both before and after."
1110 (defalias 'list-matching-lines
'occur
)
1112 (defcustom list-matching-lines-face
'match
1113 "Face used by \\[list-matching-lines] to show the text that matches.
1114 If the value is nil, don't highlight the matching portions specially."
1118 (defcustom list-matching-lines-buffer-name-face
'underline
1119 "Face used by \\[list-matching-lines] to show the names of buffers.
1120 If the value is nil, don't highlight the buffer names specially."
1124 (defcustom occur-excluded-properties
1125 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1126 yank-handler follow-link
)
1127 "Text properties to discard when copying lines to the *Occur* buffer.
1128 The value should be a list of text properties to discard or t,
1129 which means to discard all text properties."
1130 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
1134 (defun occur-read-primary-args ()
1135 (let* ((perform-collect (consp current-prefix-arg
))
1136 (regexp (read-regexp (if perform-collect
1137 "Collect strings matching regexp"
1138 "List lines matching regexp")
1139 (car regexp-history
))))
1142 ;; Perform collect operation
1143 (if (zerop (regexp-opt-depth regexp
))
1144 ;; No subexpression so collect the entire match.
1146 ;; Get the regexp for collection pattern.
1147 (let ((default (car occur-collect-regexp-history
)))
1149 (format "Regexp to collect (default %s): " default
)
1150 default
'occur-collect-regexp-history
)))
1151 ;; Otherwise normal occur takes numerical prefix argument.
1152 (when current-prefix-arg
1153 (prefix-numeric-value current-prefix-arg
))))))
1155 (defun occur-rename-buffer (&optional unique-p interactive-p
)
1156 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1157 Here `original-buffer-name' is the buffer name where Occur was originally run.
1158 When given the prefix argument, or called non-interactively, the renaming
1159 will not clobber the existing buffer(s) of that name, but use
1160 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1161 if you always want a separate *Occur* buffer for each buffer where you
1163 (interactive "P\np")
1164 (with-current-buffer
1165 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
1166 (rename-buffer (concat "*Occur: "
1167 (mapconcat #'buffer-name
1168 (car (cddr occur-revert-arguments
)) "/")
1170 (or unique-p
(not interactive-p
)))))
1172 (defun occur (regexp &optional nlines
)
1173 "Show all lines in the current buffer containing a match for REGEXP.
1174 If a match spreads across multiple lines, all those lines are shown.
1176 Each line is displayed with NLINES lines before and after, or -NLINES
1177 before if NLINES is negative.
1178 NLINES defaults to `list-matching-lines-default-context-lines'.
1179 Interactively it is the prefix arg.
1181 The lines are shown in a buffer named `*Occur*'.
1182 It serves as a menu to find any of the occurrences in this buffer.
1183 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1185 If REGEXP contains upper case characters (excluding those preceded by `\\')
1186 and `search-upper-case' is non-nil, the matching is case-sensitive.
1188 When NLINES is a string or when the function is called
1189 interactively with prefix argument without a number (`C-u' alone
1190 as prefix) the matching strings are collected into the `*Occur*'
1191 buffer by using NLINES as a replacement regexp. NLINES may
1192 contain \\& and \\N which convention follows `replace-match'.
1193 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1194 \"\\1\" for NLINES collects all the function names in a lisp
1195 program. When there is no parenthesized subexpressions in REGEXP
1196 the entire match is collected. In any case the searched buffer
1198 (interactive (occur-read-primary-args))
1199 (occur-1 regexp nlines
(list (current-buffer))))
1201 (defvar ido-ignore-item-temp-list
)
1203 (defun multi-occur (bufs regexp
&optional nlines
)
1204 "Show all lines in buffers BUFS containing a match for REGEXP.
1205 This function acts on multiple buffers; otherwise, it is exactly like
1206 `occur'. When you invoke this command interactively, you must specify
1207 the buffer names that you want, one by one.
1208 See also `multi-occur-in-matching-buffers'."
1211 (let* ((bufs (list (read-buffer "First buffer to search: "
1212 (current-buffer) t
)))
1214 (ido-ignore-item-temp-list bufs
))
1215 (while (not (string-equal
1216 (setq buf
(read-buffer
1217 (if (eq read-buffer-function
'ido-read-buffer
)
1218 "Next buffer to search (C-j to end): "
1219 "Next buffer to search (RET to end): ")
1222 (add-to-list 'bufs buf
)
1223 (setq ido-ignore-item-temp-list bufs
))
1224 (nreverse (mapcar #'get-buffer bufs
)))
1225 (occur-read-primary-args)))
1226 (occur-1 regexp nlines bufs
))
1228 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1229 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1230 Normally BUFREGEXP matches against each buffer's visited file name,
1231 but if you specify a prefix argument, it matches against the buffer name.
1232 See also `multi-occur'."
1235 (let* ((default (car regexp-history
))
1238 (if current-prefix-arg
1239 "List lines in buffers whose names match regexp: "
1240 "List lines in buffers whose filenames match regexp: "))))
1241 (if (equal input
"")
1244 (occur-read-primary-args)))
1248 (mapcar (lambda (buf)
1250 (string-match bufregexp
1252 (and (buffer-file-name buf
)
1253 (string-match bufregexp
1254 (buffer-file-name buf
))))
1258 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1259 (unless (and regexp
(not (equal regexp
"")))
1260 (error "Occur doesn't work with the empty regexp"))
1262 (setq buf-name
"*Occur*"))
1264 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1265 (when (buffer-live-p buf
) buf
))
1267 ;; Handle the case where one of the buffers we're searching is the
1268 ;; output buffer. Just rename it.
1269 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1270 (with-current-buffer (get-buffer buf-name
)
1273 ;; Now find or create the output buffer.
1274 ;; If we just renamed that buffer, we will make a new one here.
1275 (setq occur-buf
(get-buffer-create buf-name
))
1277 (with-current-buffer occur-buf
1278 (if (stringp nlines
)
1279 (fundamental-mode) ;; This is for collect operation.
1281 (let ((inhibit-read-only t
)
1282 ;; Don't generate undo entries for creation of the initial contents.
1283 (buffer-undo-list t
))
1286 (if (stringp nlines
)
1287 ;; Treat nlines as a regexp to collect.
1288 (let ((bufs active-bufs
)
1291 (with-current-buffer (car bufs
)
1293 (goto-char (point-min))
1294 (while (re-search-forward regexp nil t
)
1295 ;; Insert the replacement regexp.
1296 (let ((str (match-substitute-replacement nlines
)))
1298 (with-current-buffer occur-buf
1300 (setq count
(1+ count
))
1301 (or (zerop (current-column))
1302 (insert "\n"))))))))
1303 (setq bufs
(cdr bufs
)))
1305 ;; Perform normal occur.
1307 regexp active-bufs occur-buf
1308 (or nlines list-matching-lines-default-context-lines
)
1309 (if (and case-fold-search search-upper-case
)
1310 (isearch-no-upper-case-p regexp t
)
1312 list-matching-lines-buffer-name-face
1313 nil list-matching-lines-face
1314 (not (eq occur-excluded-properties t
))))))
1315 (let* ((bufcount (length active-bufs
))
1316 (diff (- (length bufs
) bufcount
)))
1317 (message "Searched %d buffer%s%s; %s match%s%s"
1318 bufcount
(if (= bufcount
1) "" "s")
1319 (if (zerop diff
) "" (format " (%d killed)" diff
))
1320 (if (zerop count
) "no" (format "%d" count
))
1321 (if (= count
1) "" "es")
1322 ;; Don't display regexp if with remaining text
1323 ;; it is longer than window-width.
1324 (if (> (+ (length regexp
) 42) (window-width))
1325 "" (format " for `%s'" (query-replace-descr regexp
)))))
1326 (setq occur-revert-arguments
(list regexp nlines bufs
))
1328 (kill-buffer occur-buf
)
1329 (display-buffer occur-buf
)
1330 (setq next-error-last-buffer occur-buf
)
1331 (setq buffer-read-only t
)
1332 (set-buffer-modified-p nil
)
1333 (run-hooks 'occur-hook
)))))))
1335 (defun occur-engine (regexp buffers out-buf nlines case-fold
1336 title-face prefix-face match-face keep-props
)
1337 (with-current-buffer out-buf
1338 (let ((globalcount 0)
1340 (case-fold-search case-fold
))
1341 ;; Map over all the buffers
1342 (dolist (buf buffers
)
1343 (when (buffer-live-p buf
)
1344 (let ((matches 0) ;; count of matched lines
1345 (lines 1) ;; line count
1346 (prev-after-lines nil
) ;; context lines of prev match
1347 (prev-lines nil
) ;; line number of prev match endpt
1355 (inhibit-field-text-motion t
)
1356 (headerpt (with-current-buffer out-buf
(point))))
1357 (with-current-buffer buf
1359 ;; Set CODING only if the current buffer locally
1360 ;; binds buffer-file-coding-system.
1361 (not (local-variable-p 'buffer-file-coding-system
))
1362 (setq coding buffer-file-coding-system
))
1364 (goto-char (point-min)) ;; begin searching in the buffer
1366 (setq origpt
(point))
1367 (when (setq endpt
(re-search-forward regexp nil t
))
1368 (setq matches
(1+ matches
)) ;; increment match count
1369 (setq matchbeg
(match-beginning 0))
1370 ;; Get beginning of first match line and end of the last.
1372 (goto-char matchbeg
)
1373 (setq begpt
(line-beginning-position))
1375 (setq endpt
(line-end-position)))
1376 ;; Sum line numbers up to the first match line.
1377 (setq lines
(+ lines
(count-lines origpt begpt
)))
1378 (setq marker
(make-marker))
1379 (set-marker marker matchbeg
)
1380 (setq curstring
(occur-engine-line begpt endpt keep-props
))
1381 ;; Highlight the matches
1382 (let ((len (length curstring
))
1384 (while (and (< start len
)
1385 (string-match regexp curstring start
))
1386 (add-text-properties
1387 (match-beginning 0) (match-end 0)
1391 ;; Use `face' rather than `font-lock-face' here
1392 ;; so as to override faces copied from the buffer.
1393 `(face ,match-face
)))
1395 (setq start
(match-end 0))))
1396 ;; Generate the string to insert for this match
1397 (let* ((match-prefix
1398 ;; Using 7 digits aligns tabs properly.
1399 (apply #'propertize
(format "%7d:" lines
)
1402 `(font-lock-face prefix-face
))
1403 `(occur-prefix t mouse-face
(highlight)
1404 ;; Allow insertion of text at
1405 ;; the end of the prefix (for
1406 ;; Occur Edit mode).
1407 front-sticky t rear-nonsticky t
1408 occur-target
,marker follow-link t
1409 help-echo
"mouse-2: go to this occurrence"))))
1411 ;; We don't put `mouse-face' on the newline,
1412 ;; because that loses. And don't put it
1413 ;; on context lines to reduce flicker.
1414 (propertize curstring
'mouse-face
(list 'highlight
)
1415 'occur-target marker
1418 "mouse-2: go to this occurrence"))
1422 ;; Add non-numeric prefix to all non-first lines
1423 ;; of multi-line matches.
1424 (replace-regexp-in-string
1428 ;; Add marker at eol, but no mouse props.
1429 (propertize "\n" 'occur-target marker
)))
1432 ;; The simple display style
1434 ;; The complex multi-line display style.
1435 (setq ret
(occur-context-lines
1436 out-line nlines keep-props begpt endpt
1437 lines prev-lines prev-after-lines
))
1438 ;; Set first elem of the returned list to `data',
1439 ;; and the second elem to `prev-after-lines'.
1440 (setq prev-after-lines
(nth 1 ret
))
1442 ;; Actually insert the match display data
1443 (with-current-buffer out-buf
1448 ;; Sum line numbers between first and last match lines.
1449 (setq lines
(+ lines
(count-lines begpt endpt
)
1450 ;; Add 1 for empty last match line since
1451 ;; count-lines returns 1 line less.
1452 (if (and (bolp) (eolp)) 1 0)))
1453 ;; On to the next match...
1455 (goto-char (point-max)))
1456 (setq prev-lines
(1- lines
)))
1457 ;; Flush remaining context after-lines.
1458 (when prev-after-lines
1459 (with-current-buffer out-buf
1460 (insert (apply #'concat
(occur-engine-add-prefix
1461 prev-after-lines
)))))))
1462 (when (not (zerop matches
)) ;; is the count zero?
1463 (setq globalcount
(+ globalcount matches
))
1464 (with-current-buffer out-buf
1465 (goto-char headerpt
)
1469 (format "%d match%s%s in buffer: %s\n"
1470 matches
(if (= matches
1) "" "es")
1471 ;; Don't display regexp for multi-buffer.
1472 (if (> (length buffers
) 1)
1473 "" (format " for \"%s\""
1474 (query-replace-descr regexp
)))
1478 (add-text-properties beg end
1481 `(font-lock-face ,title-face
))
1482 `(occur-title ,buf
))))
1483 (goto-char (point-min)))))))
1484 ;; Display total match count and regexp for multi-buffer.
1485 (when (and (not (zerop globalcount
)) (> (length buffers
) 1))
1486 (goto-char (point-min))
1489 (insert (format "%d match%s total for \"%s\":\n"
1490 globalcount
(if (= globalcount
1) "" "es")
1491 (query-replace-descr regexp
)))
1493 (add-text-properties beg end
(when title-face
1494 `(font-lock-face ,title-face
))))
1495 (goto-char (point-min)))
1497 ;; CODING is buffer-file-coding-system of the first buffer
1498 ;; that locally binds it. Let's use it also for the output
1500 (set-buffer-file-coding-system coding
))
1501 ;; Return the number of matches
1504 (defun occur-engine-line (beg end
&optional keep-props
)
1505 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
1506 (text-property-not-all beg end
'fontified t
))
1507 (if (fboundp 'jit-lock-fontify-now
)
1508 (jit-lock-fontify-now beg end
)))
1509 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1510 (let ((str (buffer-substring beg end
)))
1511 (remove-list-of-text-properties
1512 0 (length str
) occur-excluded-properties str
)
1514 (buffer-substring-no-properties beg end
)))
1516 (defun occur-engine-add-prefix (lines)
1519 (concat " :" line
"\n"))
1522 (defun occur-accumulate-lines (count &optional keep-props pt
)
1526 (let ((forwardp (> count
0))
1527 result beg end moved
)
1528 (while (not (or (zerop count
)
1531 (and (bobp) (not moved
)))))
1532 (setq count
(+ count
(if forwardp -
1 1)))
1533 (setq beg
(line-beginning-position)
1534 end
(line-end-position))
1535 (push (occur-engine-line beg end keep-props
) result
)
1536 (setq moved
(= 0 (forward-line (if forwardp
1 -
1)))))
1537 (nreverse result
))))
1539 ;; Generate context display for occur.
1540 ;; OUT-LINE is the line where the match is.
1541 ;; NLINES and KEEP-PROPS are args to occur-engine.
1542 ;; LINES is line count of the current match,
1543 ;; PREV-LINES is line count of the previous match,
1544 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1545 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1546 ;; then concatenate them all together.
1547 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1548 lines prev-lines prev-after-lines
)
1549 ;; Find after- and before-context lines of the current match.
1551 (nreverse (cdr (occur-accumulate-lines
1552 (- (1+ (abs nlines
))) keep-props begpt
))))
1554 (cdr (occur-accumulate-lines
1555 (1+ nlines
) keep-props endpt
)))
1558 ;; Combine after-lines of the previous match
1559 ;; with before-lines of the current match.
1561 (when prev-after-lines
1562 ;; Don't overlap prev after-lines with current before-lines.
1563 (if (>= (+ prev-lines
(length prev-after-lines
))
1564 (- lines
(length before-lines
)))
1565 (setq prev-after-lines
1566 (butlast prev-after-lines
1567 (- (length prev-after-lines
)
1568 (- lines prev-lines
(length before-lines
) 1))))
1569 ;; Separate non-overlapping context lines with a dashed line.
1570 (setq separator
"-------\n")))
1573 ;; Don't overlap current before-lines with previous match line.
1574 (if (<= (- lines
(length before-lines
))
1577 (nthcdr (- (length before-lines
)
1578 (- lines prev-lines
1))
1580 ;; Separate non-overlapping before-context lines.
1581 (unless (> nlines
0)
1582 (setq separator
"-------\n"))))
1585 ;; Return a list where the first element is the output line.
1588 (and prev-after-lines
1589 (occur-engine-add-prefix prev-after-lines
))
1590 (and separator
(list separator
))
1591 (occur-engine-add-prefix before-lines
)
1593 ;; And the second element is the list of context after-lines.
1594 (if (> nlines
0) after-lines
))))
1597 ;; It would be nice to use \\[...], but there is no reasonable way
1598 ;; to make that display both SPC and Y.
1599 (defconst query-replace-help
1600 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1601 RET or `q' to exit, Period to replace one match and exit,
1602 Comma to replace but not move point immediately,
1603 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1604 C-w to delete match and recursive edit,
1605 C-l to clear the screen, redisplay, and offer same replacement again,
1606 ! to replace all remaining matches in this buffer with no more questions,
1607 ^ to move point back to previous match,
1608 E to edit the replacement string.
1609 In multi-buffer replacements type `Y' to replace all remaining
1610 matches in all remaining buffers with no more questions,
1611 `N' to skip to the next buffer without replacing remaining matches
1612 in the current buffer."
1613 "Help message while in `query-replace'.")
1615 (defvar query-replace-map
1616 (let ((map (make-sparse-keymap)))
1617 (define-key map
" " 'act
)
1618 (define-key map
"\d" 'skip
)
1619 (define-key map
[delete] 'skip)
1620 (define-key map [backspace] 'skip)
1621 (define-key map "y" 'act)
1622 (define-key map "n" 'skip)
1623 (define-key map "Y" 'act)
1624 (define-key map "N" 'skip)
1625 (define-key map "e" 'edit-replacement)
1626 (define-key map "E" 'edit-replacement)
1627 (define-key map "," 'act-and-show)
1628 (define-key map "q" 'exit)
1629 (define-key map "\r" 'exit)
1630 (define-key map [return] 'exit)
1631 (define-key map "." 'act-and-exit)
1632 (define-key map "\C-r" 'edit)
1633 (define-key map "\C-w" 'delete-and-edit)
1634 (define-key map "\C-l" 'recenter)
1635 (define-key map "!" 'automatic)
1636 (define-key map "^" 'backup)
1637 (define-key map "\C-h" 'help)
1638 (define-key map [f1] 'help)
1639 (define-key map [help] 'help)
1640 (define-key map "?" 'help)
1641 (define-key map "\C-g" 'quit)
1642 (define-key map "\C-]" 'quit)
1643 (define-key map "\C-v" 'scroll-up)
1644 (define-key map "\M-v" 'scroll-down)
1645 (define-key map [next] 'scroll-up)
1646 (define-key map [prior] 'scroll-down)
1647 (define-key map [?\C-\M-v] 'scroll-other-window)
1648 (define-key map [M-next] 'scroll-other-window)
1649 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1650 (define-key map [M-prior] 'scroll-other-window-down)
1651 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1652 ;; should check for ESC specially.
1653 ;; (define-key map "\e" 'exit-prefix)
1654 (define-key map [escape] 'exit-prefix)
1656 "Keymap of responses to questions posed by commands like `query-replace'.
1657 The \"bindings\" in this map are not commands; they are answers.
1658 The valid answers include `act', `skip', `act-and-show',
1659 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1660 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1661 `edit', `edit-replacement', `delete-and-edit', `automatic',
1662 `backup', `quit', and `help'.
1664 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1666 (defvar multi-query-replace-map
1667 (let ((map (make-sparse-keymap)))
1668 (set-keymap-parent map query-replace-map)
1669 (define-key map "Y" 'automatic-all)
1670 (define-key map "N" 'exit-current)
1672 "Keymap that defines additional bindings for multi-buffer replacements.
1673 It extends its parent map `query-replace-map' with new bindings to
1674 operate on a set of buffers/files. The difference with its parent map
1675 is the additional answers `automatic-all' to replace all remaining
1676 matches in all remaining buffers with no more questions, and
1677 `exit-current' to skip remaining matches in the current buffer
1678 and to continue with the next buffer in the sequence.")
1680 (defun replace-match-string-symbols (n)
1681 "Process a list (and any sub-lists), expanding certain symbols.
1683 N (match-string N) (where N is a string of digits)
1684 #N (string-to-number (match-string N))
1686 #& (string-to-number (match-string 0))
1689 Note that these symbols must be preceded by a backslash in order to
1690 type them using Lisp syntax."
1694 (replace-match-string-symbols (car n))) ;Process sub-list
1696 (let ((name (symbol-name (car n))))
1698 ((string-match "^[0-9]+$" name)
1699 (setcar n (list 'match-string (string-to-number name))))
1700 ((string-match "^#[0-9]+$" name)
1701 (setcar n (list 'string-to-number
1703 (string-to-number (substring name 1))))))
1705 (setcar n '(match-string 0)))
1706 ((string= "#&" name)
1707 (setcar n '(string-to-number (match-string 0))))
1709 (setcar n 'replace-count))))))
1712 (defun replace-eval-replacement (expression count)
1713 (let* ((replace-count count)
1714 (replacement (eval expression)))
1715 (if (stringp replacement)
1717 (prin1-to-string replacement t))))
1719 (defun replace-quote (replacement)
1720 "Quote a replacement string.
1721 This just doubles all backslashes in REPLACEMENT and
1722 returns the resulting string. If REPLACEMENT is not
1723 a string, it is first passed through `prin1-to-string'
1724 with the `noescape' argument set.
1726 `match-data' is preserved across the call."
1728 (replace-regexp-in-string "\\\\" "\\\\"
1729 (if (stringp replacement)
1731 (prin1-to-string replacement t))
1734 (defun replace-loop-through-replacements (data count)
1735 ;; DATA is a vector containing the following values:
1736 ;; 0 next-rotate-count
1738 ;; 2 next-replacement
1740 (if (= (aref data 0) count)
1742 (aset data 0 (+ count (aref data 1)))
1743 (let ((next (cdr (aref data 2))))
1744 (aset data 2 (if (consp next) next (aref data 3))))))
1745 (car (aref data 2)))
1747 (defun replace-match-data (integers reuse &optional new)
1748 "Like `match-data', but markers in REUSE get invalidated.
1749 If NEW is non-nil, it is set and returned instead of fresh data,
1750 but coerced to the correct value of INTEGERS."
1753 (set-match-data new)
1755 (eq (null integers) (markerp (car reuse)))
1757 (match-data integers reuse t)))
1759 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1760 "Make a replacement with `replace-match', editing `\\?'.
1761 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1762 check for `\\?' is made to save time. MATCH-DATA is used for the
1763 replacement. In case editing is done, it is changed to use markers.
1765 The return value is non-nil if there has been no `\\?' or NOEDIT was
1766 passed in. If LITERAL is set, no checking is done, anyway."
1767 (unless (or literal noedit)
1769 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1772 (read-string "Edit replacement string: "
1775 (replace-match "" t t newtext 3)
1776 (1+ (match-beginning 3)))
1779 nil match-data match-data))))
1781 (set-match-data match-data)
1782 (replace-match newtext fixedcase literal)
1785 (defvar replace-search-function nil
1786 "Function to use when searching for strings to replace.
1787 It is used by `query-replace' and `replace-string', and is called
1788 with three arguments, as if it were `search-forward'.")
1790 (defvar replace-re-search-function nil
1791 "Function to use when searching for regexps to replace.
1792 It is used by `query-replace-regexp', `replace-regexp',
1793 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1794 It is called with three arguments, as if it were
1795 `re-search-forward'.")
1797 (defun perform-replace (from-string replacements
1798 query-flag regexp-flag delimited-flag
1799 &optional repeat-count map start end)
1800 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1801 Don't use this in your own program unless you want to query and set the mark
1802 just as `query-replace' does. Instead, write a simple loop like this:
1804 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1805 (replace-match \"foobar\" nil nil))
1807 which will run faster and probably do exactly what you want. Please
1808 see the documentation of `replace-match' to find out how to simulate
1811 This function returns nil if and only if there were no matches to
1812 make, or the user didn't cancel the call."
1813 (or map (setq map query-replace-map))
1814 (and query-flag minibuffer-auto-raise
1815 (raise-frame (window-frame (minibuffer-window))))
1816 (let* ((case-fold-search
1817 (if (and case-fold-search search-upper-case)
1818 (isearch-no-upper-case-p from-string regexp-flag)
1820 (nocasify (not (and case-replace case-fold-search)))
1821 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1824 replace-re-search-function
1825 replace-search-function)
1826 (let ((isearch-regexp regexp-flag)
1827 (isearch-word delimited-flag)
1828 (isearch-lax-whitespace
1829 replace-lax-whitespace)
1830 (isearch-regexp-lax-whitespace
1831 replace-regexp-lax-whitespace)
1832 (isearch-case-fold-search case-fold-search)
1833 (isearch-forward t))
1834 (isearch-search-fun))))
1835 (search-string from-string)
1836 (real-match-data nil) ; The match data for the current match.
1837 (next-replacement nil)
1838 ;; This is non-nil if we know there is nothing for the user
1839 ;; to edit in the replacement.
1844 (nonempty-match nil)
1846 (recenter-last-op nil) ; Start cycling order with initial position.
1848 ;; If non-nil, it is marker saying where in the buffer to stop.
1851 ;; Data for the next match. If a cons, it has the same format as
1852 ;; (match-data); otherwise it is t if a match is possible at point.
1858 (substitute-command-keys
1859 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1860 minibuffer-prompt-properties))))
1862 ;; If region is active, in Transient Mark mode, operate on region.
1864 (setq limit (copy-marker (max start end)))
1865 (goto-char (min start end))
1868 ;; If last typed key in previous call of multi-buffer perform-replace
1869 ;; was `automatic-all', don't ask more questions in next files
1870 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
1871 (setq query-flag nil multi-buffer t))
1873 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1874 ;; containing a function and its first argument. The function is
1875 ;; called to generate each replacement like this:
1876 ;; (funcall (car replacements) (cdr replacements) replace-count)
1877 ;; It must return a string.
1879 ((stringp replacements)
1880 (setq next-replacement replacements
1882 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1883 (or repeat-count (setq repeat-count 1))
1884 (setq replacements (cons 'replace-loop-through-replacements
1885 (vector repeat-count repeat-count
1886 replacements replacements)))))
1888 (when query-replace-lazy-highlight
1889 (setq isearch-lazy-highlight-last-string nil))
1894 ;; Loop finding occurrences that perhaps should be replaced.
1895 (while (and keep-going
1896 (not (or (eobp) (and limit (>= (point) limit))))
1897 ;; Use the next match if it is already known;
1898 ;; otherwise, search for a match after moving forward
1899 ;; one char if progress is required.
1900 (setq real-match-data
1901 (cond ((consp match-again)
1902 (goto-char (nth 1 match-again))
1904 t real-match-data match-again))
1905 ;; MATCH-AGAIN non-nil means accept an
1909 (funcall search-function search-string
1911 ;; For speed, use only integers and
1912 ;; reuse the list used last time.
1913 (replace-match-data t real-match-data)))
1914 ((and (< (1+ (point)) (point-max))
1916 (< (1+ (point)) limit)))
1917 ;; If not accepting adjacent matches,
1918 ;; move one char to the right before
1919 ;; searching again. Undo the motion
1920 ;; if the search fails.
1921 (let ((opoint (point)))
1924 search-function search-string
1931 ;; Record whether the match is nonempty, to avoid an infinite loop
1932 ;; repeatedly matching the same empty string.
1933 (setq nonempty-match
1934 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1936 ;; If the match is empty, record that the next one can't be
1939 ;; Otherwise, if matching a regular expression, do the next
1940 ;; match now, since the replacement for this match may
1941 ;; affect whether the next match is adjacent to this one.
1942 ;; If that match is empty, don't use it.
1945 (or (not regexp-flag)
1946 (and (looking-at search-string)
1947 (let ((match (match-data)))
1948 (and (/= (nth 0 match) (nth 1 match))
1951 ;; Optionally ignore matches that have a read-only property.
1952 (unless (and query-replace-skip-read-only
1953 (text-property-not-all
1954 (nth 0 real-match-data) (nth 1 real-match-data)
1957 ;; Calculate the replacement string, if necessary.
1959 (set-match-data real-match-data)
1960 (setq next-replacement
1961 (funcall (car replacements) (cdr replacements)
1963 (if (not query-flag)
1965 (unless (or literal noedit)
1967 (nth 0 real-match-data) (nth 1 real-match-data)
1968 start end search-string
1969 regexp-flag delimited-flag case-fold-search))
1971 (replace-match-maybe-edit
1972 next-replacement nocasify literal
1973 noedit real-match-data)
1974 replace-count (1+ replace-count)))
1976 (let (done replaced key def)
1977 ;; Loop reading commands until one of them sets done,
1978 ;; which means it has finished handling this
1979 ;; occurrence. Any command that sets `done' should
1980 ;; leave behind proper match data for the stack.
1981 ;; Commands not setting `done' need to adjust
1982 ;; `real-match-data'.
1984 (set-match-data real-match-data)
1986 (match-beginning 0) (match-end 0)
1987 start end search-string
1988 regexp-flag delimited-flag case-fold-search)
1989 ;; Bind message-log-max so we don't fill up the message log
1990 ;; with a bunch of identical messages.
1991 (let ((message-log-max nil)
1992 (replacement-presentation
1993 (if query-replace-show-replacement
1995 (set-match-data real-match-data)
1996 (match-substitute-replacement next-replacement
2000 (query-replace-descr from-string)
2001 (query-replace-descr replacement-presentation)))
2002 (setq key (read-event))
2003 ;; Necessary in case something happens during read-event
2004 ;; that clobbers the match data.
2005 (set-match-data real-match-data)
2006 (setq key (vector key))
2007 (setq def (lookup-key map key))
2008 ;; Restore the match data while we process the command.
2009 (cond ((eq def 'help)
2010 (with-output-to-temp-buffer "*Help*"
2012 (concat "Query replacing "
2013 (if delimited-flag "word " "")
2014 (if regexp-flag "regexp " "")
2015 from-string " with "
2016 next-replacement ".\n\n"
2017 (substitute-command-keys
2018 query-replace-help)))
2019 (with-current-buffer standard-output
2022 (setq keep-going nil)
2024 ((eq def 'exit-current)
2025 (setq multi-buffer t keep-going nil done t))
2028 (let ((elt (pop stack)))
2029 (goto-char (nth 0 elt))
2030 (setq replaced (nth 1 elt)
2035 (message "No previous match")
2036 (ding 'no-terminate)
2041 (replace-match-maybe-edit
2042 next-replacement nocasify literal
2043 noedit real-match-data)
2044 replace-count (1+ replace-count)))
2045 (setq done t replaced t))
2046 ((eq def 'act-and-exit)
2049 (replace-match-maybe-edit
2050 next-replacement nocasify literal
2051 noedit real-match-data)
2052 replace-count (1+ replace-count)))
2053 (setq keep-going nil)
2054 (setq done t replaced t))
2055 ((eq def 'act-and-show)
2058 (replace-match-maybe-edit
2059 next-replacement nocasify literal
2060 noedit real-match-data)
2061 replace-count (1+ replace-count)
2062 real-match-data (replace-match-data
2065 ((or (eq def 'automatic) (eq def 'automatic-all))
2068 (replace-match-maybe-edit
2069 next-replacement nocasify literal
2070 noedit real-match-data)
2071 replace-count (1+ replace-count)))
2072 (setq done t query-flag nil replaced t)
2073 (if (eq def 'automatic-all) (setq multi-buffer t)))
2077 ;; `this-command' has the value `query-replace',
2078 ;; so we need to bind it to `recenter-top-bottom'
2079 ;; to allow it to detect a sequence of `C-l'.
2080 (let ((this-command 'recenter-top-bottom)
2081 (last-command 'recenter-top-bottom))
2082 (recenter-top-bottom)))
2084 (let ((opos (point-marker)))
2085 (setq real-match-data (replace-match-data
2088 (goto-char (match-beginning 0))
2090 (save-window-excursion
2093 (set-marker opos nil))
2094 ;; Before we make the replacement,
2095 ;; decide whether the search string
2096 ;; can match again just after this match.
2097 (if (and regexp-flag nonempty-match)
2098 (setq match-again (and (looking-at search-string)
2100 ;; Edit replacement.
2101 ((eq def 'edit-replacement)
2102 (setq real-match-data (replace-match-data
2106 (read-string "Edit replacement string: "
2110 (set-match-data real-match-data)
2112 (replace-match-maybe-edit
2113 next-replacement nocasify literal noedit
2118 ((eq def 'delete-and-edit)
2119 (replace-match "" t t)
2120 (setq real-match-data (replace-match-data
2121 nil real-match-data))
2122 (replace-dehighlight)
2123 (save-excursion (recursive-edit))
2125 ;; Note: we do not need to treat `exit-prefix'
2126 ;; specially here, since we reread
2127 ;; any unrecognized character.
2129 (setq this-command 'mode-exited)
2130 (setq keep-going nil)
2131 (setq unread-command-events
2132 (append (listify-key-sequence key)
2133 unread-command-events))
2135 (when query-replace-lazy-highlight
2136 ;; Force lazy rehighlighting only after replacements.
2137 (if (not (memq def '(skip backup)))
2138 (setq isearch-lazy-highlight-last-string nil)))
2139 (unless (eq def 'recenter)
2140 ;; Reset recenter cycling order to initial position.
2141 (setq recenter-last-op nil)))
2142 ;; Record previous position for ^ when we move on.
2143 ;; Change markers to numbers in the match data
2144 ;; since lots of markers slow down editing.
2145 (push (list (point) replaced
2146 ;;; If the replacement has already happened, all we need is the
2147 ;;; current match start and end. We could get this with a trivial
2149 ;;; (save-excursion (goto-char (match-beginning 0))
2150 ;;; (search-forward (match-string 0))
2152 ;;; if we really wanted to avoid manually constructing match data.
2153 ;;; Adding current-buffer is necessary so that match-data calls can
2154 ;;; return markers which are appropriate for editing.
2163 (replace-dehighlight))
2164 (or unread-command-events
2165 (message "Replaced %d occurrence%s"
2167 (if (= replace-count 1) "" "s")))
2168 (or (and keep-going stack) multi-buffer)))
2170 (defvar replace-overlay nil)
2172 (defun replace-highlight (match-beg match-end range-beg range-end
2173 search-string regexp-flag delimited-flag
2175 (if query-replace-highlight
2177 (move-overlay replace-overlay match-beg match-end (current-buffer))
2178 (setq replace-overlay (make-overlay match-beg match-end))
2179 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2180 (overlay-put replace-overlay 'face 'query-replace)))
2181 (if query-replace-lazy-highlight
2182 (let ((isearch-string search-string)
2183 (isearch-regexp regexp-flag)
2184 (isearch-word delimited-flag)
2185 (isearch-lax-whitespace
2186 replace-lax-whitespace)
2187 (isearch-regexp-lax-whitespace
2188 replace-regexp-lax-whitespace)
2189 (isearch-case-fold-search case-fold-search)
2191 (isearch-error nil))
2192 (isearch-lazy-highlight-new-loop range-beg range-end))))
2194 (defun replace-dehighlight ()
2195 (when replace-overlay
2196 (delete-overlay replace-overlay))
2197 (when query-replace-lazy-highlight
2198 (lazy-highlight-cleanup lazy-highlight-cleanup)
2199 (setq isearch-lazy-highlight-last-string nil)))
2201 ;;; replace.el ends here