1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985, 1986, 1987, 1992, 1994, 1996, 1997, 2000, 2001,
4 ;; 2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; This package supplies the string and regular-expression replace functions
26 ;; documented in the Emacs user's manual.
30 (defcustom case-replace t
31 "*Non-nil means `query-replace' should preserve case in replacements."
35 (defvar query-replace-history nil
)
37 (defvar query-replace-defaults nil
38 "Default values of FROM-STRING and TO-STRING for `query-replace'.
39 This is a cons cell (FROM-STRING . TO-STRING), or nil if there is
42 (defvar query-replace-interactive nil
43 "Non-nil means `query-replace' uses the last search string.
44 That becomes the \"string to replace\".")
46 (defcustom query-replace-from-history-variable
'query-replace-history
47 "History list to use for the FROM argument of `query-replace' commands.
48 The value of this variable should be a symbol; that symbol
49 is used as a variable to hold a history list for the strings
50 or patterns to be replaced."
55 (defcustom query-replace-to-history-variable
'query-replace-history
56 "History list to use for the TO argument of `query-replace' commands.
57 The value of this variable should be a symbol; that symbol
58 is used as a variable to hold a history list for replacement
64 (defcustom query-replace-skip-read-only nil
65 "*Non-nil means `query-replace' and friends ignore read-only matches."
70 (defcustom query-replace-show-replacement t
71 "*Non-nil means to show what actual replacement text will be."
76 (defcustom query-replace-highlight t
77 "*Non-nil means to highlight matches during query replacement."
81 (defcustom query-replace-lazy-highlight t
82 "*Controls the lazy-highlighting during query replacements.
83 When non-nil, all text in the buffer matching the current match
84 is highlighted lazily using isearch lazy highlighting (see
85 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
87 :group
'lazy-highlight
91 (defface query-replace
92 '((t (:inherit isearch
)))
93 "Face for highlighting query replacement matches."
97 (defun query-replace-descr (string)
98 (mapconcat 'isearch-text-char-description string
""))
100 (defun query-replace-read-from (prompt regexp-flag
)
101 "Query and return the `from' argument of a query-replace operation.
102 The return value can also be a pair (FROM . TO) indicating that the user
103 wants to replace FROM with TO."
104 (if query-replace-interactive
105 (car (if regexp-flag regexp-search-ring search-ring
))
106 (let* ((history-add-new-input nil
)
108 ;; The save-excursion here is in case the user marks and copies
109 ;; a region in order to specify the minibuffer input.
110 ;; That should not clobber the region for the query-replace itself.
112 (read-from-minibuffer
113 (if query-replace-defaults
114 (format "%s (default %s -> %s): " prompt
115 (query-replace-descr (car query-replace-defaults
))
116 (query-replace-descr (cdr query-replace-defaults
)))
117 (format "%s: " prompt
))
119 query-replace-from-history-variable
121 (if (and (zerop (length from
)) query-replace-defaults
)
122 (cons (car query-replace-defaults
)
123 (query-replace-compile-replacement
124 (cdr query-replace-defaults
) regexp-flag
))
125 (add-to-history query-replace-from-history-variable from nil t
)
126 ;; Warn if user types \n or \t, but don't reject the input.
128 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
129 (let ((match (match-string 3 from
)))
131 ((string= match
"\\n")
132 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
133 ((string= match
"\\t")
134 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
138 (defun query-replace-compile-replacement (to regexp-flag
)
139 "Maybe convert a regexp replacement TO to Lisp.
140 Returns a list suitable for `perform-replace' if necessary,
141 the original string if not."
143 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
))
147 (setq pos
(match-end 0))
148 (push (substring to
0 (- pos
2)) list
)
149 (setq char
(aref to
(1- pos
))
150 to
(substring to pos
))
152 (push '(number-to-string replace-count
) list
))
154 (setq pos
(read-from-string to
))
155 (push `(replace-quote ,(car pos
)) list
)
157 ;; Swallow a space after a symbol
158 ;; if there is a space.
159 (if (and (or (symbolp (car pos
))
160 ;; Swallow a space after 'foo
161 ;; but not after (quote foo).
162 (and (eq (car-safe (car pos
)) 'quote
)
163 (not (= ?\
( (aref to
0)))))
164 (eq (string-match " " to
(cdr pos
))
168 (setq to
(substring to end
)))))
169 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
)))
170 (setq to
(nreverse (delete "" (cons to list
))))
171 (replace-match-string-symbols to
)
172 (cons 'replace-eval-replacement
179 (defun query-replace-read-to (from prompt regexp-flag
)
180 "Query and return the `to' argument of a query-replace operation."
181 (query-replace-compile-replacement
183 (let* ((history-add-new-input nil
)
184 (to (read-from-minibuffer
185 (format "%s %s with: " prompt
(query-replace-descr from
))
187 query-replace-to-history-variable from t
)))
188 (add-to-history query-replace-to-history-variable to nil t
)
189 (setq query-replace-defaults
(cons from to
))
193 (defun query-replace-read-args (prompt regexp-flag
&optional noerror
)
195 (barf-if-buffer-read-only))
196 (let* ((from (query-replace-read-from prompt regexp-flag
))
197 (to (if (consp from
) (prog1 (cdr from
) (setq from
(car from
)))
198 (query-replace-read-to from prompt regexp-flag
))))
199 (list from to current-prefix-arg
)))
201 (defun query-replace (from-string to-string
&optional delimited start end
)
202 "Replace some occurrences of FROM-STRING with TO-STRING.
203 As each match is found, the user must type a character saying
204 what to do with it. For directions, type \\[help-command] at that time.
206 In Transient Mark mode, if the mark is active, operate on the contents
207 of the region. Otherwise, operate from point to the end of the buffer.
209 If `query-replace-interactive' is non-nil, the last incremental search
210 string is used as FROM-STRING--you don't have to specify it with the
213 Matching is independent of case if `case-fold-search' is non-nil and
214 FROM-STRING has no uppercase letters. Replacement transfers the case
215 pattern of the old text to the new text, if `case-replace' and
216 `case-fold-search' are non-nil and FROM-STRING has no uppercase
217 letters. \(Transferring the case pattern means that if the old text
218 matched is all caps, or capitalized, then its replacement is upcased
221 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
222 only matches surrounded by word boundaries.
223 Fourth and fifth arg START and END specify the region to operate on.
225 To customize possible responses, change the \"bindings\" in `query-replace-map'."
226 (interactive (let ((common
227 (query-replace-read-args
228 (if (and transient-mark-mode mark-active
)
229 "Query replace in region"
232 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
233 ;; These are done separately here
234 ;; so that command-history will record these expressions
235 ;; rather than the values they had this time.
236 (if (and transient-mark-mode mark-active
)
238 (if (and transient-mark-mode mark-active
)
240 (perform-replace from-string to-string t nil delimited nil nil start end
))
242 (define-key esc-map
"%" 'query-replace
)
244 (defun query-replace-regexp (regexp to-string
&optional delimited start end
)
245 "Replace some things after point matching REGEXP with TO-STRING.
246 As each match is found, the user must type a character saying
247 what to do with it. For directions, type \\[help-command] at that time.
249 In Transient Mark mode, if the mark is active, operate on the contents
250 of the region. Otherwise, operate from point to the end of the buffer.
252 If `query-replace-interactive' is non-nil, the last incremental search
253 regexp is used as REGEXP--you don't have to specify it with the
256 Matching is independent of case if `case-fold-search' is non-nil and
257 REGEXP has no uppercase letters. Replacement transfers the case
258 pattern of the old text to the new text, if `case-replace' and
259 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
260 \(Transferring the case pattern means that if the old text matched is
261 all caps, or capitalized, then its replacement is upcased or
264 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
265 only matches surrounded by word boundaries.
266 Fourth and fifth arg START and END specify the region to operate on.
268 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
269 and `\\=\\N' (where N is a digit) stands for
270 whatever what matched the Nth `\\(...\\)' in REGEXP.
271 `\\?' lets you edit the replacement text in the minibuffer
272 at the given position for each replacement.
274 In interactive calls, the replacement text can contain `\\,'
275 followed by a Lisp expression. Each
276 replacement evaluates that expression to compute the replacement
277 string. Inside of that expression, `\\&' is a string denoting the
278 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
279 for the whole or a partial match converted to a number with
280 `string-to-number', and `\\#' itself for the number of replacements
281 done so far (starting with zero).
283 If the replacement expression is a symbol, write a space after it
284 to terminate it. One space there, if any, will be discarded.
286 When using those Lisp features interactively in the replacement
287 text, TO-STRING is actually made a list instead of a string.
288 Use \\[repeat-complex-command] after this command for details."
291 (query-replace-read-args
292 (if (and transient-mark-mode mark-active
)
293 "Query replace regexp in region"
294 "Query replace regexp")
296 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
297 ;; These are done separately here
298 ;; so that command-history will record these expressions
299 ;; rather than the values they had this time.
300 (if (and transient-mark-mode mark-active
)
302 (if (and transient-mark-mode mark-active
)
304 (perform-replace regexp to-string t t delimited nil nil start end
))
306 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
308 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
309 "Replace some things after point matching REGEXP with the result of TO-EXPR.
311 Interactive use of this function is deprecated in favor of the
312 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
313 using `search-forward-regexp' and `replace-match' is preferred.
315 As each match is found, the user must type a character saying
316 what to do with it. For directions, type \\[help-command] at that time.
318 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
319 reference `replace-count' to get the number of replacements already made.
320 If the result of TO-EXPR is not a string, it is converted to one using
321 `prin1-to-string' with the NOESCAPE argument (which see).
323 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
324 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
325 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
326 Use `\\#&' or `\\#N' if you want a number instead of a string.
327 In interactive use, `\\#' in itself stands for `replace-count'.
329 In Transient Mark mode, if the mark is active, operate on the contents
330 of the region. Otherwise, operate from point to the end of the buffer.
332 If `query-replace-interactive' is non-nil, the last incremental search
333 regexp is used as REGEXP--you don't have to specify it with the
336 Preserves case in each replacement if `case-replace' and `case-fold-search'
337 are non-nil and REGEXP has no uppercase letters.
339 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
340 only matches that are surrounded by word boundaries.
341 Fourth and fifth arg START and END specify the region to operate on."
344 (barf-if-buffer-read-only)
346 ;; Let-bind the history var to disable the "foo -> bar" default.
347 ;; Maybe we shouldn't disable this default, but for now I'll
348 ;; leave it off. --Stef
349 (let ((query-replace-to-history-variable nil
))
350 (query-replace-read-from "Query replace regexp" t
)))
351 (to (list (read-from-minibuffer
352 (format "Query replace regexp %s with eval: "
353 (query-replace-descr from
))
354 nil nil t query-replace-to-history-variable from t
))))
355 ;; We make TO a list because replace-match-string-symbols requires one,
356 ;; and the user might enter a single token.
357 (replace-match-string-symbols to
)
358 (list from
(car to
) current-prefix-arg
359 (if (and transient-mark-mode mark-active
)
361 (if (and transient-mark-mode mark-active
)
363 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
364 t
'literal delimited nil nil start end
))
366 (make-obsolete 'query-replace-regexp-eval
367 "for interactive use, use the special `\\,' feature of
368 `query-replace-regexp' instead. Non-interactively, a loop
369 using `search-forward-regexp' and `replace-match' is preferred." "22.1")
371 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
372 "Replace some matches for REGEXP with various strings, in rotation.
373 The second argument TO-STRINGS contains the replacement strings, separated
374 by spaces. This command works like `query-replace-regexp' except that
375 each successive replacement uses the next successive replacement string,
376 wrapping around from the last such string to the first.
378 In Transient Mark mode, if the mark is active, operate on the contents
379 of the region. Otherwise, operate from point to the end of the buffer.
381 Non-interactively, TO-STRINGS may be a list of replacement strings.
383 If `query-replace-interactive' is non-nil, the last incremental search
384 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
386 A prefix argument N says to use each replacement string N times
387 before rotating to the next.
388 Fourth and fifth arg START and END specify the region to operate on."
390 (let* ((from (if query-replace-interactive
391 (car regexp-search-ring
)
392 (read-from-minibuffer "Map query replace (regexp): "
394 'query-replace-history nil t
)))
395 (to (read-from-minibuffer
396 (format "Query replace %s with (space-separated strings): "
397 (query-replace-descr from
))
399 'query-replace-history from t
)))
401 (and current-prefix-arg
402 (prefix-numeric-value current-prefix-arg
))
403 (if (and transient-mark-mode mark-active
)
405 (if (and transient-mark-mode mark-active
)
408 (if (listp to-strings
)
409 (setq replacements to-strings
)
410 (while (/= (length to-strings
) 0)
411 (if (string-match " " to-strings
)
414 (list (substring to-strings
0
415 (string-match " " to-strings
))))
416 to-strings
(substring to-strings
417 (1+ (string-match " " to-strings
))))
418 (setq replacements
(append replacements
(list to-strings
))
420 (perform-replace regexp replacements t t nil n nil start end
)))
422 (defun replace-string (from-string to-string
&optional delimited start end
)
423 "Replace occurrences of FROM-STRING with TO-STRING.
424 Preserve case in each match if `case-replace' and `case-fold-search'
425 are non-nil and FROM-STRING has no uppercase letters.
426 \(Preserving case means that if the string matched is all caps, or capitalized,
427 then its replacement is upcased or capitalized.)
429 In Transient Mark mode, if the mark is active, operate on the contents
430 of the region. Otherwise, operate from point to the end of the buffer.
432 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
433 only matches surrounded by word boundaries.
434 Fourth and fifth arg START and END specify the region to operate on.
436 If `query-replace-interactive' is non-nil, the last incremental search
437 string is used as FROM-STRING--you don't have to specify it with the
440 This function is usually the wrong thing to use in a Lisp program.
441 What you probably want is a loop like this:
442 (while (search-forward FROM-STRING nil t)
443 (replace-match TO-STRING nil t))
444 which will run faster and will not set the mark or print anything.
445 \(You may need a more complex loop if FROM-STRING can match the null string
446 and TO-STRING is also null.)"
449 (query-replace-read-args
450 (if (and transient-mark-mode mark-active
)
451 "Replace string in region"
454 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
455 (if (and transient-mark-mode mark-active
)
457 (if (and transient-mark-mode mark-active
)
459 (perform-replace from-string to-string nil nil delimited nil nil start end
))
461 (defun replace-regexp (regexp to-string
&optional delimited start end
)
462 "Replace things after point matching REGEXP with TO-STRING.
463 Preserve case in each match if `case-replace' and `case-fold-search'
464 are non-nil and REGEXP has no uppercase letters.
466 In Transient Mark mode, if the mark is active, operate on the contents
467 of the region. Otherwise, operate from point to the end of the buffer.
469 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
470 only matches surrounded by word boundaries.
471 Fourth and fifth arg START and END specify the region to operate on.
473 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
474 and `\\=\\N' (where N is a digit) stands for
475 whatever what matched the Nth `\\(...\\)' in REGEXP.
476 `\\?' lets you edit the replacement text in the minibuffer
477 at the given position for each replacement.
479 In interactive calls, the replacement text may contain `\\,'
480 followed by a Lisp expression used as part of the replacement
481 text. Inside of that expression, `\\&' is a string denoting the
482 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
483 numeric values from `string-to-number', and `\\#' itself for
484 `replace-count', the number of replacements occurred so far.
486 If your Lisp expression is an identifier and the next letter in
487 the replacement string would be interpreted as part of it, you
488 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
489 for this particular case you may also enter `\\#' in the
490 replacement text directly.
492 When using those Lisp features interactively in the replacement
493 text, TO-STRING is actually made a list instead of a string.
494 Use \\[repeat-complex-command] after this command for details.
496 If `query-replace-interactive' is non-nil, the last incremental search
497 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
499 This function is usually the wrong thing to use in a Lisp program.
500 What you probably want is a loop like this:
501 (while (re-search-forward REGEXP nil t)
502 (replace-match TO-STRING nil nil))
503 which will run faster and will not set the mark or print anything."
506 (query-replace-read-args
507 (if (and transient-mark-mode mark-active
)
508 "Replace regexp in region"
511 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
512 (if (and transient-mark-mode mark-active
)
514 (if (and transient-mark-mode mark-active
)
516 (perform-replace regexp to-string nil t delimited nil nil start end
))
519 (defvar regexp-history nil
520 "History list for some commands that read regular expressions.
522 Maximum length of the history list is determined by the value
523 of `history-length', which see.")
525 (defun read-regexp (prompt)
526 "Read regexp as a string using the regexp history and some useful defaults.
527 Prompt for a regular expression with PROMPT in the minibuffer.
528 Provide the last element of the regexp history as the basic default,
529 and return it on typing RET. Additional defaults are the string
530 at point, the last isearch regexp, the last isearch string, and the
531 last replacement regexp. Return the regexp as a string."
532 (let* ((default (car regexp-history
))
535 (or (funcall (or find-tag-default-function
536 (get major-mode
'find-tag-default-function
)
539 (car regexp-search-ring
)
540 (regexp-quote (or (car search-ring
) ""))
542 query-replace-from-history-variable
))))
543 (defaults (delete-dups (delq nil
(delete "" defaults
))))
544 ;; Don't add automatically the car of defaults for empty input
545 (history-add-new-input nil
)
547 (read-from-minibuffer
549 (format "%s (default %s): " prompt
(query-replace-descr default
))
550 (format "%s: " prompt
))
551 nil nil nil
'regexp-history defaults t
)))
555 (add-to-history 'regexp-history input
)))))
558 (defalias 'delete-non-matching-lines
'keep-lines
)
559 (defalias 'delete-matching-lines
'flush-lines
)
560 (defalias 'count-matches
'how-many
)
563 (defun keep-lines-read-args (prompt)
564 "Read arguments for `keep-lines' and friends.
565 Prompt for a regexp with PROMPT.
566 Value is a list, (REGEXP)."
567 (list (read-regexp prompt
) nil nil t
))
569 (defun keep-lines (regexp &optional rstart rend interactive
)
570 "Delete all lines except those containing matches for REGEXP.
571 A match split across lines preserves all the lines it lies in.
572 When called from Lisp (and usually interactively as well, see below)
573 applies to all lines starting after point.
575 If REGEXP contains upper case characters (excluding those preceded by `\\')
576 and `search-upper-case' is non-nil, the matching is case-sensitive.
578 Second and third arg RSTART and REND specify the region to operate on.
579 This command operates on (the accessible part of) all lines whose
580 accessible part is entirely contained in the region determined by RSTART
581 and REND. (A newline ending a line counts as part of that line.)
583 Interactively, in Transient Mark mode when the mark is active, operate
584 on all lines whose accessible part is entirely contained in the region.
585 Otherwise, the command applies to all lines starting after point.
586 When calling this function from Lisp, you can pretend that it was
587 called interactively by passing a non-nil INTERACTIVE argument.
589 This function starts looking for the next match from the end of
590 the previous match. Hence, it ignores matches that overlap
591 a previously found match."
595 (barf-if-buffer-read-only)
596 (keep-lines-read-args "Keep lines containing match for regexp")))
599 (goto-char (min rstart rend
))
603 (goto-char (max rstart rend
))
604 (unless (or (bolp) (eobp))
607 (if (and interactive transient-mark-mode mark-active
)
608 (setq rstart
(region-beginning)
610 (goto-char (region-end))
611 (unless (or (bolp) (eobp))
615 rend
(point-max-marker)))
618 (or (bolp) (forward-line 1))
619 (let ((start (point))
621 (if (and case-fold-search search-upper-case
)
622 (isearch-no-upper-case-p regexp t
)
624 (while (< (point) rend
)
625 ;; Start is first char not preserved by previous match.
626 (if (not (re-search-forward regexp rend
'move
))
627 (delete-region start rend
)
628 (let ((end (save-excursion (goto-char (match-beginning 0))
631 ;; Now end is first char preserved by the new match.
633 (delete-region start end
))))
635 (setq start
(save-excursion (forward-line 1) (point)))
636 ;; If the match was empty, avoid matching again at same place.
637 (and (< (point) rend
)
638 (= (match-beginning 0) (match-end 0))
640 (set-marker rend nil
)
644 (defun flush-lines (regexp &optional rstart rend interactive
)
645 "Delete lines containing matches for REGEXP.
646 When called from Lisp (and usually when called interactively as
647 well, see below), applies to the part of the buffer after point.
648 The line point is in is deleted if and only if it contains a
649 match for regexp starting after point.
651 If REGEXP contains upper case characters (excluding those preceded by `\\')
652 and `search-upper-case' is non-nil, the matching is case-sensitive.
654 Second and third arg RSTART and REND specify the region to operate on.
655 Lines partially contained in this region are deleted if and only if
656 they contain a match entirely contained in it.
658 Interactively, in Transient Mark mode when the mark is active, operate
659 on the contents of the region. Otherwise, operate from point to the
660 end of (the accessible portion of) the buffer. When calling this function
661 from Lisp, you can pretend that it was called interactively by passing
662 a non-nil INTERACTIVE argument.
664 If a match is split across lines, all the lines it lies in are deleted.
665 They are deleted _before_ looking for the next match. Hence, a match
666 starting on the same line at which another match ended is ignored."
670 (barf-if-buffer-read-only)
671 (keep-lines-read-args "Flush lines containing match for regexp")))
674 (goto-char (min rstart rend
))
675 (setq rend
(copy-marker (max rstart rend
))))
676 (if (and interactive transient-mark-mode mark-active
)
677 (setq rstart
(region-beginning)
678 rend
(copy-marker (region-end)))
680 rend
(point-max-marker)))
682 (let ((case-fold-search
683 (if (and case-fold-search search-upper-case
)
684 (isearch-no-upper-case-p regexp t
)
687 (while (and (< (point) rend
)
688 (re-search-forward regexp rend t
))
689 (delete-region (save-excursion (goto-char (match-beginning 0))
692 (progn (forward-line 1) (point))))))
693 (set-marker rend nil
)
697 (defun how-many (regexp &optional rstart rend interactive
)
698 "Print and return number of matches for REGEXP following point.
699 When called from Lisp and INTERACTIVE is omitted or nil, just return
700 the number, do not print it; if INTERACTIVE is t, the function behaves
701 in all respects has if it had been called interactively.
703 If REGEXP contains upper case characters (excluding those preceded by `\\')
704 and `search-upper-case' is non-nil, the matching is case-sensitive.
706 Second and third arg RSTART and REND specify the region to operate on.
708 Interactively, in Transient Mark mode when the mark is active, operate
709 on the contents of the region. Otherwise, operate from point to the
710 end of (the accessible portion of) the buffer.
712 This function starts looking for the next match from the end of
713 the previous match. Hence, it ignores matches that overlap
714 a previously found match."
717 (keep-lines-read-args "How many matches for regexp"))
721 (goto-char (min rstart rend
))
722 (setq rend
(max rstart rend
)))
723 (if (and interactive transient-mark-mode mark-active
)
724 (setq rstart
(region-beginning)
732 (if (and case-fold-search search-upper-case
)
733 (isearch-no-upper-case-p regexp t
)
735 (while (and (< (point) rend
)
736 (progn (setq opoint
(point))
737 (re-search-forward regexp rend t
)))
738 (if (= opoint
(point))
740 (setq count
(1+ count
))))
741 (when interactive
(message "%d occurrence%s"
743 (if (= count
1) "" "s")))
747 (defvar occur-mode-map
748 (let ((map (make-sparse-keymap)))
749 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
750 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
751 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
752 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
753 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
754 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
755 (define-key map
"\M-n" 'occur-next
)
756 (define-key map
"\M-p" 'occur-prev
)
757 (define-key map
"r" 'occur-rename-buffer
)
758 (define-key map
"c" 'clone-buffer
)
759 (define-key map
"g" 'revert-buffer
)
760 (define-key map
"q" 'quit-window
)
761 (define-key map
"z" 'kill-this-buffer
)
762 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
763 (define-key map
[menu-bar
] (make-sparse-keymap))
764 (define-key map
[menu-bar occur
]
766 (define-key map
[next-error-follow-minor-mode
]
767 (menu-bar-make-mm-toggle next-error-follow-minor-mode
768 "Auto Occurrence Display"
769 "Display another occurrence when moving the cursor"))
770 (define-key map
[separator-1
] '("--"))
771 (define-key map
[kill-this-buffer
]
772 '(menu-item "Kill occur buffer" kill-this-buffer
773 :help
"Kill the current *Occur* buffer"))
774 (define-key map
[quit-window
]
775 '(menu-item "Quit occur window" quit-window
776 :help
"Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
777 (define-key map
[revert-buffer
]
778 '(menu-item "Revert occur buffer" revert-buffer
779 :help
"Replace the text in the *Occur* buffer with the results of rerunning occur"))
780 (define-key map
[clone-buffer
]
781 '(menu-item "Clone occur buffer" clone-buffer
782 :help
"Create and return a twin copy of the current *Occur* buffer"))
783 (define-key map
[occur-rename-buffer
]
784 '(menu-item "Rename occur buffer" occur-rename-buffer
785 :help
"Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
786 (define-key map
[separator-2
] '("--"))
787 (define-key map
[occur-mode-goto-occurrence-other-window
]
788 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
789 :help
"Go to the occurrence the current line describes, in another window"))
790 (define-key map
[occur-mode-goto-occurrence
]
791 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
792 :help
"Go to the occurrence the current line describes"))
793 (define-key map
[occur-mode-display-occurrence
]
794 '(menu-item "Display Occurrence" occur-mode-display-occurrence
795 :help
"Display in another window the occurrence the current line describes"))
796 (define-key map
[occur-next
]
797 '(menu-item "Move to next match" occur-next
798 :help
"Move to the Nth (default 1) next match in an Occur mode buffer"))
799 (define-key map
[occur-prev
]
800 '(menu-item "Move to previous match" occur-prev
801 :help
"Move to the Nth (default 1) previous match in an Occur mode buffer"))
803 "Keymap for `occur-mode'.")
805 (defvar occur-revert-arguments nil
806 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
807 See `occur-revert-function'.")
809 (defcustom occur-mode-hook
'(turn-on-font-lock)
810 "Hook run when entering Occur mode."
814 (defcustom occur-hook nil
815 "Hook run by Occur when there are any matches."
819 (defcustom occur-mode-find-occurrence-hook nil
820 "Hook run by Occur after locating an occurrence.
821 This will be called with the cursor position at the occurrence. An application
822 for this is to reveal context in an outline-mode when the occurrence is hidden."
826 (put 'occur-mode
'mode-class
'special
)
828 "Major mode for output from \\[occur].
829 \\<occur-mode-map>Move point to one of the items in this buffer, then use
830 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
831 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
835 (kill-all-local-variables)
836 (use-local-map occur-mode-map
)
837 (setq major-mode
'occur-mode
)
838 (setq mode-name
"Occur")
839 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
840 (make-local-variable 'occur-revert-arguments
)
841 (add-hook 'change-major-mode-hook
'font-lock-defontify nil t
)
842 (setq next-error-function
'occur-next-error
)
843 (run-mode-hooks 'occur-mode-hook
))
845 (defun occur-revert-function (ignore1 ignore2
)
846 "Handle `revert-buffer' for Occur mode buffers."
847 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
849 (defun occur-mode-find-occurrence ()
850 (let ((pos (get-text-property (point) 'occur-target
)))
852 (error "No occurrence on this line"))
853 (unless (buffer-live-p (marker-buffer pos
))
854 (error "Buffer for this occurrence was killed"))
857 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
858 (defun occur-mode-goto-occurrence (&optional event
)
859 "Go to the occurrence the current line describes."
860 (interactive (list last-nonmenu-event
))
863 ;; Actually `event-end' works correctly with a nil argument as
864 ;; well, so we could dispense with this test, but let's not
865 ;; rely on this undocumented behavior.
866 (occur-mode-find-occurrence)
867 (with-current-buffer (window-buffer (posn-window (event-end event
)))
869 (goto-char (posn-point (event-end event
)))
870 (occur-mode-find-occurrence)))))
871 same-window-buffer-names
873 (pop-to-buffer (marker-buffer pos
))
875 (run-hooks 'occur-mode-find-occurrence-hook
)))
877 (defun occur-mode-goto-occurrence-other-window ()
878 "Go to the occurrence the current line describes, in another window."
880 (let ((pos (occur-mode-find-occurrence)))
881 (switch-to-buffer-other-window (marker-buffer pos
))
883 (run-hooks 'occur-mode-find-occurrence-hook
)))
885 (defun occur-mode-display-occurrence ()
886 "Display in another window the occurrence the current line describes."
888 (let ((pos (occur-mode-find-occurrence))
890 ;; Bind these to ensure `display-buffer' puts it in another window.
891 same-window-buffer-names
893 (setq window
(display-buffer (marker-buffer pos
)))
894 ;; This is the way to set point in the proper window.
895 (save-selected-window
896 (select-window window
)
898 (run-hooks 'occur-mode-find-occurrence-hook
))))
900 (defun occur-find-match (n search message
)
901 (if (not n
) (setq n
1))
904 (setq r
(funcall search
(point) 'occur-match
))
906 (get-text-property r
'occur-match
)
907 (setq r
(funcall search r
'occur-match
)))
913 (defun occur-next (&optional n
)
914 "Move to the Nth (default 1) next match in an Occur mode buffer."
916 (occur-find-match n
#'next-single-property-change
"No more matches"))
918 (defun occur-prev (&optional n
)
919 "Move to the Nth (default 1) previous match in an Occur mode buffer."
921 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
923 (defun occur-next-error (&optional argp reset
)
924 "Move to the Nth (default 1) next match in an Occur mode buffer.
925 Compatibility function for \\[next-error] invocations."
927 ;; we need to run occur-find-match from within the Occur buffer
929 ;; Choose the buffer and make it current.
930 (if (next-error-buffer-p (current-buffer))
932 (next-error-find-buffer nil nil
934 (eq major-mode
'occur-mode
))))
936 (goto-char (cond (reset (point-min))
937 ((< argp
0) (line-beginning-position))
938 ((> argp
0) (line-end-position))
943 #'previous-single-property-change
944 #'next-single-property-change
)
946 ;; In case the *Occur* buffer is visible in a nonselected window.
947 (let ((win (get-buffer-window (current-buffer) t
)))
948 (if win
(set-window-point win
(point))))
949 (occur-mode-goto-occurrence)))
952 '((((class color
) (min-colors 88) (background light
))
953 :background
"yellow1")
954 (((class color
) (min-colors 88) (background dark
))
955 :background
"RoyalBlue3")
956 (((class color
) (min-colors 8) (background light
))
957 :background
"yellow" :foreground
"black")
958 (((class color
) (min-colors 8) (background dark
))
959 :background
"blue" :foreground
"white")
960 (((type tty
) (class mono
))
962 (t :background
"gray"))
963 "Face used to highlight matches permanently."
967 (defcustom list-matching-lines-default-context-lines
0
968 "*Default number of context lines included around `list-matching-lines' matches.
969 A negative number means to include that many lines before the match.
970 A positive number means to include that many lines both before and after."
974 (defalias 'list-matching-lines
'occur
)
976 (defcustom list-matching-lines-face
'match
977 "*Face used by \\[list-matching-lines] to show the text that matches.
978 If the value is nil, don't highlight the matching portions specially."
982 (defcustom list-matching-lines-buffer-name-face
'underline
983 "*Face used by \\[list-matching-lines] to show the names of buffers.
984 If the value is nil, don't highlight the buffer names specially."
988 (defcustom occur-excluded-properties
989 '(read-only invisible intangible field mouse-face help-echo local-map keymap
990 yank-handler follow-link
)
991 "*Text properties to discard when copying lines to the *Occur* buffer.
992 The value should be a list of text properties to discard or t,
993 which means to discard all text properties."
994 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
998 (defun occur-accumulate-lines (count &optional keep-props
)
1000 (let ((forwardp (> count
0))
1002 (while (not (or (zerop count
)
1006 (setq count
(+ count
(if forwardp -
1 1)))
1007 (setq beg
(line-beginning-position)
1008 end
(line-end-position))
1009 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
1010 (text-property-not-all beg end
'fontified t
))
1011 (if (fboundp 'jit-lock-fontify-now
)
1012 (jit-lock-fontify-now beg end
)))
1014 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1015 (let ((str (buffer-substring beg end
)))
1016 (remove-list-of-text-properties
1017 0 (length str
) occur-excluded-properties str
)
1019 (buffer-substring-no-properties beg end
))
1021 (forward-line (if forwardp
1 -
1)))
1022 (nreverse result
))))
1024 (defun occur-read-primary-args ()
1025 (list (read-regexp "List lines matching regexp")
1026 (when current-prefix-arg
1027 (prefix-numeric-value current-prefix-arg
))))
1029 (defun occur-rename-buffer (&optional unique-p interactive-p
)
1030 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1031 Here `original-buffer-name' is the buffer name were Occur was originally run.
1032 When given the prefix argument, or called non-interactively, the renaming
1033 will not clobber the existing buffer(s) of that name, but use
1034 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1035 if you always want a separate *Occur* buffer for each buffer where you
1037 (interactive "P\np")
1038 (with-current-buffer
1039 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
1040 (rename-buffer (concat "*Occur: "
1041 (mapconcat #'buffer-name
1042 (car (cddr occur-revert-arguments
)) "/")
1044 (or unique-p
(not interactive-p
)))))
1046 (defun occur (regexp &optional nlines
)
1047 "Show all lines in the current buffer containing a match for REGEXP.
1048 This function can not handle matches that span more than one line.
1050 Each line is displayed with NLINES lines before and after, or -NLINES
1051 before if NLINES is negative.
1052 NLINES defaults to `list-matching-lines-default-context-lines'.
1053 Interactively it is the prefix arg.
1055 The lines are shown in a buffer named `*Occur*'.
1056 It serves as a menu to find any of the occurrences in this buffer.
1057 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1059 If REGEXP contains upper case characters (excluding those preceded by `\\')
1060 and `search-upper-case' is non-nil, the matching is case-sensitive."
1061 (interactive (occur-read-primary-args))
1062 (occur-1 regexp nlines
(list (current-buffer))))
1064 (defun multi-occur (bufs regexp
&optional nlines
)
1065 "Show all lines in buffers BUFS containing a match for REGEXP.
1066 This function acts on multiple buffers; otherwise, it is exactly like
1067 `occur'. When you invoke this command interactively, you must specify
1068 the buffer names that you want, one by one."
1071 (let* ((bufs (list (read-buffer "First buffer to search: "
1072 (current-buffer) t
)))
1074 (ido-ignore-item-temp-list bufs
))
1075 (while (not (string-equal
1076 (setq buf
(read-buffer
1077 (if (eq read-buffer-function
'ido-read-buffer
)
1078 "Next buffer to search (C-j to end): "
1079 "Next buffer to search (RET to end): ")
1082 (add-to-list 'bufs buf
)
1083 (setq ido-ignore-item-temp-list bufs
))
1084 (nreverse (mapcar #'get-buffer bufs
)))
1085 (occur-read-primary-args)))
1086 (occur-1 regexp nlines bufs
))
1088 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1089 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1090 Normally BUFREGEXP matches against each buffer's visited file name,
1091 but if you specify a prefix argument, it matches against the buffer name.
1092 See also `multi-occur'."
1095 (let* ((default (car regexp-history
))
1097 (read-from-minibuffer
1098 (if current-prefix-arg
1099 "List lines in buffers whose names match regexp: "
1100 "List lines in buffers whose filenames match regexp: ")
1105 (if (equal input
"")
1108 (occur-read-primary-args)))
1112 (mapcar (lambda (buf)
1114 (string-match bufregexp
1116 (and (buffer-file-name buf
)
1117 (string-match bufregexp
1118 (buffer-file-name buf
))))
1122 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1123 (unless (and regexp
(not (equal regexp
"")))
1124 (error "Occur doesn't work with the empty regexp"))
1126 (setq buf-name
"*Occur*"))
1128 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1129 (when (buffer-live-p buf
) buf
))
1131 ;; Handle the case where one of the buffers we're searching is the
1132 ;; output buffer. Just rename it.
1133 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1134 (with-current-buffer (get-buffer buf-name
)
1137 ;; Now find or create the output buffer.
1138 ;; If we just renamed that buffer, we will make a new one here.
1139 (setq occur-buf
(get-buffer-create buf-name
))
1141 (with-current-buffer occur-buf
1143 (let ((inhibit-read-only t
)
1144 ;; Don't generate undo entries for creation of the initial contents.
1145 (buffer-undo-list t
))
1147 (let ((count (occur-engine
1148 regexp active-bufs occur-buf
1149 (or nlines list-matching-lines-default-context-lines
)
1150 (if (and case-fold-search search-upper-case
)
1151 (isearch-no-upper-case-p regexp t
)
1153 list-matching-lines-buffer-name-face
1154 nil list-matching-lines-face
1155 (not (eq occur-excluded-properties t
)))))
1156 (let* ((bufcount (length active-bufs
))
1157 (diff (- (length bufs
) bufcount
)))
1158 (message "Searched %d buffer%s%s; %s match%s for `%s'"
1159 bufcount
(if (= bufcount
1) "" "s")
1160 (if (zerop diff
) "" (format " (%d killed)" diff
))
1161 (if (zerop count
) "no" (format "%d" count
))
1162 (if (= count
1) "" "es")
1164 (setq occur-revert-arguments
(list regexp nlines bufs
))
1166 (kill-buffer occur-buf
)
1167 (display-buffer occur-buf
)
1168 (setq next-error-last-buffer occur-buf
)
1169 (setq buffer-read-only t
)
1170 (set-buffer-modified-p nil
)
1171 (run-hooks 'occur-hook
)))))))
1173 (defun occur-engine-add-prefix (lines)
1176 (concat " :" line
"\n"))
1179 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
1180 title-face prefix-face match-face keep-props
)
1181 (with-current-buffer out-buf
1182 (let ((globalcount 0)
1184 ;; Map over all the buffers
1185 (dolist (buf buffers
)
1186 (when (buffer-live-p buf
)
1187 (let ((matches 0) ;; count of matched lines
1188 (lines 1) ;; line count
1195 (inhibit-field-text-motion t
)
1196 (headerpt (with-current-buffer out-buf
(point))))
1197 (with-current-buffer buf
1199 ;; Set CODING only if the current buffer locally
1200 ;; binds buffer-file-coding-system.
1201 (not (local-variable-p 'buffer-file-coding-system
))
1202 (setq coding buffer-file-coding-system
))
1204 (goto-char (point-min)) ;; begin searching in the buffer
1206 (setq origpt
(point))
1207 (when (setq endpt
(re-search-forward regexp nil t
))
1208 (setq matches
(1+ matches
)) ;; increment match count
1209 (setq matchbeg
(match-beginning 0))
1210 (setq lines
(+ lines
(1- (count-lines origpt endpt
))))
1212 (goto-char matchbeg
)
1213 (setq begpt
(line-beginning-position)
1214 endpt
(line-end-position)))
1215 (setq marker
(make-marker))
1216 (set-marker marker matchbeg
)
1218 (if (boundp 'jit-lock-mode
) jit-lock-mode
)
1219 (text-property-not-all begpt endpt
'fontified t
))
1220 (if (fboundp 'jit-lock-fontify-now
)
1221 (jit-lock-fontify-now begpt endpt
)))
1222 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1224 (setq curstring
(buffer-substring begpt endpt
))
1225 (remove-list-of-text-properties
1226 0 (length curstring
) occur-excluded-properties curstring
))
1227 (setq curstring
(buffer-substring-no-properties begpt endpt
)))
1228 ;; Highlight the matches
1229 (let ((len (length curstring
))
1231 (while (and (< start len
)
1232 (string-match regexp curstring start
))
1233 (add-text-properties
1234 (match-beginning 0) (match-end 0)
1238 ;; Use `face' rather than `font-lock-face' here
1239 ;; so as to override faces copied from the buffer.
1240 `(face ,match-face
)))
1242 (setq start
(match-end 0))))
1243 ;; Generate the string to insert for this match
1246 ;; Using 7 digits aligns tabs properly.
1247 (apply #'propertize
(format "%7d:" lines
)
1250 `(font-lock-face prefix-face
))
1251 `(occur-prefix t mouse-face
(highlight)
1252 occur-target
,marker follow-link t
1253 help-echo
"mouse-2: go to this occurrence")))
1254 ;; We don't put `mouse-face' on the newline,
1255 ;; because that loses. And don't put it
1256 ;; on context lines to reduce flicker.
1257 (propertize curstring
'mouse-face
(list 'highlight
)
1258 'occur-target marker
1261 "mouse-2: go to this occurrence")
1262 ;; Add marker at eol, but no mouse props.
1263 (propertize "\n" 'occur-target marker
)))
1266 ;; The simple display style
1268 ;; The complex multi-line display style.
1269 (occur-context-lines out-line nlines keep-props
)
1271 ;; Actually insert the match display data
1272 (with-current-buffer out-buf
1274 (end (progn (insert data
) (point))))
1275 (unless (= nlines
0)
1276 (insert "-------\n")))))
1280 (setq lines
(1+ lines
))
1281 ;; On to the next match...
1283 (goto-char (point-max))))))
1284 (when (not (zerop matches
)) ;; is the count zero?
1285 (setq globalcount
(+ globalcount matches
))
1286 (with-current-buffer out-buf
1287 (goto-char headerpt
)
1290 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1291 matches
(if (= matches
1) "" "es")
1292 regexp
(buffer-name buf
)))
1294 (add-text-properties beg end
1297 `(font-lock-face ,title-face
))
1298 `(occur-title ,buf
))))
1299 (goto-char (point-min)))))))
1301 ;; CODING is buffer-file-coding-system of the first buffer
1302 ;; that locally binds it. Let's use it also for the output
1304 (set-buffer-file-coding-system coding
))
1305 ;; Return the number of matches
1308 ;; Generate context display for occur.
1309 ;; OUT-LINE is the line where the match is.
1310 ;; NLINES and KEEP-PROPS are args to occur-engine.
1311 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1312 ;; then concatenate them all together.
1313 (defun occur-context-lines (out-line nlines keep-props
)
1316 (occur-engine-add-prefix
1317 (nreverse (cdr (occur-accumulate-lines
1318 (- (1+ (abs nlines
))) keep-props
))))
1321 (occur-engine-add-prefix
1322 (cdr (occur-accumulate-lines (1+ nlines
) keep-props
)))))))
1324 ;; It would be nice to use \\[...], but there is no reasonable way
1325 ;; to make that display both SPC and Y.
1326 (defconst query-replace-help
1327 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1328 RET or `q' to exit, Period to replace one match and exit,
1329 Comma to replace but not move point immediately,
1330 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1331 C-w to delete match and recursive edit,
1332 C-l to clear the screen, redisplay, and offer same replacement again,
1333 ! to replace all remaining matches with no more questions,
1334 ^ to move point back to previous match,
1335 E to edit the replacement string"
1336 "Help message while in `query-replace'.")
1338 (defvar query-replace-map
1339 (let ((map (make-sparse-keymap)))
1340 (define-key map
" " 'act
)
1341 (define-key map
"\d" 'skip
)
1342 (define-key map
[delete] 'skip)
1343 (define-key map [backspace] 'skip)
1344 (define-key map "y" 'act)
1345 (define-key map "n" 'skip)
1346 (define-key map "Y" 'act)
1347 (define-key map "N" 'skip)
1348 (define-key map "e" 'edit-replacement)
1349 (define-key map "E" 'edit-replacement)
1350 (define-key map "," 'act-and-show)
1351 (define-key map "q" 'exit)
1352 (define-key map "\r" 'exit)
1353 (define-key map [return] 'exit)
1354 (define-key map "." 'act-and-exit)
1355 (define-key map "\C-r" 'edit)
1356 (define-key map "\C-w" 'delete-and-edit)
1357 (define-key map "\C-l" 'recenter)
1358 (define-key map "!" 'automatic)
1359 (define-key map "^" 'backup)
1360 (define-key map "\C-h" 'help)
1361 (define-key map [f1] 'help)
1362 (define-key map [help] 'help)
1363 (define-key map "?" 'help)
1364 (define-key map "\C-g" 'quit)
1365 (define-key map "\C-]" 'quit)
1366 (define-key map "\e" 'exit-prefix)
1367 (define-key map [escape] 'exit-prefix)
1369 "Keymap that defines the responses to questions in `query-replace'.
1370 The \"bindings\" in this map are not commands; they are answers.
1371 The valid answers include `act', `skip', `act-and-show',
1372 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1373 `automatic', `backup', `exit-prefix', and `help'.")
1375 (defun replace-match-string-symbols (n)
1376 "Process a list (and any sub-lists), expanding certain symbols.
1378 N (match-string N) (where N is a string of digits)
1379 #N (string-to-number (match-string N))
1381 #& (string-to-number (match-string 0))
1384 Note that these symbols must be preceeded by a backslash in order to
1385 type them using Lisp syntax."
1389 (replace-match-string-symbols (car n))) ;Process sub-list
1391 (let ((name (symbol-name (car n))))
1393 ((string-match "^[0-9]+$" name)
1394 (setcar n (list 'match-string (string-to-number name))))
1395 ((string-match "^#[0-9]+$" name)
1396 (setcar n (list 'string-to-number
1398 (string-to-number (substring name 1))))))
1400 (setcar n '(match-string 0)))
1401 ((string= "#&" name)
1402 (setcar n '(string-to-number (match-string 0))))
1404 (setcar n 'replace-count))))))
1407 (defun replace-eval-replacement (expression replace-count)
1408 (let ((replacement (eval expression)))
1409 (if (stringp replacement)
1411 (prin1-to-string replacement t))))
1413 (defun replace-quote (replacement)
1414 "Quote a replacement string.
1415 This just doubles all backslashes in REPLACEMENT and
1416 returns the resulting string. If REPLACEMENT is not
1417 a string, it is first passed through `prin1-to-string'
1418 with the `noescape' argument set.
1420 `match-data' is preserved across the call."
1422 (replace-regexp-in-string "\\\\" "\\\\"
1423 (if (stringp replacement)
1425 (prin1-to-string replacement t))
1428 (defun replace-loop-through-replacements (data replace-count)
1429 ;; DATA is a vector contaning the following values:
1430 ;; 0 next-rotate-count
1432 ;; 2 next-replacement
1434 (if (= (aref data 0) replace-count)
1436 (aset data 0 (+ replace-count (aref data 1)))
1437 (let ((next (cdr (aref data 2))))
1438 (aset data 2 (if (consp next) next (aref data 3))))))
1439 (car (aref data 2)))
1441 (defun replace-match-data (integers reuse &optional new)
1442 "Like `match-data', but markers in REUSE get invalidated.
1443 If NEW is non-nil, it is set and returned instead of fresh data,
1444 but coerced to the correct value of INTEGERS."
1447 (set-match-data new)
1449 (eq (null integers) (markerp (car reuse)))
1451 (match-data integers reuse t)))
1453 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1454 "Make a replacement with `replace-match', editing `\\?'.
1455 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1456 check for `\\?' is made to save time. MATCH-DATA is used for the
1457 replacement. In case editing is done, it is changed to use markers.
1459 The return value is non-nil if there has been no `\\?' or NOEDIT was
1460 passed in. If LITERAL is set, no checking is done, anyway."
1461 (unless (or literal noedit)
1463 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1466 (read-string "Edit replacement string: "
1469 (replace-match "" t t newtext 3)
1470 (1+ (match-beginning 3)))
1473 nil match-data match-data))))
1475 (set-match-data match-data)
1476 (replace-match newtext fixedcase literal)
1479 (defvar replace-search-function 'search-forward
1480 "Function to use when searching for strings to replace.
1481 It is used by `query-replace' and `replace-string', and is called
1482 with three arguments, as if it were `search-forward'.")
1484 (defvar replace-re-search-function 're-search-forward
1485 "Function to use when searching for regexps to replace.
1486 It is used by `query-replace-regexp', `replace-regexp',
1487 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1488 It is called with three arguments, as if it were
1489 `re-search-forward'.")
1491 (defun perform-replace (from-string replacements
1492 query-flag regexp-flag delimited-flag
1493 &optional repeat-count map start end)
1494 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1495 Don't use this in your own program unless you want to query and set the mark
1496 just as `query-replace' does. Instead, write a simple loop like this:
1498 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1499 (replace-match \"foobar\" nil nil))
1501 which will run faster and probably do exactly what you want. Please
1502 see the documentation of `replace-match' to find out how to simulate
1505 This function returns nil if and only if there were no matches to
1506 make, or the user didn't cancel the call."
1507 (or map (setq map query-replace-map))
1508 (and query-flag minibuffer-auto-raise
1509 (raise-frame (window-frame (minibuffer-window))))
1510 (let* ((case-fold-search
1511 (if (and case-fold-search search-upper-case)
1512 (isearch-no-upper-case-p from-string regexp-flag)
1514 (nocasify (not (and case-replace case-fold-search)))
1515 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1518 replace-re-search-function
1519 replace-search-function))
1520 (search-string from-string)
1521 (real-match-data nil) ; The match data for the current match.
1522 (next-replacement nil)
1523 ;; This is non-nil if we know there is nothing for the user
1524 ;; to edit in the replacement.
1529 (nonempty-match nil)
1531 ;; If non-nil, it is marker saying where in the buffer to stop.
1534 ;; Data for the next match. If a cons, it has the same format as
1535 ;; (match-data); otherwise it is t if a match is possible at point.
1541 (substitute-command-keys
1542 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1543 minibuffer-prompt-properties))))
1545 ;; If region is active, in Transient Mark mode, operate on region.
1547 (setq limit (copy-marker (max start end)))
1548 (goto-char (min start end))
1551 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1552 ;; containing a function and its first argument. The function is
1553 ;; called to generate each replacement like this:
1554 ;; (funcall (car replacements) (cdr replacements) replace-count)
1555 ;; It must return a string.
1557 ((stringp replacements)
1558 (setq next-replacement replacements
1560 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1561 (or repeat-count (setq repeat-count 1))
1562 (setq replacements (cons 'replace-loop-through-replacements
1563 (vector repeat-count repeat-count
1564 replacements replacements)))))
1567 (setq search-function 're-search-forward
1568 search-string (concat "\\b"
1569 (if regexp-flag from-string
1570 (regexp-quote from-string))
1572 (when query-replace-lazy-highlight
1573 (setq isearch-lazy-highlight-last-string nil))
1578 ;; Loop finding occurrences that perhaps should be replaced.
1579 (while (and keep-going
1580 (not (or (eobp) (and limit (>= (point) limit))))
1581 ;; Use the next match if it is already known;
1582 ;; otherwise, search for a match after moving forward
1583 ;; one char if progress is required.
1584 (setq real-match-data
1585 (cond ((consp match-again)
1586 (goto-char (nth 1 match-again))
1588 t real-match-data match-again))
1589 ;; MATCH-AGAIN non-nil means accept an
1593 (funcall search-function search-string
1595 ;; For speed, use only integers and
1596 ;; reuse the list used last time.
1597 (replace-match-data t real-match-data)))
1598 ((and (< (1+ (point)) (point-max))
1600 (< (1+ (point)) limit)))
1601 ;; If not accepting adjacent matches,
1602 ;; move one char to the right before
1603 ;; searching again. Undo the motion
1604 ;; if the search fails.
1605 (let ((opoint (point)))
1608 search-function search-string
1615 ;; Record whether the match is nonempty, to avoid an infinite loop
1616 ;; repeatedly matching the same empty string.
1617 (setq nonempty-match
1618 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1620 ;; If the match is empty, record that the next one can't be
1623 ;; Otherwise, if matching a regular expression, do the next
1624 ;; match now, since the replacement for this match may
1625 ;; affect whether the next match is adjacent to this one.
1626 ;; If that match is empty, don't use it.
1629 (or (not regexp-flag)
1630 (and (looking-at search-string)
1631 (let ((match (match-data)))
1632 (and (/= (nth 0 match) (nth 1 match))
1635 ;; Optionally ignore matches that have a read-only property.
1636 (unless (and query-replace-skip-read-only
1637 (text-property-not-all
1638 (nth 0 real-match-data) (nth 1 real-match-data)
1641 ;; Calculate the replacement string, if necessary.
1643 (set-match-data real-match-data)
1644 (setq next-replacement
1645 (funcall (car replacements) (cdr replacements)
1647 (if (not query-flag)
1648 (let ((inhibit-read-only
1649 query-replace-skip-read-only))
1650 (unless (or literal noedit)
1652 (nth 0 real-match-data) (nth 1 real-match-data)
1653 start end search-string
1654 (or delimited-flag regexp-flag) case-fold-search))
1656 (replace-match-maybe-edit
1657 next-replacement nocasify literal
1658 noedit real-match-data)
1659 replace-count (1+ replace-count)))
1661 (let (done replaced key def)
1662 ;; Loop reading commands until one of them sets done,
1663 ;; which means it has finished handling this
1664 ;; occurrence. Any command that sets `done' should
1665 ;; leave behind proper match data for the stack.
1666 ;; Commands not setting `done' need to adjust
1667 ;; `real-match-data'.
1669 (set-match-data real-match-data)
1671 (match-beginning 0) (match-end 0)
1672 start end search-string
1673 (or delimited-flag regexp-flag) case-fold-search)
1674 ;; Bind message-log-max so we don't fill up the message log
1675 ;; with a bunch of identical messages.
1676 (let ((message-log-max nil)
1677 (replacement-presentation
1678 (if query-replace-show-replacement
1680 (set-match-data real-match-data)
1681 (match-substitute-replacement next-replacement
1685 (query-replace-descr from-string)
1686 (query-replace-descr replacement-presentation)))
1687 (setq key (read-event))
1688 ;; Necessary in case something happens during read-event
1689 ;; that clobbers the match data.
1690 (set-match-data real-match-data)
1691 (setq key (vector key))
1692 (setq def (lookup-key map key))
1693 ;; Restore the match data while we process the command.
1694 (cond ((eq def 'help)
1695 (with-output-to-temp-buffer "*Help*"
1697 (concat "Query replacing "
1698 (if regexp-flag "regexp " "")
1699 from-string " with "
1700 next-replacement ".\n\n"
1701 (substitute-command-keys
1702 query-replace-help)))
1703 (with-current-buffer standard-output
1706 (setq keep-going nil)
1710 (let ((elt (pop stack)))
1711 (goto-char (nth 0 elt))
1712 (setq replaced (nth 1 elt)
1717 (message "No previous match")
1718 (ding 'no-terminate)
1723 (replace-match-maybe-edit
1724 next-replacement nocasify literal
1725 noedit real-match-data)
1726 replace-count (1+ replace-count)))
1727 (setq done t replaced t))
1728 ((eq def 'act-and-exit)
1731 (replace-match-maybe-edit
1732 next-replacement nocasify literal
1733 noedit real-match-data)
1734 replace-count (1+ replace-count)))
1735 (setq keep-going nil)
1736 (setq done t replaced t))
1737 ((eq def 'act-and-show)
1740 (replace-match-maybe-edit
1741 next-replacement nocasify literal
1742 noedit real-match-data)
1743 replace-count (1+ replace-count)
1744 real-match-data (replace-match-data
1747 ((eq def 'automatic)
1750 (replace-match-maybe-edit
1751 next-replacement nocasify literal
1752 noedit real-match-data)
1753 replace-count (1+ replace-count)))
1754 (setq done t query-flag nil replaced t))
1760 (let ((opos (point-marker)))
1761 (setq real-match-data (replace-match-data
1764 (goto-char (match-beginning 0))
1766 (save-window-excursion
1769 (set-marker opos nil))
1770 ;; Before we make the replacement,
1771 ;; decide whether the search string
1772 ;; can match again just after this match.
1773 (if (and regexp-flag nonempty-match)
1774 (setq match-again (and (looking-at search-string)
1776 ;; Edit replacement.
1777 ((eq def 'edit-replacement)
1778 (setq real-match-data (replace-match-data
1782 (read-string "Edit replacement string: "
1786 (set-match-data real-match-data)
1788 (replace-match-maybe-edit
1789 next-replacement nocasify literal noedit
1794 ((eq def 'delete-and-edit)
1795 (replace-match "" t t)
1796 (setq real-match-data (replace-match-data
1797 nil real-match-data))
1798 (replace-dehighlight)
1799 (save-excursion (recursive-edit))
1801 ;; Note: we do not need to treat `exit-prefix'
1802 ;; specially here, since we reread
1803 ;; any unrecognized character.
1805 (setq this-command 'mode-exited)
1806 (setq keep-going nil)
1807 (setq unread-command-events
1808 (append (listify-key-sequence key)
1809 unread-command-events))
1811 (when query-replace-lazy-highlight
1812 ;; Force lazy rehighlighting only after replacements
1813 (if (not (memq def '(skip backup)))
1814 (setq isearch-lazy-highlight-last-string nil))))
1815 ;; Record previous position for ^ when we move on.
1816 ;; Change markers to numbers in the match data
1817 ;; since lots of markers slow down editing.
1818 (push (list (point) replaced
1819 ;;; If the replacement has already happened, all we need is the
1820 ;;; current match start and end. We could get this with a trivial
1822 ;;; (save-excursion (goto-char (match-beginning 0))
1823 ;;; (search-forward (match-string 0))
1825 ;;; if we really wanted to avoid manually constructing match data.
1826 ;;; Adding current-buffer is necessary so that match-data calls can
1827 ;;; return markers which are appropriate for editing.
1836 (replace-dehighlight))
1837 (or unread-command-events
1838 (message "Replaced %d occurrence%s"
1840 (if (= replace-count 1) "" "s")))
1841 (and keep-going stack)))
1843 (defvar replace-overlay nil)
1845 (defun replace-highlight (match-beg match-end range-beg range-end
1846 string regexp case-fold)
1847 (if query-replace-highlight
1849 (move-overlay replace-overlay match-beg match-end (current-buffer))
1850 (setq replace-overlay (make-overlay match-beg match-end))
1851 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
1852 (overlay-put replace-overlay 'face 'query-replace)))
1853 (if query-replace-lazy-highlight
1854 (let ((isearch-string string)
1855 (isearch-regexp regexp)
1856 (search-whitespace-regexp nil)
1857 (isearch-case-fold-search case-fold))
1858 (isearch-lazy-highlight-new-loop range-beg range-end))))
1860 (defun replace-dehighlight ()
1861 (when replace-overlay
1862 (delete-overlay replace-overlay))
1863 (when query-replace-lazy-highlight
1864 (lazy-highlight-cleanup lazy-highlight-cleanup)
1865 (setq isearch-lazy-highlight-last-string nil)))
1867 ;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1868 ;;; replace.el ends here