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 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, or (at your option)
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; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
23 ;; Boston, MA 02110-1301, USA.
27 ;; This package supplies the string and regular-expression replace functions
28 ;; documented in the Emacs user's manual.
32 (defcustom case-replace t
33 "*Non-nil means `query-replace' should preserve case in replacements."
37 (defvar query-replace-history nil
)
39 (defvar query-replace-defaults nil
40 "Default values of FROM-STRING and TO-STRING for `query-replace'.
41 This is a cons cell (FROM-STRING . TO-STRING), or nil if there is
44 (defvar query-replace-interactive nil
45 "Non-nil means `query-replace' uses the last search string.
46 That becomes the \"string to replace\".")
48 (defcustom query-replace-from-history-variable
'query-replace-history
49 "History list to use for the FROM argument of `query-replace' commands.
50 The value of this variable should be a symbol; that symbol
51 is used as a variable to hold a history list for the strings
52 or patterns to be replaced."
57 (defcustom query-replace-to-history-variable
'query-replace-history
58 "History list to use for the TO argument of `query-replace' commands.
59 The value of this variable should be a symbol; that symbol
60 is used as a variable to hold a history list for replacement
66 (defcustom query-replace-skip-read-only nil
67 "*Non-nil means `query-replace' and friends ignore read-only matches."
72 (defcustom query-replace-show-replacement t
73 "*Non-nil means to show what actual replacement text will be."
78 (defcustom query-replace-highlight t
79 "*Non-nil means to highlight matches during query replacement."
83 (defcustom query-replace-lazy-highlight t
84 "*Controls the lazy-highlighting during query replacements.
85 When non-nil, all text in the buffer matching the current match
86 is highlighted lazily using isearch lazy highlighting (see
87 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
89 :group
'lazy-highlight
93 (defface query-replace
94 '((t (:inherit isearch
)))
95 "Face for highlighting query replacement matches."
99 (defun query-replace-descr (string)
100 (mapconcat 'isearch-text-char-description string
""))
102 (defun query-replace-read-from (prompt regexp-flag
)
103 "Query and return the `from' argument of a query-replace operation.
104 The return value can also be a pair (FROM . TO) indicating that the user
105 wants to replace FROM with TO."
106 (if query-replace-interactive
107 (car (if regexp-flag regexp-search-ring search-ring
))
108 (let* ((history-add-new-input nil
)
110 ;; The save-excursion here is in case the user marks and copies
111 ;; a region in order to specify the minibuffer input.
112 ;; That should not clobber the region for the query-replace itself.
114 (read-from-minibuffer
115 (if query-replace-defaults
116 (format "%s (default %s -> %s): " prompt
117 (query-replace-descr (car query-replace-defaults
))
118 (query-replace-descr (cdr query-replace-defaults
)))
119 (format "%s: " prompt
))
121 query-replace-from-history-variable
123 (if (and (zerop (length from
)) query-replace-defaults
)
124 (cons (car query-replace-defaults
)
125 (query-replace-compile-replacement
126 (cdr query-replace-defaults
) regexp-flag
))
127 (add-to-history query-replace-from-history-variable from nil t
)
128 ;; Warn if user types \n or \t, but don't reject the input.
130 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from
)
131 (let ((match (match-string 3 from
)))
133 ((string= match
"\\n")
134 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
135 ((string= match
"\\t")
136 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
140 (defun query-replace-compile-replacement (to regexp-flag
)
141 "Maybe convert a regexp replacement TO to Lisp.
142 Returns a list suitable for `perform-replace' if necessary,
143 the original string if not."
145 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
))
149 (setq pos
(match-end 0))
150 (push (substring to
0 (- pos
2)) list
)
151 (setq char
(aref to
(1- pos
))
152 to
(substring to pos
))
154 (push '(number-to-string replace-count
) list
))
156 (setq pos
(read-from-string to
))
157 (push `(replace-quote ,(car pos
)) list
)
159 ;; Swallow a space after a symbol
160 ;; if there is a space.
161 (if (and (or (symbolp (car pos
))
162 ;; Swallow a space after 'foo
163 ;; but not after (quote foo).
164 (and (eq (car-safe (car pos
)) 'quote
)
165 (not (= ?\
( (aref to
0)))))
166 (eq (string-match " " to
(cdr pos
))
170 (setq to
(substring to end
)))))
171 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to
)))
172 (setq to
(nreverse (delete "" (cons to list
))))
173 (replace-match-string-symbols to
)
174 (cons 'replace-eval-replacement
181 (defun query-replace-read-to (from prompt regexp-flag
)
182 "Query and return the `to' argument of a query-replace operation."
183 (query-replace-compile-replacement
185 (let* ((history-add-new-input nil
)
186 (to (read-from-minibuffer
187 (format "%s %s with: " prompt
(query-replace-descr from
))
189 query-replace-to-history-variable from t
)))
190 (add-to-history query-replace-to-history-variable to nil t
)
191 (setq query-replace-defaults
(cons from to
))
195 (defun query-replace-read-args (prompt regexp-flag
&optional noerror
)
197 (barf-if-buffer-read-only))
198 (let* ((from (query-replace-read-from prompt regexp-flag
))
199 (to (if (consp from
) (prog1 (cdr from
) (setq from
(car from
)))
200 (query-replace-read-to from prompt regexp-flag
))))
201 (list from to current-prefix-arg
)))
203 (defun query-replace (from-string to-string
&optional delimited start end
)
204 "Replace some occurrences of FROM-STRING with TO-STRING.
205 As each match is found, the user must type a character saying
206 what to do with it. For directions, type \\[help-command] at that time.
208 In Transient Mark mode, if the mark is active, operate on the contents
209 of the region. Otherwise, operate from point to the end of the buffer.
211 If `query-replace-interactive' is non-nil, the last incremental search
212 string is used as FROM-STRING--you don't have to specify it with the
215 Matching is independent of case if `case-fold-search' is non-nil and
216 FROM-STRING has no uppercase letters. Replacement transfers the case
217 pattern of the old text to the new text, if `case-replace' and
218 `case-fold-search' are non-nil and FROM-STRING has no uppercase
219 letters. \(Transferring the case pattern means that if the old text
220 matched is all caps, or capitalized, then its replacement is upcased
223 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
224 only matches surrounded by word boundaries.
225 Fourth and fifth arg START and END specify the region to operate on.
227 To customize possible responses, change the \"bindings\" in `query-replace-map'."
228 (interactive (let ((common
229 (query-replace-read-args
230 (if (and transient-mark-mode mark-active
)
231 "Query replace in region"
234 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
235 ;; These are done separately here
236 ;; so that command-history will record these expressions
237 ;; rather than the values they had this time.
238 (if (and transient-mark-mode mark-active
)
240 (if (and transient-mark-mode mark-active
)
242 (perform-replace from-string to-string t nil delimited nil nil start end
))
244 (define-key esc-map
"%" 'query-replace
)
246 (defun query-replace-regexp (regexp to-string
&optional delimited start end
)
247 "Replace some things after point matching REGEXP with TO-STRING.
248 As each match is found, the user must type a character saying
249 what to do with it. For directions, type \\[help-command] at that time.
251 In Transient Mark mode, if the mark is active, operate on the contents
252 of the region. Otherwise, operate from point to the end of the buffer.
254 If `query-replace-interactive' is non-nil, the last incremental search
255 regexp is used as REGEXP--you don't have to specify it with the
258 Matching is independent of case if `case-fold-search' is non-nil and
259 REGEXP has no uppercase letters. Replacement transfers the case
260 pattern of the old text to the new text, if `case-replace' and
261 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
262 \(Transferring the case pattern means that if the old text matched is
263 all caps, or capitalized, then its replacement is upcased or
266 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
267 only matches surrounded by word boundaries.
268 Fourth and fifth arg START and END specify the region to operate on.
270 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
271 and `\\=\\N' (where N is a digit) stands for
272 whatever what matched the Nth `\\(...\\)' in REGEXP.
273 `\\?' lets you edit the replacement text in the minibuffer
274 at the given position for each replacement.
276 In interactive calls, the replacement text can contain `\\,'
277 followed by a Lisp expression. Each
278 replacement evaluates that expression to compute the replacement
279 string. Inside of that expression, `\\&' is a string denoting the
280 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
281 for the whole or a partial match converted to a number with
282 `string-to-number', and `\\#' itself for the number of replacements
283 done so far (starting with zero).
285 If the replacement expression is a symbol, write a space after it
286 to terminate it. One space there, if any, will be discarded.
288 When using those Lisp features interactively in the replacement
289 text, TO-STRING is actually made a list instead of a string.
290 Use \\[repeat-complex-command] after this command for details."
293 (query-replace-read-args
294 (if (and transient-mark-mode mark-active
)
295 "Query replace regexp in region"
296 "Query replace regexp")
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
452 (if (and transient-mark-mode mark-active
)
453 "Replace string in region"
456 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
457 (if (and transient-mark-mode mark-active
)
459 (if (and transient-mark-mode mark-active
)
461 (perform-replace from-string to-string nil nil delimited nil nil start end
))
463 (defun replace-regexp (regexp to-string
&optional delimited start end
)
464 "Replace things after point matching REGEXP with TO-STRING.
465 Preserve case in each match if `case-replace' and `case-fold-search'
466 are non-nil and REGEXP has no uppercase letters.
468 In Transient Mark mode, if the mark is active, operate on the contents
469 of the region. Otherwise, operate from point to the end of the buffer.
471 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
472 only matches surrounded by word boundaries.
473 Fourth and fifth arg START and END specify the region to operate on.
475 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
476 and `\\=\\N' (where N is a digit) stands for
477 whatever what matched the Nth `\\(...\\)' in REGEXP.
478 `\\?' lets you edit the replacement text in the minibuffer
479 at the given position for each replacement.
481 In interactive calls, the replacement text may contain `\\,'
482 followed by a Lisp expression used as part of the replacement
483 text. Inside of that expression, `\\&' is a string denoting the
484 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
485 numeric values from `string-to-number', and `\\#' itself for
486 `replace-count', the number of replacements occurred so far.
488 If your Lisp expression is an identifier and the next letter in
489 the replacement string would be interpreted as part of it, you
490 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
491 for this particular case you may also enter `\\#' in the
492 replacement text directly.
494 When using those Lisp features interactively in the replacement
495 text, TO-STRING is actually made a list instead of a string.
496 Use \\[repeat-complex-command] after this command for details.
498 If `query-replace-interactive' is non-nil, the last incremental search
499 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
501 This function is usually the wrong thing to use in a Lisp program.
502 What you probably want is a loop like this:
503 (while (re-search-forward REGEXP nil t)
504 (replace-match TO-STRING nil nil))
505 which will run faster and will not set the mark or print anything."
508 (query-replace-read-args
509 (if (and transient-mark-mode mark-active
)
510 "Replace regexp in region"
513 (list (nth 0 common
) (nth 1 common
) (nth 2 common
)
514 (if (and transient-mark-mode mark-active
)
516 (if (and transient-mark-mode mark-active
)
518 (perform-replace regexp to-string nil t delimited nil nil start end
))
521 (defvar regexp-history nil
522 "History list for some commands that read regular expressions.
524 Maximum length of the history list is determined by the value
525 of `history-length', which see.")
528 (defalias 'delete-non-matching-lines
'keep-lines
)
529 (defalias 'delete-matching-lines
'flush-lines
)
530 (defalias 'count-matches
'how-many
)
533 (defun keep-lines-read-args (prompt)
534 "Read arguments for `keep-lines' and friends.
535 Prompt for a regexp with PROMPT.
536 Value is a list, (REGEXP)."
537 (let* ((default (list
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 (default (delete-dups (delq nil
(delete "" default
)))))
548 (list (read-from-minibuffer prompt nil nil nil
549 'regexp-history default t
)
552 (defun keep-lines (regexp &optional rstart rend interactive
)
553 "Delete all lines except those containing matches for REGEXP.
554 A match split across lines preserves all the lines it lies in.
555 When called from Lisp (and usually interactively as well, see below)
556 applies to all lines starting after point.
558 If REGEXP contains upper case characters (excluding those preceded by `\\')
559 and `search-upper-case' is non-nil, the matching is case-sensitive.
561 Second and third arg RSTART and REND specify the region to operate on.
562 This command operates on (the accessible part of) all lines whose
563 accessible part is entirely contained in the region determined by RSTART
564 and REND. (A newline ending a line counts as part of that line.)
566 Interactively, in Transient Mark mode when the mark is active, operate
567 on all lines whose accessible part is entirely contained in the region.
568 Otherwise, the command applies to all lines starting after point.
569 When calling this function from Lisp, you can pretend that it was
570 called interactively by passing a non-nil INTERACTIVE argument.
572 This function starts looking for the next match from the end of
573 the previous match. Hence, it ignores matches that overlap
574 a previously found match."
578 (barf-if-buffer-read-only)
579 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
582 (goto-char (min rstart rend
))
586 (goto-char (max rstart rend
))
587 (unless (or (bolp) (eobp))
590 (if (and interactive transient-mark-mode mark-active
)
591 (setq rstart
(region-beginning)
593 (goto-char (region-end))
594 (unless (or (bolp) (eobp))
598 rend
(point-max-marker)))
601 (or (bolp) (forward-line 1))
602 (let ((start (point))
604 (if (and case-fold-search search-upper-case
)
605 (isearch-no-upper-case-p regexp t
)
607 (while (< (point) rend
)
608 ;; Start is first char not preserved by previous match.
609 (if (not (re-search-forward regexp rend
'move
))
610 (delete-region start rend
)
611 (let ((end (save-excursion (goto-char (match-beginning 0))
614 ;; Now end is first char preserved by the new match.
616 (delete-region start end
))))
618 (setq start
(save-excursion (forward-line 1) (point)))
619 ;; If the match was empty, avoid matching again at same place.
620 (and (< (point) rend
)
621 (= (match-beginning 0) (match-end 0))
623 (set-marker rend nil
)
627 (defun flush-lines (regexp &optional rstart rend interactive
)
628 "Delete lines containing matches for REGEXP.
629 When called from Lisp (and usually when called interactively as
630 well, see below), applies to the part of the buffer after point.
631 The line point is in is deleted if and only if it contains a
632 match for regexp starting after point.
634 If REGEXP contains upper case characters (excluding those preceded by `\\')
635 and `search-upper-case' is non-nil, the matching is case-sensitive.
637 Second and third arg RSTART and REND specify the region to operate on.
638 Lines partially contained in this region are deleted if and only if
639 they contain a match entirely contained in it.
641 Interactively, in Transient Mark mode when the mark is active, operate
642 on the contents of the region. Otherwise, operate from point to the
643 end of (the accessible portion of) the buffer. When calling this function
644 from Lisp, you can pretend that it was called interactively by passing
645 a non-nil INTERACTIVE argument.
647 If a match is split across lines, all the lines it lies in are deleted.
648 They are deleted _before_ looking for the next match. Hence, a match
649 starting on the same line at which another match ended is ignored."
653 (barf-if-buffer-read-only)
654 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
657 (goto-char (min rstart rend
))
658 (setq rend
(copy-marker (max rstart rend
))))
659 (if (and interactive transient-mark-mode mark-active
)
660 (setq rstart
(region-beginning)
661 rend
(copy-marker (region-end)))
663 rend
(point-max-marker)))
665 (let ((case-fold-search
666 (if (and case-fold-search search-upper-case
)
667 (isearch-no-upper-case-p regexp t
)
670 (while (and (< (point) rend
)
671 (re-search-forward regexp rend t
))
672 (delete-region (save-excursion (goto-char (match-beginning 0))
675 (progn (forward-line 1) (point))))))
676 (set-marker rend nil
)
680 (defun how-many (regexp &optional rstart rend interactive
)
681 "Print and return number of matches for REGEXP following point.
682 When called from Lisp and INTERACTIVE is omitted or nil, just return
683 the number, do not print it; if INTERACTIVE is t, the function behaves
684 in all respects has if it had been called interactively.
686 If REGEXP contains upper case characters (excluding those preceded by `\\')
687 and `search-upper-case' is non-nil, the matching is case-sensitive.
689 Second and third arg RSTART and REND specify the region to operate on.
691 Interactively, in Transient Mark mode when the mark is active, operate
692 on the contents of the region. Otherwise, operate from point to the
693 end of (the accessible portion of) the buffer.
695 This function starts looking for the next match from the end of
696 the previous match. Hence, it ignores matches that overlap
697 a previously found match."
700 (keep-lines-read-args "How many matches for (regexp): "))
704 (goto-char (min rstart rend
))
705 (setq rend
(max rstart rend
)))
706 (if (and interactive transient-mark-mode mark-active
)
707 (setq rstart
(region-beginning)
715 (if (and case-fold-search search-upper-case
)
716 (isearch-no-upper-case-p regexp t
)
718 (while (and (< (point) rend
)
719 (progn (setq opoint
(point))
720 (re-search-forward regexp rend t
)))
721 (if (= opoint
(point))
723 (setq count
(1+ count
))))
724 (when interactive
(message "%d occurrence%s"
726 (if (= count
1) "" "s")))
730 (defvar occur-mode-map
731 (let ((map (make-sparse-keymap)))
732 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
733 (define-key map
[mouse-2
] 'occur-mode-mouse-goto
)
734 (define-key map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
735 (define-key map
"\C-m" 'occur-mode-goto-occurrence
)
736 (define-key map
"o" 'occur-mode-goto-occurrence-other-window
)
737 (define-key map
"\C-o" 'occur-mode-display-occurrence
)
738 (define-key map
"\M-n" 'occur-next
)
739 (define-key map
"\M-p" 'occur-prev
)
740 (define-key map
"r" 'occur-rename-buffer
)
741 (define-key map
"c" 'clone-buffer
)
742 (define-key map
"g" 'revert-buffer
)
743 (define-key map
"q" 'quit-window
)
744 (define-key map
"z" 'kill-this-buffer
)
745 (define-key map
"\C-c\C-f" 'next-error-follow-minor-mode
)
746 (define-key map
[menu-bar
] (make-sparse-keymap))
747 (define-key map
[menu-bar occur
]
749 (define-key map
[next-error-follow-minor-mode
]
750 (menu-bar-make-mm-toggle next-error-follow-minor-mode
751 "Auto Occurrence Display"
752 "Display another occurrence when moving the cursor"))
753 (define-key map
[separator-1
] '("--"))
754 (define-key map
[kill-this-buffer
]
755 '("Kill occur buffer" . kill-this-buffer
))
756 (define-key map
[quit-window
]
757 '("Quit occur window" . quit-window
))
758 (define-key map
[revert-buffer
]
759 '("Revert occur buffer" . revert-buffer
))
760 (define-key map
[clone-buffer
]
761 '("Clone occur buffer" . clone-buffer
))
762 (define-key map
[occur-rename-buffer
]
763 '("Rename occur buffer" . occur-rename-buffer
))
764 (define-key map
[separator-2
] '("--"))
765 (define-key map
[occur-mode-goto-occurrence-other-window
]
766 '("Go To Occurrence Other Window" . occur-mode-goto-occurrence-other-window
))
767 (define-key map
[occur-mode-goto-occurrence
]
768 '("Go To Occurrence" . occur-mode-goto-occurrence
))
769 (define-key map
[occur-mode-display-occurrence
]
770 '("Display Occurrence" . occur-mode-display-occurrence
))
771 (define-key map
[occur-next
]
772 '("Move to next match" . occur-next
))
773 (define-key map
[occur-prev
]
774 '("Move to previous match" . occur-prev
))
776 "Keymap for `occur-mode'.")
778 (defvar occur-revert-arguments nil
779 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
780 See `occur-revert-function'.")
782 (defcustom occur-mode-hook
'(turn-on-font-lock)
783 "Hook run when entering Occur mode."
787 (defcustom occur-hook nil
788 "Hook run by Occur when there are any matches."
792 (put 'occur-mode
'mode-class
'special
)
794 "Major mode for output from \\[occur].
795 \\<occur-mode-map>Move point to one of the items in this buffer, then use
796 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
797 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
801 (kill-all-local-variables)
802 (use-local-map occur-mode-map
)
803 (setq major-mode
'occur-mode
)
804 (setq mode-name
"Occur")
805 (set (make-local-variable 'revert-buffer-function
) 'occur-revert-function
)
806 (make-local-variable 'occur-revert-arguments
)
807 (add-hook 'change-major-mode-hook
'font-lock-defontify nil t
)
808 (setq next-error-function
'occur-next-error
)
809 (run-mode-hooks 'occur-mode-hook
))
811 (defun occur-revert-function (ignore1 ignore2
)
812 "Handle `revert-buffer' for Occur mode buffers."
813 (apply 'occur-1
(append occur-revert-arguments
(list (buffer-name)))))
815 (defun occur-mode-find-occurrence ()
816 (let ((pos (get-text-property (point) 'occur-target
)))
818 (error "No occurrence on this line"))
819 (unless (buffer-live-p (marker-buffer pos
))
820 (error "Buffer for this occurrence was killed"))
823 (defalias 'occur-mode-mouse-goto
'occur-mode-goto-occurrence
)
824 (defun occur-mode-goto-occurrence (&optional event
)
825 "Go to the occurrence the current line describes."
826 (interactive (list last-nonmenu-event
))
829 ;; Actually `event-end' works correctly with a nil argument as
830 ;; well, so we could dispense with this test, but let's not
831 ;; rely on this undocumented behavior.
832 (occur-mode-find-occurrence)
833 (with-current-buffer (window-buffer (posn-window (event-end event
)))
835 (goto-char (posn-point (event-end event
)))
836 (occur-mode-find-occurrence)))))
837 same-window-buffer-names
839 (pop-to-buffer (marker-buffer pos
))
842 (defun occur-mode-goto-occurrence-other-window ()
843 "Go to the occurrence the current line describes, in another window."
845 (let ((pos (occur-mode-find-occurrence)))
846 (switch-to-buffer-other-window (marker-buffer pos
))
849 (defun occur-mode-display-occurrence ()
850 "Display in another window the occurrence the current line describes."
852 (let ((pos (occur-mode-find-occurrence))
854 ;; Bind these to ensure `display-buffer' puts it in another window.
855 same-window-buffer-names
857 (setq window
(display-buffer (marker-buffer pos
)))
858 ;; This is the way to set point in the proper window.
859 (save-selected-window
860 (select-window window
)
863 (defun occur-find-match (n search message
)
864 (if (not n
) (setq n
1))
867 (setq r
(funcall search
(point) 'occur-match
))
869 (get-text-property r
'occur-match
)
870 (setq r
(funcall search r
'occur-match
)))
876 (defun occur-next (&optional n
)
877 "Move to the Nth (default 1) next match in an Occur mode buffer."
879 (occur-find-match n
#'next-single-property-change
"No more matches"))
881 (defun occur-prev (&optional n
)
882 "Move to the Nth (default 1) previous match in an Occur mode buffer."
884 (occur-find-match n
#'previous-single-property-change
"No earlier matches"))
886 (defun occur-next-error (&optional argp reset
)
887 "Move to the Nth (default 1) next match in an Occur mode buffer.
888 Compatibility function for \\[next-error] invocations."
890 ;; we need to run occur-find-match from within the Occur buffer
892 ;; Choose the buffer and make it current.
893 (if (next-error-buffer-p (current-buffer))
895 (next-error-find-buffer nil nil
897 (eq major-mode
'occur-mode
))))
899 (goto-char (cond (reset (point-min))
900 ((< argp
0) (line-beginning-position))
901 ((> argp
0) (line-end-position))
906 #'previous-single-property-change
907 #'next-single-property-change
)
909 ;; In case the *Occur* buffer is visible in a nonselected window.
910 (let ((win (get-buffer-window (current-buffer) t
)))
911 (if win
(set-window-point win
(point))))
912 (occur-mode-goto-occurrence)))
915 '((((class color
) (min-colors 88) (background light
))
916 :background
"yellow1")
917 (((class color
) (min-colors 88) (background dark
))
918 :background
"RoyalBlue3")
919 (((class color
) (min-colors 8) (background light
))
920 :background
"yellow" :foreground
"black")
921 (((class color
) (min-colors 8) (background dark
))
922 :background
"blue" :foreground
"white")
923 (((type tty
) (class mono
))
925 (t :background
"gray"))
926 "Face used to highlight matches permanently."
930 (defcustom list-matching-lines-default-context-lines
0
931 "*Default number of context lines included around `list-matching-lines' matches.
932 A negative number means to include that many lines before the match.
933 A positive number means to include that many lines both before and after."
937 (defalias 'list-matching-lines
'occur
)
939 (defcustom list-matching-lines-face
'match
940 "*Face used by \\[list-matching-lines] to show the text that matches.
941 If the value is nil, don't highlight the matching portions specially."
945 (defcustom list-matching-lines-buffer-name-face
'underline
946 "*Face used by \\[list-matching-lines] to show the names of buffers.
947 If the value is nil, don't highlight the buffer names specially."
951 (defcustom occur-excluded-properties
952 '(read-only invisible intangible field mouse-face help-echo local-map keymap
953 yank-handler follow-link
)
954 "*Text properties to discard when copying lines to the *Occur* buffer.
955 The value should be a list of text properties to discard or t,
956 which means to discard all text properties."
957 :type
'(choice (const :tag
"All" t
) (repeat symbol
))
961 (defun occur-accumulate-lines (count &optional keep-props
)
963 (let ((forwardp (> count
0))
965 (while (not (or (zerop count
)
969 (setq count
(+ count
(if forwardp -
1 1)))
970 (setq beg
(line-beginning-position)
971 end
(line-end-position))
972 (if (and keep-props
(if (boundp 'jit-lock-mode
) jit-lock-mode
)
973 (text-property-not-all beg end
'fontified t
))
974 (if (fboundp 'jit-lock-fontify-now
)
975 (jit-lock-fontify-now beg end
)))
977 (if (and keep-props
(not (eq occur-excluded-properties t
)))
978 (let ((str (buffer-substring beg end
)))
979 (remove-list-of-text-properties
980 0 (length str
) occur-excluded-properties str
)
982 (buffer-substring-no-properties beg end
))
984 (forward-line (if forwardp
1 -
1)))
987 (defun occur-read-primary-args ()
989 (list (and transient-mark-mode mark-active
991 (buffer-substring-no-properties
992 (region-beginning) (region-end))))
995 (or find-tag-default-function
996 (get major-mode
'find-tag-default-function
)
999 (car regexp-search-ring
)
1000 (regexp-quote (or (car search-ring
) ""))
1002 query-replace-from-history-variable
))))
1003 (default (delete-dups (delq nil
(delete "" default
))))
1005 (read-from-minibuffer
1006 "List lines matching regexp: "
1007 nil nil nil
'regexp-history default
)))
1009 (when current-prefix-arg
1010 (prefix-numeric-value current-prefix-arg
)))))
1012 (defun occur-rename-buffer (&optional unique-p interactive-p
)
1013 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1014 Here `original-buffer-name' is the buffer name were Occur was originally run.
1015 When given the prefix argument, or called non-interactively, the renaming
1016 will not clobber the existing buffer(s) of that name, but use
1017 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1018 if you always want a separate *Occur* buffer for each buffer where you
1020 (interactive "P\np")
1021 (with-current-buffer
1022 (if (eq major-mode
'occur-mode
) (current-buffer) (get-buffer "*Occur*"))
1023 (rename-buffer (concat "*Occur: "
1024 (mapconcat #'buffer-name
1025 (car (cddr occur-revert-arguments
)) "/")
1027 (or unique-p
(not interactive-p
)))))
1029 (defun occur (regexp &optional nlines
)
1030 "Show all lines in the current buffer containing a match for REGEXP.
1031 This function can not handle matches that span more than one line.
1033 Each line is displayed with NLINES lines before and after, or -NLINES
1034 before if NLINES is negative.
1035 NLINES defaults to `list-matching-lines-default-context-lines'.
1036 Interactively it is the prefix arg.
1038 The lines are shown in a buffer named `*Occur*'.
1039 It serves as a menu to find any of the occurrences in this buffer.
1040 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1042 If REGEXP contains upper case characters (excluding those preceded by `\\')
1043 and `search-upper-case' is non-nil, the matching is case-sensitive."
1044 (interactive (occur-read-primary-args))
1045 (occur-1 regexp nlines
(list (current-buffer))))
1047 (defun multi-occur (bufs regexp
&optional nlines
)
1048 "Show all lines in buffers BUFS containing a match for REGEXP.
1049 This function acts on multiple buffers; otherwise, it is exactly like
1050 `occur'. When you invoke this command interactively, you must specify
1051 the buffer names that you want, one by one."
1054 (let* ((bufs (list (read-buffer "First buffer to search: "
1055 (current-buffer) t
)))
1057 (ido-ignore-item-temp-list bufs
))
1058 (while (not (string-equal
1059 (setq buf
(read-buffer
1060 (if (eq read-buffer-function
'ido-read-buffer
)
1061 "Next buffer to search (C-j to end): "
1062 "Next buffer to search (RET to end): ")
1065 (add-to-list 'bufs buf
)
1066 (setq ido-ignore-item-temp-list bufs
))
1067 (nreverse (mapcar #'get-buffer bufs
)))
1068 (occur-read-primary-args)))
1069 (occur-1 regexp nlines bufs
))
1071 (defun multi-occur-in-matching-buffers (bufregexp regexp
&optional allbufs
)
1072 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1073 Normally BUFREGEXP matches against each buffer's visited file name,
1074 but if you specify a prefix argument, it matches against the buffer name.
1075 See also `multi-occur'."
1078 (let* ((default (car regexp-history
))
1080 (read-from-minibuffer
1081 (if current-prefix-arg
1082 "List lines in buffers whose names match regexp: "
1083 "List lines in buffers whose filenames match regexp: ")
1088 (if (equal input
"")
1091 (occur-read-primary-args)))
1095 (mapcar (lambda (buf)
1097 (string-match bufregexp
1099 (and (buffer-file-name buf
)
1100 (string-match bufregexp
1101 (buffer-file-name buf
))))
1105 (defun occur-1 (regexp nlines bufs
&optional buf-name
)
1107 (setq buf-name
"*Occur*"))
1109 (active-bufs (delq nil
(mapcar #'(lambda (buf)
1110 (when (buffer-live-p buf
) buf
))
1112 ;; Handle the case where one of the buffers we're searching is the
1113 ;; output buffer. Just rename it.
1114 (when (member buf-name
(mapcar 'buffer-name active-bufs
))
1115 (with-current-buffer (get-buffer buf-name
)
1118 ;; Now find or create the output buffer.
1119 ;; If we just renamed that buffer, we will make a new one here.
1120 (setq occur-buf
(get-buffer-create buf-name
))
1122 (with-current-buffer occur-buf
1124 (let ((inhibit-read-only t
)
1125 ;; Don't generate undo entries for creation of the initial contents.
1126 (buffer-undo-list t
))
1128 (let ((count (occur-engine
1129 regexp active-bufs occur-buf
1130 (or nlines list-matching-lines-default-context-lines
)
1131 (if (and case-fold-search search-upper-case
)
1132 (isearch-no-upper-case-p regexp t
)
1134 list-matching-lines-buffer-name-face
1135 nil list-matching-lines-face
1136 (not (eq occur-excluded-properties t
)))))
1137 (let* ((bufcount (length active-bufs
))
1138 (diff (- (length bufs
) bufcount
)))
1139 (message "Searched %d buffer%s%s; %s match%s for `%s'"
1140 bufcount
(if (= bufcount
1) "" "s")
1141 (if (zerop diff
) "" (format " (%d killed)" diff
))
1142 (if (zerop count
) "no" (format "%d" count
))
1143 (if (= count
1) "" "es")
1145 (setq occur-revert-arguments
(list regexp nlines bufs
))
1147 (kill-buffer occur-buf
)
1148 (display-buffer occur-buf
)
1149 (setq next-error-last-buffer occur-buf
)
1150 (setq buffer-read-only t
)
1151 (set-buffer-modified-p nil
)
1152 (run-hooks 'occur-hook
)))))))
1154 (defun occur-engine-add-prefix (lines)
1157 (concat " :" line
"\n"))
1160 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
1161 title-face prefix-face match-face keep-props
)
1162 (with-current-buffer out-buf
1163 (let ((globalcount 0)
1165 ;; Map over all the buffers
1166 (dolist (buf buffers
)
1167 (when (buffer-live-p buf
)
1168 (let ((matches 0) ;; count of matched lines
1169 (lines 1) ;; line count
1176 (inhibit-field-text-motion t
)
1177 (headerpt (with-current-buffer out-buf
(point))))
1178 (with-current-buffer buf
1180 ;; Set CODING only if the current buffer locally
1181 ;; binds buffer-file-coding-system.
1182 (not (local-variable-p 'buffer-file-coding-system
))
1183 (setq coding buffer-file-coding-system
))
1185 (goto-char (point-min)) ;; begin searching in the buffer
1187 (setq origpt
(point))
1188 (when (setq endpt
(re-search-forward regexp nil t
))
1189 (setq matches
(1+ matches
)) ;; increment match count
1190 (setq matchbeg
(match-beginning 0))
1191 (setq lines
(+ lines
(1- (count-lines origpt endpt
))))
1193 (goto-char matchbeg
)
1194 (setq begpt
(line-beginning-position)
1195 endpt
(line-end-position)))
1196 (setq marker
(make-marker))
1197 (set-marker marker matchbeg
)
1199 (if (boundp 'jit-lock-mode
) jit-lock-mode
)
1200 (text-property-not-all begpt endpt
'fontified t
))
1201 (if (fboundp 'jit-lock-fontify-now
)
1202 (jit-lock-fontify-now begpt endpt
)))
1203 (if (and keep-props
(not (eq occur-excluded-properties t
)))
1205 (setq curstring
(buffer-substring begpt endpt
))
1206 (remove-list-of-text-properties
1207 0 (length curstring
) occur-excluded-properties curstring
))
1208 (setq curstring
(buffer-substring-no-properties begpt endpt
)))
1209 ;; Highlight the matches
1210 (let ((len (length curstring
))
1212 (while (and (< start len
)
1213 (string-match regexp curstring start
))
1214 (add-text-properties
1215 (match-beginning 0) (match-end 0)
1219 ;; Use `face' rather than `font-lock-face' here
1220 ;; so as to override faces copied from the buffer.
1221 `(face ,match-face
)))
1223 (setq start
(match-end 0))))
1224 ;; Generate the string to insert for this match
1227 ;; Using 7 digits aligns tabs properly.
1228 (apply #'propertize
(format "%7d:" lines
)
1231 `(font-lock-face prefix-face
))
1232 `(occur-prefix t mouse-face
(highlight)
1233 occur-target
,marker follow-link t
1234 help-echo
"mouse-2: go to this occurrence")))
1235 ;; We don't put `mouse-face' on the newline,
1236 ;; because that loses. And don't put it
1237 ;; on context lines to reduce flicker.
1238 (propertize curstring
'mouse-face
(list 'highlight
)
1239 'occur-target marker
1242 "mouse-2: go to this occurrence")
1243 ;; Add marker at eol, but no mouse props.
1244 (propertize "\n" 'occur-target marker
)))
1247 ;; The simple display style
1249 ;; The complex multi-line display style.
1250 (occur-context-lines out-line nlines keep-props
)
1252 ;; Actually insert the match display data
1253 (with-current-buffer out-buf
1255 (end (progn (insert data
) (point))))
1256 (unless (= nlines
0)
1257 (insert "-------\n")))))
1261 (setq lines
(1+ lines
))
1262 ;; On to the next match...
1264 (goto-char (point-max))))))
1265 (when (not (zerop matches
)) ;; is the count zero?
1266 (setq globalcount
(+ globalcount matches
))
1267 (with-current-buffer out-buf
1268 (goto-char headerpt
)
1271 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1272 matches
(if (= matches
1) "" "es")
1273 regexp
(buffer-name buf
)))
1275 (add-text-properties beg end
1278 `(font-lock-face ,title-face
))
1279 `(occur-title ,buf
))))
1280 (goto-char (point-min)))))))
1282 ;; CODING is buffer-file-coding-system of the first buffer
1283 ;; that locally binds it. Let's use it also for the output
1285 (set-buffer-file-coding-system coding
))
1286 ;; Return the number of matches
1289 ;; Generate context display for occur.
1290 ;; OUT-LINE is the line where the match is.
1291 ;; NLINES and KEEP-PROPS are args to occur-engine.
1292 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1293 ;; then concatenate them all together.
1294 (defun occur-context-lines (out-line nlines keep-props
)
1297 (occur-engine-add-prefix
1298 (nreverse (cdr (occur-accumulate-lines
1299 (- (1+ (abs nlines
))) keep-props
))))
1302 (occur-engine-add-prefix
1303 (cdr (occur-accumulate-lines (1+ nlines
) keep-props
)))))))
1305 ;; It would be nice to use \\[...], but there is no reasonable way
1306 ;; to make that display both SPC and Y.
1307 (defconst query-replace-help
1308 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1309 RET or `q' to exit, Period to replace one match and exit,
1310 Comma to replace but not move point immediately,
1311 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1312 C-w to delete match and recursive edit,
1313 C-l to clear the screen, redisplay, and offer same replacement again,
1314 ! to replace all remaining matches with no more questions,
1315 ^ to move point back to previous match,
1316 E to edit the replacement string"
1317 "Help message while in `query-replace'.")
1319 (defvar query-replace-map
1320 (let ((map (make-sparse-keymap)))
1321 (define-key map
" " 'act
)
1322 (define-key map
"\d" 'skip
)
1323 (define-key map
[delete] 'skip)
1324 (define-key map [backspace] 'skip)
1325 (define-key map "y" 'act)
1326 (define-key map "n" 'skip)
1327 (define-key map "Y" 'act)
1328 (define-key map "N" 'skip)
1329 (define-key map "e" 'edit-replacement)
1330 (define-key map "E" 'edit-replacement)
1331 (define-key map "," 'act-and-show)
1332 (define-key map "q" 'exit)
1333 (define-key map "\r" 'exit)
1334 (define-key map [return] 'exit)
1335 (define-key map "." 'act-and-exit)
1336 (define-key map "\C-r" 'edit)
1337 (define-key map "\C-w" 'delete-and-edit)
1338 (define-key map "\C-l" 'recenter)
1339 (define-key map "!" 'automatic)
1340 (define-key map "^" 'backup)
1341 (define-key map "\C-h" 'help)
1342 (define-key map [f1] 'help)
1343 (define-key map [help] 'help)
1344 (define-key map "?" 'help)
1345 (define-key map "\C-g" 'quit)
1346 (define-key map "\C-]" 'quit)
1347 (define-key map "\e" 'exit-prefix)
1348 (define-key map [escape] 'exit-prefix)
1350 "Keymap that defines the responses to questions in `query-replace'.
1351 The \"bindings\" in this map are not commands; they are answers.
1352 The valid answers include `act', `skip', `act-and-show',
1353 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1354 `automatic', `backup', `exit-prefix', and `help'.")
1356 (defun replace-match-string-symbols (n)
1357 "Process a list (and any sub-lists), expanding certain symbols.
1359 N (match-string N) (where N is a string of digits)
1360 #N (string-to-number (match-string N))
1362 #& (string-to-number (match-string 0))
1365 Note that these symbols must be preceeded by a backslash in order to
1366 type them using Lisp syntax."
1370 (replace-match-string-symbols (car n))) ;Process sub-list
1372 (let ((name (symbol-name (car n))))
1374 ((string-match "^[0-9]+$" name)
1375 (setcar n (list 'match-string (string-to-number name))))
1376 ((string-match "^#[0-9]+$" name)
1377 (setcar n (list 'string-to-number
1379 (string-to-number (substring name 1))))))
1381 (setcar n '(match-string 0)))
1382 ((string= "#&" name)
1383 (setcar n '(string-to-number (match-string 0))))
1385 (setcar n 'replace-count))))))
1388 (defun replace-eval-replacement (expression replace-count)
1389 (let ((replacement (eval expression)))
1390 (if (stringp replacement)
1392 (prin1-to-string replacement t))))
1394 (defun replace-quote (replacement)
1395 "Quote a replacement string.
1396 This just doubles all backslashes in REPLACEMENT and
1397 returns the resulting string. If REPLACEMENT is not
1398 a string, it is first passed through `prin1-to-string'
1399 with the `noescape' argument set.
1401 `match-data' is preserved across the call."
1403 (replace-regexp-in-string "\\\\" "\\\\"
1404 (if (stringp replacement)
1406 (prin1-to-string replacement t))
1409 (defun replace-loop-through-replacements (data replace-count)
1410 ;; DATA is a vector contaning the following values:
1411 ;; 0 next-rotate-count
1413 ;; 2 next-replacement
1415 (if (= (aref data 0) replace-count)
1417 (aset data 0 (+ replace-count (aref data 1)))
1418 (let ((next (cdr (aref data 2))))
1419 (aset data 2 (if (consp next) next (aref data 3))))))
1420 (car (aref data 2)))
1422 (defun replace-match-data (integers reuse &optional new)
1423 "Like `match-data', but markers in REUSE get invalidated.
1424 If NEW is non-nil, it is set and returned instead of fresh data,
1425 but coerced to the correct value of INTEGERS."
1428 (set-match-data new)
1430 (eq (null integers) (markerp (car reuse)))
1432 (match-data integers reuse t)))
1434 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1435 "Make a replacement with `replace-match', editing `\\?'.
1436 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1437 check for `\\?' is made to save time. MATCH-DATA is used for the
1438 replacement. In case editing is done, it is changed to use markers.
1440 The return value is non-nil if there has been no `\\?' or NOEDIT was
1441 passed in. If LITERAL is set, no checking is done, anyway."
1442 (unless (or literal noedit)
1444 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1447 (read-string "Edit replacement string: "
1450 (replace-match "" t t newtext 3)
1451 (1+ (match-beginning 3)))
1454 nil match-data match-data))))
1456 (set-match-data match-data)
1457 (replace-match newtext fixedcase literal)
1460 (defun perform-replace (from-string replacements
1461 query-flag regexp-flag delimited-flag
1462 &optional repeat-count map start end)
1463 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1464 Don't use this in your own program unless you want to query and set the mark
1465 just as `query-replace' does. Instead, write a simple loop like this:
1467 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1468 (replace-match \"foobar\" nil nil))
1470 which will run faster and probably do exactly what you want. Please
1471 see the documentation of `replace-match' to find out how to simulate
1474 This function returns nil if and only if there were no matches to
1475 make, or the user didn't cancel the call."
1476 (or map (setq map query-replace-map))
1477 (and query-flag minibuffer-auto-raise
1478 (raise-frame (window-frame (minibuffer-window))))
1479 (let* ((case-fold-search
1480 (if (and case-fold-search search-upper-case)
1481 (isearch-no-upper-case-p from-string regexp-flag)
1483 (nocasify (not (and case-replace case-fold-search)))
1484 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1485 (search-function (if regexp-flag 're-search-forward 'search-forward))
1486 (search-string from-string)
1487 (real-match-data nil) ; The match data for the current match.
1488 (next-replacement nil)
1489 ;; This is non-nil if we know there is nothing for the user
1490 ;; to edit in the replacement.
1495 (nonempty-match nil)
1497 ;; If non-nil, it is marker saying where in the buffer to stop.
1500 ;; Data for the next match. If a cons, it has the same format as
1501 ;; (match-data); otherwise it is t if a match is possible at point.
1507 (substitute-command-keys
1508 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1509 minibuffer-prompt-properties))))
1511 ;; If region is active, in Transient Mark mode, operate on region.
1513 (setq limit (copy-marker (max start end)))
1514 (goto-char (min start end))
1517 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1518 ;; containing a function and its first argument. The function is
1519 ;; called to generate each replacement like this:
1520 ;; (funcall (car replacements) (cdr replacements) replace-count)
1521 ;; It must return a string.
1523 ((stringp replacements)
1524 (setq next-replacement replacements
1526 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1527 (or repeat-count (setq repeat-count 1))
1528 (setq replacements (cons 'replace-loop-through-replacements
1529 (vector repeat-count repeat-count
1530 replacements replacements)))))
1533 (setq search-function 're-search-forward
1534 search-string (concat "\\b"
1535 (if regexp-flag from-string
1536 (regexp-quote from-string))
1538 (when query-replace-lazy-highlight
1539 (setq isearch-lazy-highlight-last-string nil))
1544 ;; Loop finding occurrences that perhaps should be replaced.
1545 (while (and keep-going
1546 (not (or (eobp) (and limit (>= (point) limit))))
1547 ;; Use the next match if it is already known;
1548 ;; otherwise, search for a match after moving forward
1549 ;; one char if progress is required.
1550 (setq real-match-data
1551 (cond ((consp match-again)
1552 (goto-char (nth 1 match-again))
1554 t real-match-data match-again))
1555 ;; MATCH-AGAIN non-nil means accept an
1559 (funcall search-function search-string
1561 ;; For speed, use only integers and
1562 ;; reuse the list used last time.
1563 (replace-match-data t real-match-data)))
1564 ((and (< (1+ (point)) (point-max))
1566 (< (1+ (point)) limit)))
1567 ;; If not accepting adjacent matches,
1568 ;; move one char to the right before
1569 ;; searching again. Undo the motion
1570 ;; if the search fails.
1571 (let ((opoint (point)))
1574 search-function search-string
1581 ;; Record whether the match is nonempty, to avoid an infinite loop
1582 ;; repeatedly matching the same empty string.
1583 (setq nonempty-match
1584 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1586 ;; If the match is empty, record that the next one can't be
1589 ;; Otherwise, if matching a regular expression, do the next
1590 ;; match now, since the replacement for this match may
1591 ;; affect whether the next match is adjacent to this one.
1592 ;; If that match is empty, don't use it.
1595 (or (not regexp-flag)
1596 (and (looking-at search-string)
1597 (let ((match (match-data)))
1598 (and (/= (nth 0 match) (nth 1 match))
1601 ;; Optionally ignore matches that have a read-only property.
1602 (unless (and query-replace-skip-read-only
1603 (text-property-not-all
1604 (nth 0 real-match-data) (nth 1 real-match-data)
1607 ;; Calculate the replacement string, if necessary.
1609 (set-match-data real-match-data)
1610 (setq next-replacement
1611 (funcall (car replacements) (cdr replacements)
1613 (if (not query-flag)
1614 (let ((inhibit-read-only
1615 query-replace-skip-read-only))
1616 (unless (or literal noedit)
1618 (nth 0 real-match-data) (nth 1 real-match-data)
1619 start end search-string
1620 (or delimited-flag regexp-flag) case-fold-search))
1622 (replace-match-maybe-edit
1623 next-replacement nocasify literal
1624 noedit real-match-data)
1625 replace-count (1+ replace-count)))
1627 (let (done replaced key def)
1628 ;; Loop reading commands until one of them sets done,
1629 ;; which means it has finished handling this
1630 ;; occurrence. Any command that sets `done' should
1631 ;; leave behind proper match data for the stack.
1632 ;; Commands not setting `done' need to adjust
1633 ;; `real-match-data'.
1635 (set-match-data real-match-data)
1637 (match-beginning 0) (match-end 0)
1638 start end search-string
1639 (or delimited-flag regexp-flag) case-fold-search)
1640 ;; Bind message-log-max so we don't fill up the message log
1641 ;; with a bunch of identical messages.
1642 (let ((message-log-max nil)
1643 (replacement-presentation
1644 (if query-replace-show-replacement
1646 (set-match-data real-match-data)
1647 (match-substitute-replacement next-replacement
1651 (query-replace-descr from-string)
1652 (query-replace-descr replacement-presentation)))
1653 (setq key (read-event))
1654 ;; Necessary in case something happens during read-event
1655 ;; that clobbers the match data.
1656 (set-match-data real-match-data)
1657 (setq key (vector key))
1658 (setq def (lookup-key map key))
1659 ;; Restore the match data while we process the command.
1660 (cond ((eq def 'help)
1661 (with-output-to-temp-buffer "*Help*"
1663 (concat "Query replacing "
1664 (if regexp-flag "regexp " "")
1665 from-string " with "
1666 next-replacement ".\n\n"
1667 (substitute-command-keys
1668 query-replace-help)))
1669 (with-current-buffer standard-output
1672 (setq keep-going nil)
1676 (let ((elt (pop stack)))
1677 (goto-char (nth 0 elt))
1678 (setq replaced (nth 1 elt)
1683 (message "No previous match")
1684 (ding 'no-terminate)
1689 (replace-match-maybe-edit
1690 next-replacement nocasify literal
1691 noedit real-match-data)
1692 replace-count (1+ replace-count)))
1693 (setq done t replaced t))
1694 ((eq def 'act-and-exit)
1697 (replace-match-maybe-edit
1698 next-replacement nocasify literal
1699 noedit real-match-data)
1700 replace-count (1+ replace-count)))
1701 (setq keep-going nil)
1702 (setq done t replaced t))
1703 ((eq def 'act-and-show)
1706 (replace-match-maybe-edit
1707 next-replacement nocasify literal
1708 noedit real-match-data)
1709 replace-count (1+ replace-count)
1710 real-match-data (replace-match-data
1713 ((eq def 'automatic)
1716 (replace-match-maybe-edit
1717 next-replacement nocasify literal
1718 noedit real-match-data)
1719 replace-count (1+ replace-count)))
1720 (setq done t query-flag nil replaced t))
1726 (let ((opos (point-marker)))
1727 (setq real-match-data (replace-match-data
1730 (goto-char (match-beginning 0))
1732 (save-window-excursion
1735 (set-marker opos nil))
1736 ;; Before we make the replacement,
1737 ;; decide whether the search string
1738 ;; can match again just after this match.
1739 (if (and regexp-flag nonempty-match)
1740 (setq match-again (and (looking-at search-string)
1742 ;; Edit replacement.
1743 ((eq def 'edit-replacement)
1744 (setq real-match-data (replace-match-data
1748 (read-string "Edit replacement string: "
1752 (set-match-data real-match-data)
1754 (replace-match-maybe-edit
1755 next-replacement nocasify literal noedit
1760 ((eq def 'delete-and-edit)
1761 (replace-match "" t t)
1762 (setq real-match-data (replace-match-data
1763 nil real-match-data))
1764 (replace-dehighlight)
1765 (save-excursion (recursive-edit))
1767 ;; Note: we do not need to treat `exit-prefix'
1768 ;; specially here, since we reread
1769 ;; any unrecognized character.
1771 (setq this-command 'mode-exited)
1772 (setq keep-going nil)
1773 (setq unread-command-events
1774 (append (listify-key-sequence key)
1775 unread-command-events))
1777 (when query-replace-lazy-highlight
1778 ;; Force lazy rehighlighting only after replacements
1779 (if (not (memq def '(skip backup)))
1780 (setq isearch-lazy-highlight-last-string nil))))
1781 ;; Record previous position for ^ when we move on.
1782 ;; Change markers to numbers in the match data
1783 ;; since lots of markers slow down editing.
1784 (push (list (point) replaced
1785 ;;; If the replacement has already happened, all we need is the
1786 ;;; current match start and end. We could get this with a trivial
1788 ;;; (save-excursion (goto-char (match-beginning 0))
1789 ;;; (search-forward (match-string 0))
1791 ;;; if we really wanted to avoid manually constructing match data.
1792 ;;; Adding current-buffer is necessary so that match-data calls can
1793 ;;; return markers which are appropriate for editing.
1802 (replace-dehighlight))
1803 (or unread-command-events
1804 (message "Replaced %d occurrence%s"
1806 (if (= replace-count 1) "" "s")))
1807 (and keep-going stack)))
1809 (defvar replace-overlay nil)
1811 (defun replace-highlight (match-beg match-end range-beg range-end
1812 string regexp case-fold)
1813 (if query-replace-highlight
1815 (move-overlay replace-overlay match-beg match-end (current-buffer))
1816 (setq replace-overlay (make-overlay match-beg match-end))
1817 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
1818 (overlay-put replace-overlay 'face 'query-replace)))
1819 (if query-replace-lazy-highlight
1820 (let ((isearch-string string)
1821 (isearch-regexp regexp)
1822 (search-whitespace-regexp nil)
1823 (isearch-case-fold-search case-fold))
1824 (isearch-lazy-highlight-new-loop range-beg range-end))))
1826 (defun replace-dehighlight ()
1827 (when replace-overlay
1828 (delete-overlay replace-overlay))
1829 (when query-replace-lazy-highlight
1830 (lazy-highlight-cleanup lazy-highlight-cleanup)
1831 (setq isearch-lazy-highlight-last-string nil)))
1833 ;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1834 ;;; replace.el ends here