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'."
228 (query-replace-read-args
229 (concat "Query replace"
230 (if current-prefix-arg
" word" "")
231 (if (and transient-mark-mode mark-active
) " in region" ""))
233 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
234 ;; These are done separately here
235 ;; so that command-history will record these expressions
236 ;; rather than the values they had this time.
237 (if (and transient-mark-mode mark-active
)
239 (if (and transient-mark-mode mark-active
)
241 (perform-replace from-string to-string t nil delimited nil nil start end
))
243 (define-key esc-map
"%" 'query-replace
)
245 (defun query-replace-regexp (regexp to-string
&optional delimited start end
)
246 "Replace some things after point matching REGEXP with TO-STRING.
247 As each match is found, the user must type a character saying
248 what to do with it. For directions, type \\[help-command] at that time.
250 In Transient Mark mode, if the mark is active, operate on the contents
251 of the region. Otherwise, operate from point to the end of the buffer.
253 If `query-replace-interactive' is non-nil, the last incremental search
254 regexp is used as REGEXP--you don't have to specify it with the
257 Matching is independent of case if `case-fold-search' is non-nil and
258 REGEXP has no uppercase letters. Replacement transfers the case
259 pattern of the old text to the new text, if `case-replace' and
260 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
261 \(Transferring the case pattern means that if the old text matched is
262 all caps, or capitalized, then its replacement is upcased or
265 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
266 only matches surrounded by word boundaries.
267 Fourth and fifth arg START and END specify the region to operate on.
269 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
270 and `\\=\\N' (where N is a digit) stands for
271 whatever what matched the Nth `\\(...\\)' in REGEXP.
272 `\\?' lets you edit the replacement text in the minibuffer
273 at the given position for each replacement.
275 In interactive calls, the replacement text can contain `\\,'
276 followed by a Lisp expression. Each
277 replacement evaluates that expression to compute the replacement
278 string. Inside of that expression, `\\&' is a string denoting the
279 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
280 for the whole or a partial match converted to a number with
281 `string-to-number', and `\\#' itself for the number of replacements
282 done so far (starting with zero).
284 If the replacement expression is a symbol, write a space after it
285 to terminate it. One space there, if any, will be discarded.
287 When using those Lisp features interactively in the replacement
288 text, TO-STRING is actually made a list instead of a string.
289 Use \\[repeat-complex-command] after this command for details."
292 (query-replace-read-args
293 (concat "Query replace"
294 (if current-prefix-arg
" word" "")
296 (if (and transient-mark-mode mark-active
) " in region" ""))
298 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
299 ;; These are done separately here
300 ;; so that command-history will record these expressions
301 ;; rather than the values they had this time.
302 (if (and transient-mark-mode mark-active
)
304 (if (and transient-mark-mode mark-active
)
306 (perform-replace regexp to-string t t delimited nil nil start end
))
308 (define-key esc-map
[?\C-%
] 'query-replace-regexp
)
310 (defun query-replace-regexp-eval (regexp to-expr
&optional delimited start end
)
311 "Replace some things after point matching REGEXP with the result of TO-EXPR.
313 Interactive use of this function is deprecated in favor of the
314 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
315 using `search-forward-regexp' and `replace-match' is preferred.
317 As each match is found, the user must type a character saying
318 what to do with it. For directions, type \\[help-command] at that time.
320 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
321 reference `replace-count' to get the number of replacements already made.
322 If the result of TO-EXPR is not a string, it is converted to one using
323 `prin1-to-string' with the NOESCAPE argument (which see).
325 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
326 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
327 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
328 Use `\\#&' or `\\#N' if you want a number instead of a string.
329 In interactive use, `\\#' in itself stands for `replace-count'.
331 In Transient Mark mode, if the mark is active, operate on the contents
332 of the region. Otherwise, operate from point to the end of the buffer.
334 If `query-replace-interactive' is non-nil, the last incremental search
335 regexp is used as REGEXP--you don't have to specify it with the
338 Preserves case in each replacement if `case-replace' and `case-fold-search'
339 are non-nil and REGEXP has no uppercase letters.
341 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
342 only matches that are surrounded by word boundaries.
343 Fourth and fifth arg START and END specify the region to operate on."
346 (barf-if-buffer-read-only)
348 ;; Let-bind the history var to disable the "foo -> bar" default.
349 ;; Maybe we shouldn't disable this default, but for now I'll
350 ;; leave it off. --Stef
351 (let ((query-replace-to-history-variable nil
))
352 (query-replace-read-from "Query replace regexp" t
)))
353 (to (list (read-from-minibuffer
354 (format "Query replace regexp %s with eval: "
355 (query-replace-descr from
))
356 nil nil t query-replace-to-history-variable from t
))))
357 ;; We make TO a list because replace-match-string-symbols requires one,
358 ;; and the user might enter a single token.
359 (replace-match-string-symbols to
)
360 (list from
(car to
) current-prefix-arg
361 (if (and transient-mark-mode mark-active
)
363 (if (and transient-mark-mode mark-active
)
365 (perform-replace regexp
(cons 'replace-eval-replacement to-expr
)
366 t
'literal delimited nil nil start end
))
368 (make-obsolete 'query-replace-regexp-eval
369 "for interactive use, use the special `\\,' feature of
370 `query-replace-regexp' instead. Non-interactively, a loop
371 using `search-forward-regexp' and `replace-match' is preferred." "22.1")
373 (defun map-query-replace-regexp (regexp to-strings
&optional n start end
)
374 "Replace some matches for REGEXP with various strings, in rotation.
375 The second argument TO-STRINGS contains the replacement strings, separated
376 by spaces. This command works like `query-replace-regexp' except that
377 each successive replacement uses the next successive replacement string,
378 wrapping around from the last such string to the first.
380 In Transient Mark mode, if the mark is active, operate on the contents
381 of the region. Otherwise, operate from point to the end of the buffer.
383 Non-interactively, TO-STRINGS may be a list of replacement strings.
385 If `query-replace-interactive' is non-nil, the last incremental search
386 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
388 A prefix argument N says to use each replacement string N times
389 before rotating to the next.
390 Fourth and fifth arg START and END specify the region to operate on."
392 (let* ((from (if query-replace-interactive
393 (car regexp-search-ring
)
394 (read-from-minibuffer "Map query replace (regexp): "
396 'query-replace-history nil t
)))
397 (to (read-from-minibuffer
398 (format "Query replace %s with (space-separated strings): "
399 (query-replace-descr from
))
401 'query-replace-history from t
)))
403 (and current-prefix-arg
404 (prefix-numeric-value current-prefix-arg
))
405 (if (and transient-mark-mode mark-active
)
407 (if (and transient-mark-mode mark-active
)
410 (if (listp to-strings
)
411 (setq replacements to-strings
)
412 (while (/= (length to-strings
) 0)
413 (if (string-match " " to-strings
)
416 (list (substring to-strings
0
417 (string-match " " to-strings
))))
418 to-strings
(substring to-strings
419 (1+ (string-match " " to-strings
))))
420 (setq replacements
(append replacements
(list to-strings
))
422 (perform-replace regexp replacements t t nil n nil start end
)))
424 (defun replace-string (from-string to-string
&optional delimited start end
)
425 "Replace occurrences of FROM-STRING with TO-STRING.
426 Preserve case in each match if `case-replace' and `case-fold-search'
427 are non-nil and FROM-STRING has no uppercase letters.
428 \(Preserving case means that if the string matched is all caps, or capitalized,
429 then its replacement is upcased or capitalized.)
431 In Transient Mark mode, if the mark is active, operate on the contents
432 of the region. Otherwise, operate from point to the end of the buffer.
434 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
435 only matches surrounded by word boundaries.
436 Fourth and fifth arg START and END specify the region to operate on.
438 If `query-replace-interactive' is non-nil, the last incremental search
439 string is used as FROM-STRING--you don't have to specify it with the
442 This function is usually the wrong thing to use in a Lisp program.
443 What you probably want is a loop like this:
444 (while (search-forward FROM-STRING nil t)
445 (replace-match TO-STRING nil t))
446 which will run faster and will not set the mark or print anything.
447 \(You may need a more complex loop if FROM-STRING can match the null string
448 and TO-STRING is also null.)"
451 (query-replace-read-args
453 (if current-prefix-arg
" word" "")
455 (if (and transient-mark-mode mark-active
) " in region" ""))
457 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
458 (if (and transient-mark-mode mark-active
)
460 (if (and transient-mark-mode mark-active
)
462 (perform-replace from-string to-string nil nil delimited nil nil start end
))
464 (defun replace-regexp (regexp to-string
&optional delimited start end
)
465 "Replace things after point matching REGEXP with TO-STRING.
466 Preserve case in each match if `case-replace' and `case-fold-search'
467 are non-nil and REGEXP has no uppercase letters.
469 In Transient Mark mode, if the mark is active, operate on the contents
470 of the region. Otherwise, operate from point to the end of the buffer.
472 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
473 only matches surrounded by word boundaries.
474 Fourth and fifth arg START and END specify the region to operate on.
476 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
477 and `\\=\\N' (where N is a digit) stands for
478 whatever what matched the Nth `\\(...\\)' in REGEXP.
479 `\\?' lets you edit the replacement text in the minibuffer
480 at the given position for each replacement.
482 In interactive calls, the replacement text may contain `\\,'
483 followed by a Lisp expression used as part of the replacement
484 text. Inside of that expression, `\\&' is a string denoting the
485 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
486 numeric values from `string-to-number', and `\\#' itself for
487 `replace-count', the number of replacements occurred so far.
489 If your Lisp expression is an identifier and the next letter in
490 the replacement string would be interpreted as part of it, you
491 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
492 for this particular case you may also enter `\\#' in the
493 replacement text directly.
495 When using those Lisp features interactively in the replacement
496 text, TO-STRING is actually made a list instead of a string.
497 Use \\[repeat-complex-command] after this command for details.
499 If `query-replace-interactive' is non-nil, the last incremental search
500 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
502 This function is usually the wrong thing to use in a Lisp program.
503 What you probably want is a loop like this:
504 (while (re-search-forward REGEXP nil t)
505 (replace-match TO-STRING nil nil))
506 which will run faster and will not set the mark or print anything."
509 (query-replace-read-args
511 (if current-prefix-arg
" word" "")
513 (if (and transient-mark-mode mark-active
) " in region" ""))
515 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
516 (if (and transient-mark-mode mark-active
)
518 (if (and transient-mark-mode mark-active
)
520 (perform-replace regexp to-string nil t delimited nil nil start end
))
523 (defvar regexp-history nil
524 "History list for some commands that read regular expressions.
526 Maximum length of the history list is determined by the value
527 of `history-length', which see.")
529 (defun read-regexp (prompt &optional default-value
)
530 "Read regexp as a string using the regexp history and some useful defaults.
531 Prompt for a regular expression with PROMPT (without a colon and
532 space) in the minibuffer. The optional argument DEFAULT-VALUE
533 provides the value to display in the minibuffer prompt that is
534 returned if the user just types RET.
535 Values available via M-n are the string at point, the last isearch
536 regexp, the last isearch string, and the last replacement regexp."
539 (or (funcall (or find-tag-default-function
540 (get major-mode
'find-tag-default-function
)
543 (car regexp-search-ring
)
544 (regexp-quote (or (car search-ring
) ""))
546 query-replace-from-history-variable
))))
547 (defaults (delete-dups (delq nil
(delete "" defaults
))))
548 ;; Don't add automatically the car of defaults for empty input
549 (history-add-new-input nil
)
551 (read-from-minibuffer
553 (format "%s (default %s): " prompt
554 (query-replace-descr default-value
))
555 (format "%s: " prompt
))
556 nil nil nil
'regexp-history defaults t
)))
560 (add-to-history 'regexp-history input
)))))
563 (defalias 'delete-non-matching-lines
'keep-lines
)
564 (defalias 'delete-matching-lines
'flush-lines
)
565 (defalias 'count-matches
'how-many
)
568 (defun keep-lines-read-args (prompt)
569 "Read arguments for `keep-lines' and friends.
570 Prompt for a regexp with PROMPT.
571 Value is a list, (REGEXP)."
572 (list (read-regexp prompt
) nil nil t
))
574 (defun keep-lines (regexp &optional rstart rend interactive
)
575 "Delete all lines except those containing matches for REGEXP.
576 A match split across lines preserves all the lines it lies in.
577 When called from Lisp (and usually interactively as well, see below)
578 applies to all lines starting after point.
580 If REGEXP contains upper case characters (excluding those preceded by `\\')
581 and `search-upper-case' is non-nil, the matching is case-sensitive.
583 Second and third arg RSTART and REND specify the region to operate on.
584 This command operates on (the accessible part of) all lines whose
585 accessible part is entirely contained in the region determined by RSTART
586 and REND. (A newline ending a line counts as part of that line.)
588 Interactively, in Transient Mark mode when the mark is active, operate
589 on all lines whose accessible part is entirely contained in the region.
590 Otherwise, the command applies to all lines starting after point.
591 When calling this function from Lisp, you can pretend that it was
592 called interactively by passing a non-nil INTERACTIVE argument.
594 This function starts looking for the next match from the end of
595 the previous match. Hence, it ignores matches that overlap
596 a previously found match."
600 (barf-if-buffer-read-only)
601 (keep-lines-read-args "Keep lines containing match for regexp")))
604 (goto-char (min rstart rend
))
608 (goto-char (max rstart rend
))
609 (unless (or (bolp) (eobp))
612 (if (and interactive transient-mark-mode mark-active
)
613 (setq rstart
(region-beginning)
615 (goto-char (region-end))
616 (unless (or (bolp) (eobp))
620 rend
(point-max-marker)))
623 (or (bolp) (forward-line 1))
624 (let ((start (point))
626 (if (and case-fold-search search-upper-case
)
627 (isearch-no-upper-case-p regexp t
)
629 (while (< (point) rend
)
630 ;; Start is first char not preserved by previous match.
631 (if (not (re-search-forward regexp rend
'move
))
632 (delete-region start rend
)
633 (let ((end (save-excursion (goto-char (match-beginning 0))
636 ;; Now end is first char preserved by the new match.
638 (delete-region start end
))))
640 (setq start
(save-excursion (forward-line 1) (point)))
641 ;; If the match was empty, avoid matching again at same place.
642 (and (< (point) rend
)
643 (= (match-beginning 0) (match-end 0))
645 (set-marker rend nil
)
649 (defun flush-lines (regexp &optional rstart rend interactive
)
650 "Delete lines containing matches for REGEXP.
651 When called from Lisp (and usually when called interactively as
652 well, see below), applies to the part of the buffer after point.
653 The line point is in is deleted if and only if it contains a
654 match for regexp starting after point.
656 If REGEXP contains upper case characters (excluding those preceded by `\\')
657 and `search-upper-case' is non-nil, the matching is case-sensitive.
659 Second and third arg RSTART and REND specify the region to operate on.
660 Lines partially contained in this region are deleted if and only if
661 they contain a match entirely contained in it.
663 Interactively, in Transient Mark mode when the mark is active, operate
664 on the contents of the region. Otherwise, operate from point to the
665 end of (the accessible portion of) the buffer. When calling this function
666 from Lisp, you can pretend that it was called interactively by passing
667 a non-nil INTERACTIVE argument.
669 If a match is split across lines, all the lines it lies in are deleted.
670 They are deleted _before_ looking for the next match. Hence, a match
671 starting on the same line at which another match ended is ignored."
675 (barf-if-buffer-read-only)
676 (keep-lines-read-args "Flush lines containing match for regexp")))
679 (goto-char (min rstart rend
))
680 (setq rend
(copy-marker (max rstart rend
))))
681 (if (and interactive transient-mark-mode mark-active
)
682 (setq rstart
(region-beginning)
683 rend
(copy-marker (region-end)))
685 rend
(point-max-marker)))
687 (let ((case-fold-search
688 (if (and case-fold-search search-upper-case
)
689 (isearch-no-upper-case-p regexp t
)
692 (while (and (< (point) rend
)
693 (re-search-forward regexp rend t
))
694 (delete-region (save-excursion (goto-char (match-beginning 0))
697 (progn (forward-line 1) (point))))))
698 (set-marker rend nil
)
702 (defun how-many (regexp &optional rstart rend interactive
)
703 "Print and return number of matches for REGEXP following point.
704 When called from Lisp and INTERACTIVE is omitted or nil, just return
705 the number, do not print it; if INTERACTIVE is t, the function behaves
706 in all respects as if it had been called interactively.
708 If REGEXP contains upper case characters (excluding those preceded by `\\')
709 and `search-upper-case' is non-nil, the matching is case-sensitive.
711 Second and third arg RSTART and REND specify the region to operate on.
713 Interactively, in Transient Mark mode when the mark is active, operate
714 on the contents of the region. Otherwise, operate from point to the
715 end of (the accessible portion of) the buffer.
717 This function starts looking for the next match from the end of
718 the previous match. Hence, it ignores matches that overlap
719 a previously found match."
722 (keep-lines-read-args "How many matches for regexp"))
726 (goto-char (min rstart rend
))
727 (setq rend
(max rstart rend
)))
728 (if (and interactive transient-mark-mode mark-active
)
729 (setq rstart
(region-beginning)
737 (if (and case-fold-search search-upper-case
)
738 (isearch-no-upper-case-p regexp t
)
740 (while (and (< (point) rend
)
741 (progn (setq opoint
(point))
742 (re-search-forward regexp rend t
)))
743 (if (= opoint
(point))
745 (setq count
(1+ count
))))
746 (when interactive
(message "%d occurrence%s"
748 (if (= count
1) "" "s")))
752 (defvar occur-mode-map
753 (let ((map (make-sparse-keymap)))
754 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
755 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
756 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
757 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
758 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
759 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
760 (define-key map
"\M-n" 'occur-next
)
761 (define-key map
"\M-p" 'occur-prev
)
762 (define-key map
"r" 'occur-rename-buffer
)
763 (define-key map
"c" 'clone-buffer
)
764 (define-key map
"g" 'revert-buffer
)
765 (define-key map
"q" 'quit-window
)
766 (define-key map
"z" 'kill-this-buffer
)
767 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
768 (define-key map
[menu-bar
] (make-sparse-keymap))
769 (define-key map
[menu-bar occur
]
771 (define-key map
[next-error-follow-minor-mode
]
772 (menu-bar-make-mm-toggle next-error-follow-minor-mode
773 "Auto Occurrence Display"
774 "Display another occurrence when moving the cursor"))
775 (define-key map
[separator-1
] '("--"))
776 (define-key map
[kill-this-buffer
]
777 '(menu-item "Kill occur buffer" kill-this-buffer
778 :help
"Kill the current *Occur* buffer"))
779 (define-key map
[quit-window
]
780 '(menu-item "Quit occur window" quit-window
781 :help
"Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
782 (define-key map
[revert-buffer
]
783 '(menu-item "Revert occur buffer" revert-buffer
784 :help
"Replace the text in the *Occur* buffer with the results of rerunning occur"))
785 (define-key map
[clone-buffer
]
786 '(menu-item "Clone occur buffer" clone-buffer
787 :help
"Create and return a twin copy of the current *Occur* buffer"))
788 (define-key map
[occur-rename-buffer
]
789 '(menu-item "Rename occur buffer" occur-rename-buffer
790 :help
"Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
791 (define-key map
[separator-2
] '("--"))
792 (define-key map
[occur-mode-goto-occurrence-other-window
]
793 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
794 :help
"Go to the occurrence the current line describes, in another window"))
795 (define-key map
[occur-mode-goto-occurrence
]
796 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
797 :help
"Go to the occurrence the current line describes"))
798 (define-key map
[occur-mode-display-occurrence
]
799 '(menu-item "Display Occurrence" occur-mode-display-occurrence
800 :help
"Display in another window the occurrence the current line describes"))
801 (define-key map
[occur-next
]
802 '(menu-item "Move to next match" occur-next
803 :help
"Move to the Nth (default 1) next match in an Occur mode buffer"))
804 (define-key map
[occur-prev
]
805 '(menu-item "Move to previous match" occur-prev
806 :help
"Move to the Nth (default 1) previous match in an Occur mode buffer"))
808 "Keymap for `occur-mode'.")
810 (defvar occur-revert-arguments nil
811 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
812 See `occur-revert-function'.")
814 (defcustom occur-mode-hook
'(turn-on-font-lock)
815 "Hook run when entering Occur mode."
819 (defcustom occur-hook nil
820 "Hook run by Occur when there are any matches."
824 (defcustom occur-mode-find-occurrence-hook nil
825 "Hook run by Occur after locating an occurrence.
826 This will be called with the cursor position at the occurrence. An application
827 for this is to reveal context in an outline-mode when the occurrence is hidden."
831 (put 'occur-mode
'mode-class
'special
)
833 "Major mode for output from \\[occur].
834 \\<occur-mode-map>Move point to one of the items in this buffer, then use
835 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
836 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
840 (kill-all-local-variables)
841 (use-local-map occur-mode-map
)
842 (setq major-mode
'occur-mode
)
843 (setq mode-name
"Occur")
844 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
845 (make-local-variable 'occur-revert-arguments
)
846 (add-hook 'change-major-mode-hook
'font-lock-defontify nil t
)
847 (setq next-error-function
'occur-next-error
)
848 (run-mode-hooks 'occur-mode-hook
))
850 (defun occur-revert-function (ignore1 ignore2
)
851 "Handle `revert-buffer' for Occur mode buffers."
852 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
854 (defun occur-mode-find-occurrence ()
855 (let ((pos (get-text-property (point) 'occur-target
)))
857 (error "No occurrence on this line"))
858 (unless (buffer-live-p (marker-buffer pos
))
859 (error "Buffer for this occurrence was killed"))
862 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
863 (defun occur-mode-goto-occurrence (&optional event
)
864 "Go to the occurrence the current line describes."
865 (interactive (list last-nonmenu-event
))
868 ;; Actually `event-end' works correctly with a nil argument as
869 ;; well, so we could dispense with this test, but let's not
870 ;; rely on this undocumented behavior.
871 (occur-mode-find-occurrence)
872 (with-current-buffer (window-buffer (posn-window (event-end event
)))
874 (goto-char (posn-point (event-end event
)))
875 (occur-mode-find-occurrence)))))
876 same-window-buffer-names
878 (pop-to-buffer (marker-buffer pos
))
880 (run-hooks 'occur-mode-find-occurrence-hook
)))
882 (defun occur-mode-goto-occurrence-other-window ()
883 "Go to the occurrence the current line describes, in another window."
885 (let ((pos (occur-mode-find-occurrence)))
886 (switch-to-buffer-other-window (marker-buffer pos
))
888 (run-hooks 'occur-mode-find-occurrence-hook
)))
890 (defun occur-mode-display-occurrence ()
891 "Display in another window the occurrence the current line describes."
893 (let ((pos (occur-mode-find-occurrence))
895 ;; Bind these to ensure `display-buffer' puts it in another window.
896 same-window-buffer-names
898 (setq window
(display-buffer (marker-buffer pos
)))
899 ;; This is the way to set point in the proper window.
900 (save-selected-window
901 (select-window window
)
903 (run-hooks 'occur-mode-find-occurrence-hook
))))
905 (defun occur-find-match (n search message
)
906 (if (not n
) (setq n
1))
909 (setq r
(funcall search
(point) 'occur-match
))
911 (get-text-property r
'occur-match
)
912 (setq r
(funcall search r
'occur-match
)))
918 (defun occur-next (&optional n
)
919 "Move to the Nth (default 1) next match in an Occur mode buffer."
921 (occur-find-match n
#'next-single-property-change
"No more matches"))
923 (defun occur-prev (&optional n
)
924 "Move to the Nth (default 1) previous match in an Occur mode buffer."
926 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
928 (defun occur-next-error (&optional argp reset
)
929 "Move to the Nth (default 1) next match in an Occur mode buffer.
930 Compatibility function for \\[next-error] invocations."
932 ;; we need to run occur-find-match from within the Occur buffer
934 ;; Choose the buffer and make it current.
935 (if (next-error-buffer-p (current-buffer))
937 (next-error-find-buffer nil nil
939 (eq major-mode
'occur-mode
))))
941 (goto-char (cond (reset (point-min))
942 ((< argp
0) (line-beginning-position))
943 ((> argp
0) (line-end-position))
948 #'previous-single-property-change
949 #'next-single-property-change
)
951 ;; In case the *Occur* buffer is visible in a nonselected window.
952 (let ((win (get-buffer-window (current-buffer) t
)))
953 (if win
(set-window-point win
(point))))
954 (occur-mode-goto-occurrence)))
957 '((((class color
) (min-colors 88) (background light
))
958 :background
"yellow1")
959 (((class color
) (min-colors 88) (background dark
))
960 :background
"RoyalBlue3")
961 (((class color
) (min-colors 8) (background light
))
962 :background
"yellow" :foreground
"black")
963 (((class color
) (min-colors 8) (background dark
))
964 :background
"blue" :foreground
"white")
965 (((type tty
) (class mono
))
967 (t :background
"gray"))
968 "Face used to highlight matches permanently."
972 (defcustom list-matching-lines-default-context-lines
0
973 "*Default number of context lines included around `list-matching-lines' matches.
974 A negative number means to include that many lines before the match.
975 A positive number means to include that many lines both before and after."
979 (defalias 'list-matching-lines
'occur
)
981 (defcustom list-matching-lines-face
'match
982 "*Face used by \\[list-matching-lines] to show the text that matches.
983 If the value is nil, don't highlight the matching portions specially."
987 (defcustom list-matching-lines-buffer-name-face
'underline
988 "*Face used by \\[list-matching-lines] to show the names of buffers.
989 If the value is nil, don't highlight the buffer names specially."
993 (defcustom occur-excluded-properties
994 '(read-only invisible intangible field mouse-face help-echo local-map keymap
995 yank-handler follow-link
)
996 "*Text properties to discard when copying lines to the *Occur* buffer.
997 The value should be a list of text properties to discard or t,
998 which means to discard all text properties."
999 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
1003 (defun occur-accumulate-lines (count &optional keep-props
)
1005 (let ((forwardp (> count
0))
1007 (while (not (or (zerop count
)
1011 (setq count
(+ count
(if forwardp -
1 1)))
1012 (setq beg
(line-beginning-position)
1013 end
(line-end-position))
1014 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
1015 (text-property-not-all beg end
'fontified t
))
1016 (if (fboundp 'jit-lock-fontify-now
)
1017 (jit-lock-fontify-now beg end
)))
1019 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1020 (let ((str (buffer-substring beg end
)))
1021 (remove-list-of-text-properties
1022 0 (length str
) occur-excluded-properties str
)
1024 (buffer-substring-no-properties beg end
))
1026 (forward-line (if forwardp
1 -
1)))
1027 (nreverse result
))))
1029 (defun occur-read-primary-args ()
1030 (list (read-regexp "List lines matching regexp"
1031 (car regexp-history
))
1032 (when current-prefix-arg
1033 (prefix-numeric-value current-prefix-arg
))))
1035 (defun occur-rename-buffer (&optional unique-p interactive-p
)
1036 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1037 Here `original-buffer-name' is the buffer name were Occur was originally run.
1038 When given the prefix argument, or called non-interactively, the renaming
1039 will not clobber the existing buffer(s) of that name, but use
1040 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1041 if you always want a separate *Occur* buffer for each buffer where you
1043 (interactive "P\np")
1044 (with-current-buffer
1045 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
1046 (rename-buffer (concat "*Occur: "
1047 (mapconcat #'buffer-name
1048 (car (cddr occur-revert-arguments
)) "/")
1050 (or unique-p
(not interactive-p
)))))
1052 (defun occur (regexp &optional nlines
)
1053 "Show all lines in the current buffer containing a match for REGEXP.
1054 This function can not handle matches that span more than one line.
1056 Each line is displayed with NLINES lines before and after, or -NLINES
1057 before if NLINES is negative.
1058 NLINES defaults to `list-matching-lines-default-context-lines'.
1059 Interactively it is the prefix arg.
1061 The lines are shown in a buffer named `*Occur*'.
1062 It serves as a menu to find any of the occurrences in this buffer.
1063 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1065 If REGEXP contains upper case characters (excluding those preceded by `\\')
1066 and `search-upper-case' is non-nil, the matching is case-sensitive."
1067 (interactive (occur-read-primary-args))
1068 (occur-1 regexp nlines
(list (current-buffer))))
1070 (defun multi-occur (bufs regexp
&optional nlines
)
1071 "Show all lines in buffers BUFS containing a match for REGEXP.
1072 This function acts on multiple buffers; otherwise, it is exactly like
1073 `occur'. When you invoke this command interactively, you must specify
1074 the buffer names that you want, one by one."
1077 (let* ((bufs (list (read-buffer "First buffer to search: "
1078 (current-buffer) t
)))
1080 (ido-ignore-item-temp-list bufs
))
1081 (while (not (string-equal
1082 (setq buf
(read-buffer
1083 (if (eq read-buffer-function
'ido-read-buffer
)
1084 "Next buffer to search (C-j to end): "
1085 "Next buffer to search (RET to end): ")
1088 (add-to-list 'bufs buf
)
1089 (setq ido-ignore-item-temp-list bufs
))
1090 (nreverse (mapcar #'get-buffer bufs
)))
1091 (occur-read-primary-args)))
1092 (occur-1 regexp nlines bufs
))
1094 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1095 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1096 Normally BUFREGEXP matches against each buffer's visited file name,
1097 but if you specify a prefix argument, it matches against the buffer name.
1098 See also `multi-occur'."
1101 (let* ((default (car regexp-history
))
1103 (read-from-minibuffer
1104 (if current-prefix-arg
1105 "List lines in buffers whose names match regexp: "
1106 "List lines in buffers whose filenames match regexp: ")
1111 (if (equal input
"")
1114 (occur-read-primary-args)))
1118 (mapcar (lambda (buf)
1120 (string-match bufregexp
1122 (and (buffer-file-name buf
)
1123 (string-match bufregexp
1124 (buffer-file-name buf
))))
1128 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1129 (unless (and regexp
(not (equal regexp
"")))
1130 (error "Occur doesn't work with the empty regexp"))
1132 (setq buf-name
"*Occur*"))
1134 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1135 (when (buffer-live-p buf
) buf
))
1137 ;; Handle the case where one of the buffers we're searching is the
1138 ;; output buffer. Just rename it.
1139 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1140 (with-current-buffer (get-buffer buf-name
)
1143 ;; Now find or create the output buffer.
1144 ;; If we just renamed that buffer, we will make a new one here.
1145 (setq occur-buf
(get-buffer-create buf-name
))
1147 (with-current-buffer occur-buf
1149 (let ((inhibit-read-only t
)
1150 ;; Don't generate undo entries for creation of the initial contents.
1151 (buffer-undo-list t
))
1153 (let ((count (occur-engine
1154 regexp active-bufs occur-buf
1155 (or nlines list-matching-lines-default-context-lines
)
1156 (if (and case-fold-search search-upper-case
)
1157 (isearch-no-upper-case-p regexp t
)
1159 list-matching-lines-buffer-name-face
1160 nil list-matching-lines-face
1161 (not (eq occur-excluded-properties t
)))))
1162 (let* ((bufcount (length active-bufs
))
1163 (diff (- (length bufs
) bufcount
)))
1164 (message "Searched %d buffer%s%s; %s match%s for `%s'"
1165 bufcount
(if (= bufcount
1) "" "s")
1166 (if (zerop diff
) "" (format " (%d killed)" diff
))
1167 (if (zerop count
) "no" (format "%d" count
))
1168 (if (= count
1) "" "es")
1170 (setq occur-revert-arguments
(list regexp nlines bufs
))
1172 (kill-buffer occur-buf
)
1173 (display-buffer occur-buf
)
1174 (setq next-error-last-buffer occur-buf
)
1175 (setq buffer-read-only t
)
1176 (set-buffer-modified-p nil
)
1177 (run-hooks 'occur-hook
)))))))
1179 (defun occur-engine-add-prefix (lines)
1182 (concat " :" line
"\n"))
1185 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
1186 title-face prefix-face match-face keep-props
)
1187 (with-current-buffer out-buf
1188 (let ((globalcount 0)
1190 ;; Map over all the buffers
1191 (dolist (buf buffers
)
1192 (when (buffer-live-p buf
)
1193 (let ((matches 0) ;; count of matched lines
1194 (lines 1) ;; line count
1201 (inhibit-field-text-motion t
)
1202 (headerpt (with-current-buffer out-buf
(point))))
1203 (with-current-buffer buf
1205 ;; Set CODING only if the current buffer locally
1206 ;; binds buffer-file-coding-system.
1207 (not (local-variable-p 'buffer-file-coding-system
))
1208 (setq coding buffer-file-coding-system
))
1210 (goto-char (point-min)) ;; begin searching in the buffer
1212 (setq origpt
(point))
1213 (when (setq endpt
(re-search-forward regexp nil t
))
1214 (setq matches
(1+ matches
)) ;; increment match count
1215 (setq matchbeg
(match-beginning 0))
1216 (setq lines
(+ lines
(1- (count-lines origpt endpt
))))
1218 (goto-char matchbeg
)
1219 (setq begpt
(line-beginning-position)
1220 endpt
(line-end-position)))
1221 (setq marker
(make-marker))
1222 (set-marker marker matchbeg
)
1224 (if (boundp 'jit-lock-mode
) jit-lock-mode
)
1225 (text-property-not-all begpt endpt
'fontified t
))
1226 (if (fboundp 'jit-lock-fontify-now
)
1227 (jit-lock-fontify-now begpt endpt
)))
1228 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1230 (setq curstring
(buffer-substring begpt endpt
))
1231 (remove-list-of-text-properties
1232 0 (length curstring
) occur-excluded-properties curstring
))
1233 (setq curstring
(buffer-substring-no-properties begpt endpt
)))
1234 ;; Highlight the matches
1235 (let ((len (length curstring
))
1237 (while (and (< start len
)
1238 (string-match regexp curstring start
))
1239 (add-text-properties
1240 (match-beginning 0) (match-end 0)
1244 ;; Use `face' rather than `font-lock-face' here
1245 ;; so as to override faces copied from the buffer.
1246 `(face ,match-face
)))
1248 (setq start
(match-end 0))))
1249 ;; Generate the string to insert for this match
1252 ;; Using 7 digits aligns tabs properly.
1253 (apply #'propertize
(format "%7d:" lines
)
1256 `(font-lock-face prefix-face
))
1257 `(occur-prefix t mouse-face
(highlight)
1258 occur-target
,marker follow-link t
1259 help-echo
"mouse-2: go to this occurrence")))
1260 ;; We don't put `mouse-face' on the newline,
1261 ;; because that loses. And don't put it
1262 ;; on context lines to reduce flicker.
1263 (propertize curstring
'mouse-face
(list 'highlight
)
1264 'occur-target marker
1267 "mouse-2: go to this occurrence")
1268 ;; Add marker at eol, but no mouse props.
1269 (propertize "\n" 'occur-target marker
)))
1272 ;; The simple display style
1274 ;; The complex multi-line display style.
1275 (occur-context-lines out-line nlines keep-props
)
1277 ;; Actually insert the match display data
1278 (with-current-buffer out-buf
1280 (end (progn (insert data
) (point))))
1281 (unless (= nlines
0)
1282 (insert "-------\n")))))
1286 (setq lines
(1+ lines
))
1287 ;; On to the next match...
1289 (goto-char (point-max))))))
1290 (when (not (zerop matches
)) ;; is the count zero?
1291 (setq globalcount
(+ globalcount matches
))
1292 (with-current-buffer out-buf
1293 (goto-char headerpt
)
1296 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1297 matches
(if (= matches
1) "" "es")
1298 regexp
(buffer-name buf
)))
1300 (add-text-properties beg end
1303 `(font-lock-face ,title-face
))
1304 `(occur-title ,buf
))))
1305 (goto-char (point-min)))))))
1307 ;; CODING is buffer-file-coding-system of the first buffer
1308 ;; that locally binds it. Let's use it also for the output
1310 (set-buffer-file-coding-system coding
))
1311 ;; Return the number of matches
1314 ;; Generate context display for occur.
1315 ;; OUT-LINE is the line where the match is.
1316 ;; NLINES and KEEP-PROPS are args to occur-engine.
1317 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1318 ;; then concatenate them all together.
1319 (defun occur-context-lines (out-line nlines keep-props
)
1322 (occur-engine-add-prefix
1323 (nreverse (cdr (occur-accumulate-lines
1324 (- (1+ (abs nlines
))) keep-props
))))
1327 (occur-engine-add-prefix
1328 (cdr (occur-accumulate-lines (1+ nlines
) keep-props
)))))))
1330 ;; It would be nice to use \\[...], but there is no reasonable way
1331 ;; to make that display both SPC and Y.
1332 (defconst query-replace-help
1333 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1334 RET or `q' to exit, Period to replace one match and exit,
1335 Comma to replace but not move point immediately,
1336 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1337 C-w to delete match and recursive edit,
1338 C-l to clear the screen, redisplay, and offer same replacement again,
1339 ! to replace all remaining matches with no more questions,
1340 ^ to move point back to previous match,
1341 E to edit the replacement string"
1342 "Help message while in `query-replace'.")
1344 (defvar query-replace-map
1345 (let ((map (make-sparse-keymap)))
1346 (define-key map
" " 'act
)
1347 (define-key map
"\d" 'skip
)
1348 (define-key map
[delete] 'skip)
1349 (define-key map [backspace] 'skip)
1350 (define-key map "y" 'act)
1351 (define-key map "n" 'skip)
1352 (define-key map "Y" 'act)
1353 (define-key map "N" 'skip)
1354 (define-key map "e" 'edit-replacement)
1355 (define-key map "E" 'edit-replacement)
1356 (define-key map "," 'act-and-show)
1357 (define-key map "q" 'exit)
1358 (define-key map "\r" 'exit)
1359 (define-key map [return] 'exit)
1360 (define-key map "." 'act-and-exit)
1361 (define-key map "\C-r" 'edit)
1362 (define-key map "\C-w" 'delete-and-edit)
1363 (define-key map "\C-l" 'recenter)
1364 (define-key map "!" 'automatic)
1365 (define-key map "^" 'backup)
1366 (define-key map "\C-h" 'help)
1367 (define-key map [f1] 'help)
1368 (define-key map [help] 'help)
1369 (define-key map "?" 'help)
1370 (define-key map "\C-g" 'quit)
1371 (define-key map "\C-]" 'quit)
1372 (define-key map "\e" 'exit-prefix)
1373 (define-key map [escape] 'exit-prefix)
1375 "Keymap that defines the responses to questions in `query-replace'.
1376 The \"bindings\" in this map are not commands; they are answers.
1377 The valid answers include `act', `skip', `act-and-show',
1378 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1379 `automatic', `backup', `exit-prefix', and `help'.")
1381 (defvar multi-query-replace-map
1382 (let ((map (make-sparse-keymap)))
1383 (set-keymap-parent map query-replace-map)
1384 (define-key map "Y" 'automatic-all)
1385 (define-key map "N" 'exit-current)
1387 "Keymap that defines additional bindings for multi-buffer replacements.
1388 It extends its parent map `query-replace-map' with new bindings to
1389 operate on a set of buffers/files. The difference with its parent map
1390 is the additional answers `automatic-all' to replace all remaining
1391 matches in all remaining buffers with no more questions, and
1392 `exit-current' to skip remaining matches in the current buffer
1393 and to continue with the next buffer in the sequence.")
1395 (defun replace-match-string-symbols (n)
1396 "Process a list (and any sub-lists), expanding certain symbols.
1398 N (match-string N) (where N is a string of digits)
1399 #N (string-to-number (match-string N))
1401 #& (string-to-number (match-string 0))
1404 Note that these symbols must be preceeded by a backslash in order to
1405 type them using Lisp syntax."
1409 (replace-match-string-symbols (car n))) ;Process sub-list
1411 (let ((name (symbol-name (car n))))
1413 ((string-match "^[0-9]+$" name)
1414 (setcar n (list 'match-string (string-to-number name))))
1415 ((string-match "^#[0-9]+$" name)
1416 (setcar n (list 'string-to-number
1418 (string-to-number (substring name 1))))))
1420 (setcar n '(match-string 0)))
1421 ((string= "#&" name)
1422 (setcar n '(string-to-number (match-string 0))))
1424 (setcar n 'replace-count))))))
1427 (defun replace-eval-replacement (expression replace-count)
1428 (let ((replacement (eval expression)))
1429 (if (stringp replacement)
1431 (prin1-to-string replacement t))))
1433 (defun replace-quote (replacement)
1434 "Quote a replacement string.
1435 This just doubles all backslashes in REPLACEMENT and
1436 returns the resulting string. If REPLACEMENT is not
1437 a string, it is first passed through `prin1-to-string'
1438 with the `noescape' argument set.
1440 `match-data' is preserved across the call."
1442 (replace-regexp-in-string "\\\\" "\\\\"
1443 (if (stringp replacement)
1445 (prin1-to-string replacement t))
1448 (defun replace-loop-through-replacements (data replace-count)
1449 ;; DATA is a vector contaning the following values:
1450 ;; 0 next-rotate-count
1452 ;; 2 next-replacement
1454 (if (= (aref data 0) replace-count)
1456 (aset data 0 (+ replace-count (aref data 1)))
1457 (let ((next (cdr (aref data 2))))
1458 (aset data 2 (if (consp next) next (aref data 3))))))
1459 (car (aref data 2)))
1461 (defun replace-match-data (integers reuse &optional new)
1462 "Like `match-data', but markers in REUSE get invalidated.
1463 If NEW is non-nil, it is set and returned instead of fresh data,
1464 but coerced to the correct value of INTEGERS."
1467 (set-match-data new)
1469 (eq (null integers) (markerp (car reuse)))
1471 (match-data integers reuse t)))
1473 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1474 "Make a replacement with `replace-match', editing `\\?'.
1475 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1476 check for `\\?' is made to save time. MATCH-DATA is used for the
1477 replacement. In case editing is done, it is changed to use markers.
1479 The return value is non-nil if there has been no `\\?' or NOEDIT was
1480 passed in. If LITERAL is set, no checking is done, anyway."
1481 (unless (or literal noedit)
1483 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1486 (read-string "Edit replacement string: "
1489 (replace-match "" t t newtext 3)
1490 (1+ (match-beginning 3)))
1493 nil match-data match-data))))
1495 (set-match-data match-data)
1496 (replace-match newtext fixedcase literal)
1499 (defvar replace-search-function 'search-forward
1500 "Function to use when searching for strings to replace.
1501 It is used by `query-replace' and `replace-string', and is called
1502 with three arguments, as if it were `search-forward'.")
1504 (defvar replace-re-search-function 're-search-forward
1505 "Function to use when searching for regexps to replace.
1506 It is used by `query-replace-regexp', `replace-regexp',
1507 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1508 It is called with three arguments, as if it were
1509 `re-search-forward'.")
1511 (defun perform-replace (from-string replacements
1512 query-flag regexp-flag delimited-flag
1513 &optional repeat-count map start end)
1514 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1515 Don't use this in your own program unless you want to query and set the mark
1516 just as `query-replace' does. Instead, write a simple loop like this:
1518 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1519 (replace-match \"foobar\" nil nil))
1521 which will run faster and probably do exactly what you want. Please
1522 see the documentation of `replace-match' to find out how to simulate
1525 This function returns nil if and only if there were no matches to
1526 make, or the user didn't cancel the call."
1527 (or map (setq map query-replace-map))
1528 (and query-flag minibuffer-auto-raise
1529 (raise-frame (window-frame (minibuffer-window))))
1530 (let* ((case-fold-search
1531 (if (and case-fold-search search-upper-case)
1532 (isearch-no-upper-case-p from-string regexp-flag)
1534 (nocasify (not (and case-replace case-fold-search)))
1535 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1538 replace-re-search-function
1539 replace-search-function))
1540 (search-string from-string)
1541 (real-match-data nil) ; The match data for the current match.
1542 (next-replacement nil)
1543 ;; This is non-nil if we know there is nothing for the user
1544 ;; to edit in the replacement.
1549 (nonempty-match nil)
1552 ;; If non-nil, it is marker saying where in the buffer to stop.
1555 ;; Data for the next match. If a cons, it has the same format as
1556 ;; (match-data); otherwise it is t if a match is possible at point.
1562 (substitute-command-keys
1563 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1564 minibuffer-prompt-properties))))
1566 ;; If region is active, in Transient Mark mode, operate on region.
1568 (setq limit (copy-marker (max start end)))
1569 (goto-char (min start end))
1572 ;; If last typed key in previous call of multi-buffer perform-replace
1573 ;; was `automatic-all', don't ask more questions in next files
1574 (when (eq (lookup-key map (vector last-input-char)) 'automatic-all)
1575 (setq query-flag nil multi-buffer t))
1577 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1578 ;; containing a function and its first argument. The function is
1579 ;; called to generate each replacement like this:
1580 ;; (funcall (car replacements) (cdr replacements) replace-count)
1581 ;; It must return a string.
1583 ((stringp replacements)
1584 (setq next-replacement replacements
1586 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1587 (or repeat-count (setq repeat-count 1))
1588 (setq replacements (cons 'replace-loop-through-replacements
1589 (vector repeat-count repeat-count
1590 replacements replacements)))))
1593 (setq search-function 're-search-forward
1594 search-string (concat "\\b"
1595 (if regexp-flag from-string
1596 (regexp-quote from-string))
1598 (when query-replace-lazy-highlight
1599 (setq isearch-lazy-highlight-last-string nil))
1604 ;; Loop finding occurrences that perhaps should be replaced.
1605 (while (and keep-going
1606 (not (or (eobp) (and limit (>= (point) limit))))
1607 ;; Use the next match if it is already known;
1608 ;; otherwise, search for a match after moving forward
1609 ;; one char if progress is required.
1610 (setq real-match-data
1611 (cond ((consp match-again)
1612 (goto-char (nth 1 match-again))
1614 t real-match-data match-again))
1615 ;; MATCH-AGAIN non-nil means accept an
1619 (funcall search-function search-string
1621 ;; For speed, use only integers and
1622 ;; reuse the list used last time.
1623 (replace-match-data t real-match-data)))
1624 ((and (< (1+ (point)) (point-max))
1626 (< (1+ (point)) limit)))
1627 ;; If not accepting adjacent matches,
1628 ;; move one char to the right before
1629 ;; searching again. Undo the motion
1630 ;; if the search fails.
1631 (let ((opoint (point)))
1634 search-function search-string
1641 ;; Record whether the match is nonempty, to avoid an infinite loop
1642 ;; repeatedly matching the same empty string.
1643 (setq nonempty-match
1644 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1646 ;; If the match is empty, record that the next one can't be
1649 ;; Otherwise, if matching a regular expression, do the next
1650 ;; match now, since the replacement for this match may
1651 ;; affect whether the next match is adjacent to this one.
1652 ;; If that match is empty, don't use it.
1655 (or (not regexp-flag)
1656 (and (looking-at search-string)
1657 (let ((match (match-data)))
1658 (and (/= (nth 0 match) (nth 1 match))
1661 ;; Optionally ignore matches that have a read-only property.
1662 (unless (and query-replace-skip-read-only
1663 (text-property-not-all
1664 (nth 0 real-match-data) (nth 1 real-match-data)
1667 ;; Calculate the replacement string, if necessary.
1669 (set-match-data real-match-data)
1670 (setq next-replacement
1671 (funcall (car replacements) (cdr replacements)
1673 (if (not query-flag)
1675 (unless (or literal noedit)
1677 (nth 0 real-match-data) (nth 1 real-match-data)
1678 start end search-string
1679 (or delimited-flag regexp-flag) case-fold-search))
1681 (replace-match-maybe-edit
1682 next-replacement nocasify literal
1683 noedit real-match-data)
1684 replace-count (1+ replace-count)))
1686 (let (done replaced key def)
1687 ;; Loop reading commands until one of them sets done,
1688 ;; which means it has finished handling this
1689 ;; occurrence. Any command that sets `done' should
1690 ;; leave behind proper match data for the stack.
1691 ;; Commands not setting `done' need to adjust
1692 ;; `real-match-data'.
1694 (set-match-data real-match-data)
1696 (match-beginning 0) (match-end 0)
1697 start end search-string
1698 (or delimited-flag regexp-flag) case-fold-search)
1699 ;; Bind message-log-max so we don't fill up the message log
1700 ;; with a bunch of identical messages.
1701 (let ((message-log-max nil)
1702 (replacement-presentation
1703 (if query-replace-show-replacement
1705 (set-match-data real-match-data)
1706 (match-substitute-replacement next-replacement
1710 (query-replace-descr from-string)
1711 (query-replace-descr replacement-presentation)))
1712 (setq key (read-event))
1713 ;; Necessary in case something happens during read-event
1714 ;; that clobbers the match data.
1715 (set-match-data real-match-data)
1716 (setq key (vector key))
1717 (setq def (lookup-key map key))
1718 ;; Restore the match data while we process the command.
1719 (cond ((eq def 'help)
1720 (with-output-to-temp-buffer "*Help*"
1722 (concat "Query replacing "
1723 (if delimited-flag "word " "")
1724 (if regexp-flag "regexp " "")
1725 from-string " with "
1726 next-replacement ".\n\n"
1727 (substitute-command-keys
1728 query-replace-help)))
1729 (with-current-buffer standard-output
1732 (setq keep-going nil)
1734 ((eq def 'exit-current)
1735 (setq multi-buffer t keep-going nil done t))
1738 (let ((elt (pop stack)))
1739 (goto-char (nth 0 elt))
1740 (setq replaced (nth 1 elt)
1745 (message "No previous match")
1746 (ding 'no-terminate)
1751 (replace-match-maybe-edit
1752 next-replacement nocasify literal
1753 noedit real-match-data)
1754 replace-count (1+ replace-count)))
1755 (setq done t replaced t))
1756 ((eq def 'act-and-exit)
1759 (replace-match-maybe-edit
1760 next-replacement nocasify literal
1761 noedit real-match-data)
1762 replace-count (1+ replace-count)))
1763 (setq keep-going nil)
1764 (setq done t replaced t))
1765 ((eq def 'act-and-show)
1768 (replace-match-maybe-edit
1769 next-replacement nocasify literal
1770 noedit real-match-data)
1771 replace-count (1+ replace-count)
1772 real-match-data (replace-match-data
1775 ((or (eq def 'automatic) (eq def 'automatic-all))
1778 (replace-match-maybe-edit
1779 next-replacement nocasify literal
1780 noedit real-match-data)
1781 replace-count (1+ replace-count)))
1782 (setq done t query-flag nil replaced t)
1783 (if (eq def 'automatic-all) (setq multi-buffer t)))
1789 (let ((opos (point-marker)))
1790 (setq real-match-data (replace-match-data
1793 (goto-char (match-beginning 0))
1795 (save-window-excursion
1798 (set-marker opos nil))
1799 ;; Before we make the replacement,
1800 ;; decide whether the search string
1801 ;; can match again just after this match.
1802 (if (and regexp-flag nonempty-match)
1803 (setq match-again (and (looking-at search-string)
1805 ;; Edit replacement.
1806 ((eq def 'edit-replacement)
1807 (setq real-match-data (replace-match-data
1811 (read-string "Edit replacement string: "
1815 (set-match-data real-match-data)
1817 (replace-match-maybe-edit
1818 next-replacement nocasify literal noedit
1823 ((eq def 'delete-and-edit)
1824 (replace-match "" t t)
1825 (setq real-match-data (replace-match-data
1826 nil real-match-data))
1827 (replace-dehighlight)
1828 (save-excursion (recursive-edit))
1830 ;; Note: we do not need to treat `exit-prefix'
1831 ;; specially here, since we reread
1832 ;; any unrecognized character.
1834 (setq this-command 'mode-exited)
1835 (setq keep-going nil)
1836 (setq unread-command-events
1837 (append (listify-key-sequence key)
1838 unread-command-events))
1840 (when query-replace-lazy-highlight
1841 ;; Force lazy rehighlighting only after replacements
1842 (if (not (memq def '(skip backup)))
1843 (setq isearch-lazy-highlight-last-string nil))))
1844 ;; Record previous position for ^ when we move on.
1845 ;; Change markers to numbers in the match data
1846 ;; since lots of markers slow down editing.
1847 (push (list (point) replaced
1848 ;;; If the replacement has already happened, all we need is the
1849 ;;; current match start and end. We could get this with a trivial
1851 ;;; (save-excursion (goto-char (match-beginning 0))
1852 ;;; (search-forward (match-string 0))
1854 ;;; if we really wanted to avoid manually constructing match data.
1855 ;;; Adding current-buffer is necessary so that match-data calls can
1856 ;;; return markers which are appropriate for editing.
1865 (replace-dehighlight))
1866 (or unread-command-events
1867 (message "Replaced %d occurrence%s"
1869 (if (= replace-count 1) "" "s")))
1870 (or (and keep-going stack) multi-buffer)))
1872 (defvar replace-overlay nil)
1874 (defun replace-highlight (match-beg match-end range-beg range-end
1875 string regexp case-fold)
1876 (if query-replace-highlight
1878 (move-overlay replace-overlay match-beg match-end (current-buffer))
1879 (setq replace-overlay (make-overlay match-beg match-end))
1880 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
1881 (overlay-put replace-overlay 'face 'query-replace)))
1882 (if query-replace-lazy-highlight
1883 (let ((isearch-string string)
1884 (isearch-regexp regexp)
1885 (search-whitespace-regexp nil)
1886 (isearch-case-fold-search case-fold))
1887 (isearch-lazy-highlight-new-loop range-beg range-end))))
1889 (defun replace-dehighlight ()
1890 (when replace-overlay
1891 (delete-overlay replace-overlay))
1892 (when query-replace-lazy-highlight
1893 (lazy-highlight-cleanup lazy-highlight-cleanup)
1894 (setq isearch-lazy-highlight-last-string nil)))
1896 ;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1897 ;;; replace.el ends here