Document locate-file.
[bpt/emacs.git] / lisp / replace.el
... / ...
CommitLineData
1;;; replace.el --- replace commands for Emacs
2
3;; Copyright (C) 1985, 1986, 1987, 1992, 1994, 1996, 1997, 2000, 2001, 2002,
4;; 2003, 2004, 2005 Free Software Foundation, Inc.
5
6;; Maintainer: FSF
7
8;; This file is part of GNU Emacs.
9
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 2, or (at your option)
13;; any later version.
14
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.
19
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., 59 Temple Place - Suite 330,
23;; Boston, MA 02111-1307, USA.
24
25;;; Commentary:
26
27;; This package supplies the string and regular-expression replace functions
28;; documented in the Emacs user's manual.
29
30;;; Code:
31
32(defcustom case-replace t
33 "*Non-nil means `query-replace' should preserve case in replacements."
34 :type 'boolean
35 :group 'matching)
36
37(defvar query-replace-history nil)
38
39(defvar query-replace-interactive nil
40 "Non-nil means `query-replace' uses the last search string.
41That becomes the \"string to replace\".")
42
43(defcustom query-replace-from-history-variable 'query-replace-history
44 "History list to use for the FROM argument of `query-replace' commands.
45The value of this variable should be a symbol; that symbol
46is used as a variable to hold a history list for the strings
47or patterns to be replaced."
48 :group 'matching
49 :type 'symbol
50 :version "20.3")
51
52(defcustom query-replace-to-history-variable 'query-replace-history
53 "History list to use for the TO argument of `query-replace' commands.
54The value of this variable should be a symbol; that symbol
55is used as a variable to hold a history list for replacement
56strings or patterns."
57 :group 'matching
58 :type 'symbol
59 :version "20.3")
60
61(defcustom query-replace-skip-read-only nil
62 "*Non-nil means `query-replace' and friends ignore read-only matches."
63 :type 'boolean
64 :group 'matching
65 :version "22.1")
66
67(defcustom query-replace-highlight t
68 "*Non-nil means to highlight matches during query replacement."
69 :type 'boolean
70 :group 'matching)
71
72(defcustom query-replace-lazy-highlight t
73 "*Controls the lazy-highlighting during query replacements.
74When non-nil, all text in the buffer matching the current match
75is highlighted lazily using isearch lazy highlighting (see
76`lazy-highlight-initial-delay' and `lazy-highlight-interval')."
77 :type 'boolean
78 :group 'lazy-highlight
79 :group 'matching
80 :version "22.1")
81
82(defface query-replace
83 '((t (:inherit isearch)))
84 "Face for highlighting query replacement matches."
85 :group 'matching
86 :version "22.1")
87
88(defun query-replace-descr (string)
89 (mapconcat 'isearch-text-char-description string ""))
90
91(defun query-replace-read-from (string regexp-flag)
92 "Query and return the `from' argument of a query-replace operation.
93The return value can also be a pair (FROM . TO) indicating that the user
94wants to replace FROM with TO."
95 (if query-replace-interactive
96 (car (if regexp-flag regexp-search-ring search-ring))
97 (let* ((lastfrom (car (symbol-value query-replace-from-history-variable)))
98 (lastto (car (symbol-value query-replace-to-history-variable)))
99 (from
100 ;; The save-excursion here is in case the user marks and copies
101 ;; a region in order to specify the minibuffer input.
102 ;; That should not clobber the region for the query-replace itself.
103 (save-excursion
104 (when (equal lastfrom lastto)
105 ;; Typically, this is because the two histlists are shared.
106 (setq lastfrom (cadr (symbol-value
107 query-replace-from-history-variable))))
108 (read-from-minibuffer
109 (if (and lastto lastfrom)
110 (format "%s (default %s -> %s): " string
111 (query-replace-descr lastfrom)
112 (query-replace-descr lastto))
113 (format "%s: " string))
114 nil nil nil
115 query-replace-from-history-variable
116 nil t t))))
117 (if (and (zerop (length from)) lastto lastfrom)
118 (progn
119 (set query-replace-from-history-variable
120 (cdr (symbol-value query-replace-from-history-variable)))
121 (cons lastfrom
122 (query-replace-compile-replacement lastto regexp-flag)))
123 ;; Warn if user types \n or \t, but don't reject the input.
124 (and regexp-flag
125 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
126 (let ((match (match-string 3 from)))
127 (cond
128 ((string= match "\\n")
129 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
130 ((string= match "\\t")
131 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
132 (sit-for 2)))
133 from))))
134
135(defun query-replace-compile-replacement (to regexp-flag)
136 "Maybe convert a regexp replacement TO to Lisp.
137Returns a list suitable for `perform-replace' if necessary,
138the original string if not."
139 (if (and regexp-flag
140 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
141 (let (pos list char)
142 (while
143 (progn
144 (setq pos (match-end 0))
145 (push (substring to 0 (- pos 2)) list)
146 (setq char (aref to (1- pos))
147 to (substring to pos))
148 (cond ((eq char ?\#)
149 (push '(number-to-string replace-count) list))
150 ((eq char ?\,)
151 (setq pos (read-from-string to))
152 (push `(replace-quote ,(car pos)) list)
153 (let ((end
154 ;; Swallow a space after a symbol
155 ;; if there is a space.
156 (if (and (or (symbolp (car pos))
157 ;; Swallow a space after 'foo
158 ;; but not after (quote foo).
159 (and (eq (car-safe (car pos)) 'quote)
160 (not (= ?\( (aref to 0)))))
161 (eq (string-match " " to (cdr pos))
162 (cdr pos)))
163 (1+ (cdr pos))
164 (cdr pos))))
165 (setq to (substring to end)))))
166 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
167 (setq to (nreverse (delete "" (cons to list))))
168 (replace-match-string-symbols to)
169 (cons 'replace-eval-replacement
170 (if (cdr to)
171 (cons 'concat to)
172 (car to))))
173 to))
174
175
176(defun query-replace-read-to (from string regexp-flag)
177 "Query and return the `to' argument of a query-replace operation."
178 (query-replace-compile-replacement
179 (save-excursion
180 (read-from-minibuffer
181 (format "%s %s with: " string (query-replace-descr from))
182 nil nil nil
183 query-replace-to-history-variable from t t))
184 regexp-flag))
185
186(defun query-replace-read-args (string regexp-flag &optional noerror)
187 (unless noerror
188 (barf-if-buffer-read-only))
189 (let* ((from (query-replace-read-from string regexp-flag))
190 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
191 (query-replace-read-to from string regexp-flag))))
192 (list from to current-prefix-arg)))
193
194(defun query-replace (from-string to-string &optional delimited start end)
195 "Replace some occurrences of FROM-STRING with TO-STRING.
196As each match is found, the user must type a character saying
197what to do with it. For directions, type \\[help-command] at that time.
198
199In Transient Mark mode, if the mark is active, operate on the contents
200of the region. Otherwise, operate from point to the end of the buffer.
201
202If `query-replace-interactive' is non-nil, the last incremental search
203string is used as FROM-STRING--you don't have to specify it with the
204minibuffer.
205
206Matching is independent of case if `case-fold-search' is non-nil and
207FROM-STRING has no uppercase letters. Replacement transfers the case
208pattern of the old text to the new text, if `case-replace' and
209`case-fold-search' are non-nil and FROM-STRING has no uppercase
210letters. \(Transferring the case pattern means that if the old text
211matched is all caps, or capitalized, then its replacement is upcased
212or capitalized.)
213
214Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
215only matches surrounded by word boundaries.
216Fourth and fifth arg START and END specify the region to operate on.
217
218To customize possible responses, change the \"bindings\" in `query-replace-map'."
219 (interactive (let ((common
220 (query-replace-read-args
221 (if (and transient-mark-mode mark-active)
222 "Query replace in region"
223 "Query replace")
224 nil)))
225 (list (nth 0 common) (nth 1 common) (nth 2 common)
226 ;; These are done separately here
227 ;; so that command-history will record these expressions
228 ;; rather than the values they had this time.
229 (if (and transient-mark-mode mark-active)
230 (region-beginning))
231 (if (and transient-mark-mode mark-active)
232 (region-end)))))
233 (perform-replace from-string to-string t nil delimited nil nil start end))
234
235(define-key esc-map "%" 'query-replace)
236
237(defun query-replace-regexp (regexp to-string &optional delimited start end)
238 "Replace some things after point matching REGEXP with TO-STRING.
239As each match is found, the user must type a character saying
240what to do with it. For directions, type \\[help-command] at that time.
241
242In Transient Mark mode, if the mark is active, operate on the contents
243of the region. Otherwise, operate from point to the end of the buffer.
244
245If `query-replace-interactive' is non-nil, the last incremental search
246regexp is used as REGEXP--you don't have to specify it with the
247minibuffer.
248
249Matching is independent of case if `case-fold-search' is non-nil and
250REGEXP has no uppercase letters. Replacement transfers the case
251pattern of the old text to the new text, if `case-replace' and
252`case-fold-search' are non-nil and REGEXP has no uppercase letters.
253\(Transferring the case pattern means that if the old text matched is
254all caps, or capitalized, then its replacement is upcased or
255capitalized.)
256
257Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
258only matches surrounded by word boundaries.
259Fourth and fifth arg START and END specify the region to operate on.
260
261In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
262and `\\=\\N' (where N is a digit) stands for
263whatever what matched the Nth `\\(...\\)' in REGEXP.
264`\\?' lets you edit the replacement text in the minibuffer
265at the given position for each replacement.
266
267In interactive calls, the replacement text can contain `\\,'
268followed by a Lisp expression. Each
269replacement evaluates that expression to compute the replacement
270string. Inside of that expression, `\\&' is a string denoting the
271whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
272for the whole or a partial match converted to a number with
273`string-to-number', and `\\#' itself for the number of replacements
274done so far (starting with zero).
275
276If the replacement expression is a symbol, write a space after it
277to terminate it. One space there, if any, will be discarded.
278
279When using those Lisp features interactively in the replacement
280text, TO-STRING is actually made a list instead of a string.
281Use \\[repeat-complex-command] after this command for details."
282 (interactive
283 (let ((common
284 (query-replace-read-args
285 (if (and transient-mark-mode mark-active)
286 "Query replace regexp in region"
287 "Query replace regexp")
288 t)))
289 (list (nth 0 common) (nth 1 common) (nth 2 common)
290 ;; These are done separately here
291 ;; so that command-history will record these expressions
292 ;; rather than the values they had this time.
293 (if (and transient-mark-mode mark-active)
294 (region-beginning))
295 (if (and transient-mark-mode mark-active)
296 (region-end)))))
297 (perform-replace regexp to-string t t delimited nil nil start end))
298
299(define-key esc-map [?\C-%] 'query-replace-regexp)
300
301(defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
302 "Replace some things after point matching REGEXP with the result of TO-EXPR.
303As each match is found, the user must type a character saying
304what to do with it. For directions, type \\[help-command] at that time.
305
306TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
307reference `replace-count' to get the number of replacements already made.
308If the result of TO-EXPR is not a string, it is converted to one using
309`prin1-to-string' with the NOESCAPE argument (which see).
310
311For convenience, when entering TO-EXPR interactively, you can use `\\&' or
312`\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
313N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
314Use `\\#&' or `\\#N' if you want a number instead of a string.
315In interactive use, `\\#' in itself stands for `replace-count'.
316
317In Transient Mark mode, if the mark is active, operate on the contents
318of the region. Otherwise, operate from point to the end of the buffer.
319
320If `query-replace-interactive' is non-nil, the last incremental search
321regexp is used as REGEXP--you don't have to specify it with the
322minibuffer.
323
324Preserves case in each replacement if `case-replace' and `case-fold-search'
325are non-nil and REGEXP has no uppercase letters.
326
327Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
328only matches that are surrounded by word boundaries.
329Fourth and fifth arg START and END specify the region to operate on."
330 (interactive
331 (progn
332 (barf-if-buffer-read-only)
333 (let* ((from
334 ;; Let-bind the history var to disable the "foo -> bar" default.
335 ;; Maybe we shouldn't disable this default, but for now I'll
336 ;; leave it off. --Stef
337 (let ((query-replace-to-history-variable nil))
338 (query-replace-read-from "Query replace regexp" t)))
339 (to (list (read-from-minibuffer
340 (format "Query replace regexp %s with eval: "
341 (query-replace-descr from))
342 nil nil t query-replace-to-history-variable from t))))
343 ;; We make TO a list because replace-match-string-symbols requires one,
344 ;; and the user might enter a single token.
345 (replace-match-string-symbols to)
346 (list from (car to) current-prefix-arg
347 (if (and transient-mark-mode mark-active)
348 (region-beginning))
349 (if (and transient-mark-mode mark-active)
350 (region-end))))))
351 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
352 t 'literal delimited nil nil start end))
353
354(defun map-query-replace-regexp (regexp to-strings &optional n start end)
355 "Replace some matches for REGEXP with various strings, in rotation.
356The second argument TO-STRINGS contains the replacement strings,
357separated by spaces. Third arg DELIMITED (prefix arg if interactive),
358if non-nil, means replace only matches surrounded by word boundaries.
359This command works like `query-replace-regexp' except that each
360successive replacement uses the next successive replacement string,
361wrapping around from the last such string to the first.
362
363In Transient Mark mode, if the mark is active, operate on the contents
364of the region. Otherwise, operate from point to the end of the buffer.
365
366Non-interactively, TO-STRINGS may be a list of replacement strings.
367
368If `query-replace-interactive' is non-nil, the last incremental search
369regexp is used as REGEXP--you don't have to specify it with the minibuffer.
370
371A prefix argument N says to use each replacement string N times
372before rotating to the next.
373Fourth and fifth arg START and END specify the region to operate on."
374 (interactive
375 (let* ((from (if query-replace-interactive
376 (car regexp-search-ring)
377 (read-from-minibuffer "Map query replace (regexp): "
378 nil nil nil
379 'query-replace-history nil t)))
380 (to (read-from-minibuffer
381 (format "Query replace %s with (space-separated strings): "
382 (query-replace-descr from))
383 nil nil nil
384 'query-replace-history from t)))
385 (list from to
386 (and current-prefix-arg
387 (prefix-numeric-value current-prefix-arg))
388 (if (and transient-mark-mode mark-active)
389 (region-beginning))
390 (if (and transient-mark-mode mark-active)
391 (region-end)))))
392 (let (replacements)
393 (if (listp to-strings)
394 (setq replacements to-strings)
395 (while (/= (length to-strings) 0)
396 (if (string-match " " to-strings)
397 (setq replacements
398 (append replacements
399 (list (substring to-strings 0
400 (string-match " " to-strings))))
401 to-strings (substring to-strings
402 (1+ (string-match " " to-strings))))
403 (setq replacements (append replacements (list to-strings))
404 to-strings ""))))
405 (perform-replace regexp replacements t t nil n nil start end)))
406
407(defun replace-string (from-string to-string &optional delimited start end)
408 "Replace occurrences of FROM-STRING with TO-STRING.
409Preserve case in each match if `case-replace' and `case-fold-search'
410are non-nil and FROM-STRING has no uppercase letters.
411\(Preserving case means that if the string matched is all caps, or capitalized,
412then its replacement is upcased or capitalized.)
413
414In Transient Mark mode, if the mark is active, operate on the contents
415of the region. Otherwise, operate from point to the end of the buffer.
416
417Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
418only matches surrounded by word boundaries.
419Fourth and fifth arg START and END specify the region to operate on.
420
421If `query-replace-interactive' is non-nil, the last incremental search
422string is used as FROM-STRING--you don't have to specify it with the
423minibuffer.
424
425This function is usually the wrong thing to use in a Lisp program.
426What you probably want is a loop like this:
427 (while (search-forward FROM-STRING nil t)
428 (replace-match TO-STRING nil t))
429which will run faster and will not set the mark or print anything.
430\(You may need a more complex loop if FROM-STRING can match the null string
431and TO-STRING is also null.)"
432 (interactive
433 (let ((common
434 (query-replace-read-args
435 (if (and transient-mark-mode mark-active)
436 "Replace string in region"
437 "Replace string")
438 nil)))
439 (list (nth 0 common) (nth 1 common) (nth 2 common)
440 (if (and transient-mark-mode mark-active)
441 (region-beginning))
442 (if (and transient-mark-mode mark-active)
443 (region-end)))))
444 (perform-replace from-string to-string nil nil delimited nil nil start end))
445
446(defun replace-regexp (regexp to-string &optional delimited start end)
447 "Replace things after point matching REGEXP with TO-STRING.
448Preserve case in each match if `case-replace' and `case-fold-search'
449are non-nil and REGEXP has no uppercase letters.
450
451In Transient Mark mode, if the mark is active, operate on the contents
452of the region. Otherwise, operate from point to the end of the buffer.
453
454Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
455only matches surrounded by word boundaries.
456Fourth and fifth arg START and END specify the region to operate on.
457
458In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
459and `\\=\\N' (where N is a digit) stands for
460whatever what matched the Nth `\\(...\\)' in REGEXP.
461`\\?' lets you edit the replacement text in the minibuffer
462at the given position for each replacement.
463
464In interactive calls, the replacement text may contain `\\,'
465followed by a Lisp expression used as part of the replacement
466text. Inside of that expression, `\\&' is a string denoting the
467whole match, `\\N' a partial matches, `\\#&' and `\\#N' the
468respective numeric values from `string-to-number', and `\\#'
469itself for `replace-count', the number of replacements occured so
470far.
471
472If your Lisp expression is an identifier and the next letter in
473the replacement string would be interpreted as part of it, you
474can wrap it with an expression like `\\,(or \\#)'. Incidentally,
475for this particular case you may also enter `\\#' in the
476replacement text directly.
477
478When using those Lisp features interactively in the replacement
479text, TO-STRING is actually made a list instead of a string.
480Use \\[repeat-complex-command] after this command for details.
481
482If `query-replace-interactive' is non-nil, the last incremental search
483regexp is used as REGEXP--you don't have to specify it with the minibuffer.
484
485This function is usually the wrong thing to use in a Lisp program.
486What you probably want is a loop like this:
487 (while (re-search-forward REGEXP nil t)
488 (replace-match TO-STRING nil nil))
489which will run faster and will not set the mark or print anything."
490 (interactive
491 (let ((common
492 (query-replace-read-args
493 (if (and transient-mark-mode mark-active)
494 "Replace regexp in region"
495 "Replace regexp")
496 t)))
497 (list (nth 0 common) (nth 1 common) (nth 2 common)
498 (if (and transient-mark-mode mark-active)
499 (region-beginning))
500 (if (and transient-mark-mode mark-active)
501 (region-end)))))
502 (perform-replace regexp to-string nil t delimited nil nil start end))
503
504\f
505(defvar regexp-history nil
506 "History list for some commands that read regular expressions.")
507
508
509(defalias 'delete-non-matching-lines 'keep-lines)
510(defalias 'delete-matching-lines 'flush-lines)
511(defalias 'count-matches 'how-many)
512
513
514(defun keep-lines-read-args (prompt)
515 "Read arguments for `keep-lines' and friends.
516Prompt for a regexp with PROMPT.
517Value is a list, (REGEXP)."
518 (list (read-from-minibuffer prompt nil nil nil
519 'regexp-history nil t)))
520
521(defun keep-lines (regexp &optional rstart rend)
522 "Delete all lines except those containing matches for REGEXP.
523A match split across lines preserves all the lines it lies in.
524Applies to all lines after point.
525
526If REGEXP contains upper case characters (excluding those preceded by `\\'),
527the matching is case-sensitive.
528
529Second and third arg RSTART and REND specify the region to operate on.
530
531Interactively, in Transient Mark mode when the mark is active, operate
532on the contents of the region. Otherwise, operate from point to the
533end of the buffer."
534
535 (interactive
536 (progn
537 (barf-if-buffer-read-only)
538 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
539 (if rstart
540 (progn
541 (goto-char (min rstart rend))
542 (setq rend (copy-marker (max rstart rend))))
543 (if (and transient-mark-mode mark-active)
544 (setq rstart (region-beginning)
545 rend (copy-marker (region-end)))
546 (setq rstart (point)
547 rend (point-max-marker)))
548 (goto-char rstart))
549 (save-excursion
550 (or (bolp) (forward-line 1))
551 (let ((start (point))
552 (case-fold-search (and case-fold-search
553 (isearch-no-upper-case-p regexp t))))
554 (while (< (point) rend)
555 ;; Start is first char not preserved by previous match.
556 (if (not (re-search-forward regexp rend 'move))
557 (delete-region start rend)
558 (let ((end (save-excursion (goto-char (match-beginning 0))
559 (beginning-of-line)
560 (point))))
561 ;; Now end is first char preserved by the new match.
562 (if (< start end)
563 (delete-region start end))))
564
565 (setq start (save-excursion (forward-line 1) (point)))
566 ;; If the match was empty, avoid matching again at same place.
567 (and (< (point) rend)
568 (= (match-beginning 0) (match-end 0))
569 (forward-char 1))))))
570
571
572(defun flush-lines (regexp &optional rstart rend)
573 "Delete lines containing matches for REGEXP.
574If a match is split across lines, all the lines it lies in are deleted.
575Applies to lines after point.
576
577If REGEXP contains upper case characters (excluding those preceded by `\\'),
578the matching is case-sensitive.
579
580Second and third arg RSTART and REND specify the region to operate on.
581
582Interactively, in Transient Mark mode when the mark is active, operate
583on the contents of the region. Otherwise, operate from point to the
584end of the buffer."
585
586 (interactive
587 (progn
588 (barf-if-buffer-read-only)
589 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
590 (if rstart
591 (progn
592 (goto-char (min rstart rend))
593 (setq rend (copy-marker (max rstart rend))))
594 (if (and transient-mark-mode mark-active)
595 (setq rstart (region-beginning)
596 rend (copy-marker (region-end)))
597 (setq rstart (point)
598 rend (point-max-marker)))
599 (goto-char rstart))
600 (let ((case-fold-search (and case-fold-search
601 (isearch-no-upper-case-p regexp t))))
602 (save-excursion
603 (while (and (< (point) rend)
604 (re-search-forward regexp rend t))
605 (delete-region (save-excursion (goto-char (match-beginning 0))
606 (beginning-of-line)
607 (point))
608 (progn (forward-line 1) (point)))))))
609
610
611(defun how-many (regexp &optional rstart rend)
612 "Print number of matches for REGEXP following point.
613
614If REGEXP contains upper case characters (excluding those preceded by `\\'),
615the matching is case-sensitive.
616
617Second and third arg RSTART and REND specify the region to operate on.
618
619Interactively, in Transient Mark mode when the mark is active, operate
620on the contents of the region. Otherwise, operate from point to the
621end of the buffer."
622
623 (interactive
624 (keep-lines-read-args "How many matches for (regexp): "))
625 (save-excursion
626 (if rstart
627 (goto-char (min rstart rend))
628 (if (and transient-mark-mode mark-active)
629 (setq rstart (region-beginning)
630 rend (copy-marker (region-end)))
631 (setq rstart (point)
632 rend (point-max-marker)))
633 (goto-char rstart))
634 (let ((count 0)
635 opoint
636 (case-fold-search (and case-fold-search
637 (isearch-no-upper-case-p regexp t))))
638 (while (and (< (point) rend)
639 (progn (setq opoint (point))
640 (re-search-forward regexp rend t)))
641 (if (= opoint (point))
642 (forward-char 1)
643 (setq count (1+ count))))
644 (message "%d occurrences" count))))
645
646\f
647(defvar occur-mode-map
648 (let ((map (make-sparse-keymap)))
649 (define-key map [mouse-2] 'occur-mode-mouse-goto)
650 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
651 (define-key map "\C-m" 'occur-mode-goto-occurrence)
652 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
653 (define-key map "\C-o" 'occur-mode-display-occurrence)
654 (define-key map "\M-n" 'occur-next)
655 (define-key map "\M-p" 'occur-prev)
656 (define-key map "r" 'occur-rename-buffer)
657 (define-key map "c" 'clone-buffer)
658 (define-key map "g" 'revert-buffer)
659 (define-key map "q" 'quit-window)
660 (define-key map "z" 'kill-this-buffer)
661 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
662 map)
663 "Keymap for `occur-mode'.")
664
665(defvar occur-revert-arguments nil
666 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
667See `occur-revert-function'.")
668
669(defcustom occur-mode-hook '(turn-on-font-lock)
670 "Hook run when entering Occur mode."
671 :type 'hook
672 :group 'matching)
673
674(defcustom occur-hook nil
675 "Hook run when `occur' is called."
676 :type 'hook
677 :group 'matching)
678
679(put 'occur-mode 'mode-class 'special)
680(defun occur-mode ()
681 "Major mode for output from \\[occur].
682\\<occur-mode-map>Move point to one of the items in this buffer, then use
683\\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
684Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
685
686\\{occur-mode-map}"
687 (interactive)
688 (kill-all-local-variables)
689 (use-local-map occur-mode-map)
690 (setq major-mode 'occur-mode)
691 (setq mode-name "Occur")
692 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
693 (make-local-variable 'occur-revert-arguments)
694 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
695 (setq next-error-function 'occur-next-error)
696 (run-hooks 'occur-mode-hook))
697
698(defun occur-revert-function (ignore1 ignore2)
699 "Handle `revert-buffer' for Occur mode buffers."
700 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
701
702(defun occur-mode-mouse-goto (event)
703 "In Occur mode, go to the occurrence whose line you click on."
704 (interactive "e")
705 (let (pos)
706 (save-excursion
707 (set-buffer (window-buffer (posn-window (event-end event))))
708 (save-excursion
709 (goto-char (posn-point (event-end event)))
710 (setq pos (occur-mode-find-occurrence))))
711 (pop-to-buffer (marker-buffer pos))
712 (goto-char pos)))
713
714(defun occur-mode-find-occurrence ()
715 (let ((pos (get-text-property (point) 'occur-target)))
716 (unless pos
717 (error "No occurrence on this line"))
718 (unless (buffer-live-p (marker-buffer pos))
719 (error "Buffer for this occurrence was killed"))
720 pos))
721
722(defun occur-mode-goto-occurrence ()
723 "Go to the occurrence the current line describes."
724 (interactive)
725 (let ((pos (occur-mode-find-occurrence)))
726 (pop-to-buffer (marker-buffer pos))
727 (goto-char pos)))
728
729(defun occur-mode-goto-occurrence-other-window ()
730 "Go to the occurrence the current line describes, in another window."
731 (interactive)
732 (let ((pos (occur-mode-find-occurrence)))
733 (switch-to-buffer-other-window (marker-buffer pos))
734 (goto-char pos)))
735
736(defun occur-mode-display-occurrence ()
737 "Display in another window the occurrence the current line describes."
738 (interactive)
739 (let ((pos (occur-mode-find-occurrence))
740 window
741 ;; Bind these to ensure `display-buffer' puts it in another window.
742 same-window-buffer-names
743 same-window-regexps)
744 (setq window (display-buffer (marker-buffer pos)))
745 ;; This is the way to set point in the proper window.
746 (save-selected-window
747 (select-window window)
748 (goto-char pos))))
749
750(defun occur-find-match (n search message)
751 (if (not n) (setq n 1))
752 (let ((r))
753 (while (> n 0)
754 (setq r (funcall search (point) 'occur-match))
755 (and r
756 (get-text-property r 'occur-match)
757 (setq r (funcall search r 'occur-match)))
758 (if r
759 (goto-char r)
760 (error message))
761 (setq n (1- n)))))
762
763(defun occur-next (&optional n)
764 "Move to the Nth (default 1) next match in an Occur mode buffer."
765 (interactive "p")
766 (occur-find-match n #'next-single-property-change "No more matches"))
767
768(defun occur-prev (&optional n)
769 "Move to the Nth (default 1) previous match in an Occur mode buffer."
770 (interactive "p")
771 (occur-find-match n #'previous-single-property-change "No earlier matches"))
772
773(defun occur-next-error (&optional argp reset)
774 "Move to the Nth (default 1) next match in an Occur mode buffer.
775Compatibility function for \\[next-error] invocations."
776 (interactive "p")
777 ;; we need to run occur-find-match from within the Occur buffer
778 (with-current-buffer
779 ;; Choose the buffer and make it current.
780 (if (next-error-buffer-p (current-buffer))
781 (current-buffer)
782 (next-error-find-buffer nil nil
783 (lambda ()
784 (eq major-mode 'occur-mode))))
785
786 (goto-char (cond (reset (point-min))
787 ((< argp 0) (line-beginning-position))
788 ((line-end-position))))
789 (occur-find-match
790 (abs argp)
791 (if (> 0 argp)
792 #'previous-single-property-change
793 #'next-single-property-change)
794 "No more matches")
795 ;; In case the *Occur* buffer is visible in a nonselected window.
796 (set-window-point (get-buffer-window (current-buffer)) (point))
797 (occur-mode-goto-occurrence)))
798\f
799(defface match
800 '((((class color) (min-colors 88) (background light))
801 :background "Tan")
802 (((class color) (min-colors 88) (background dark))
803 :background "RoyalBlue4")
804 (((class color) (min-colors 8))
805 :background "blue" :foreground "white")
806 (((type tty) (class mono))
807 :inverse-video t)
808 (t :background "gray"))
809 "Face used to highlight matches permanently."
810 :group 'matching
811 :version "22.1")
812
813(defcustom list-matching-lines-default-context-lines 0
814 "*Default number of context lines included around `list-matching-lines' matches.
815A negative number means to include that many lines before the match.
816A positive number means to include that many lines both before and after."
817 :type 'integer
818 :group 'matching)
819
820(defalias 'list-matching-lines 'occur)
821
822(defcustom list-matching-lines-face 'match
823 "*Face used by \\[list-matching-lines] to show the text that matches.
824If the value is nil, don't highlight the matching portions specially."
825 :type 'face
826 :group 'matching)
827
828(defcustom list-matching-lines-buffer-name-face 'underline
829 "*Face used by \\[list-matching-lines] to show the names of buffers.
830If the value is nil, don't highlight the buffer names specially."
831 :type 'face
832 :group 'matching)
833
834(defun occur-accumulate-lines (count &optional keep-props)
835 (save-excursion
836 (let ((forwardp (> count 0))
837 result beg end)
838 (while (not (or (zerop count)
839 (if forwardp
840 (eobp)
841 (bobp))))
842 (setq count (+ count (if forwardp -1 1)))
843 (setq beg (line-beginning-position)
844 end (line-end-position))
845 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
846 (text-property-not-all beg end 'fontified t))
847 (if (fboundp 'jit-lock-fontify-now)
848 (jit-lock-fontify-now beg end)))
849 (push
850 (funcall (if keep-props
851 #'buffer-substring
852 #'buffer-substring-no-properties)
853 beg end)
854 result)
855 (forward-line (if forwardp 1 -1)))
856 (nreverse result))))
857
858(defun occur-read-primary-args ()
859 (list (let* ((default (car regexp-history))
860 (input
861 (read-from-minibuffer
862 (if default
863 (format "List lines matching regexp (default `%s'): "
864 (query-replace-descr default))
865 "List lines matching regexp: ")
866 nil
867 nil
868 nil
869 'regexp-history
870 default)))
871 (if (equal input "")
872 default
873 input))
874 (when current-prefix-arg
875 (prefix-numeric-value current-prefix-arg))))
876
877(defun occur-rename-buffer (&optional unique-p)
878 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
879Here `original-buffer-name' is the buffer name were occur was originally run.
880When given the prefix argument, the renaming will not clobber the existing
881buffer(s) of that name, but use `generate-new-buffer-name' instead.
882You can add this to `occur-hook' if you always want a separate *Occur*
883buffer for each buffer where you invoke `occur'."
884 (interactive "P")
885 (with-current-buffer
886 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
887 (rename-buffer (concat "*Occur: "
888 (mapconcat #'buffer-name
889 (car (cddr occur-revert-arguments)) "/")
890 "*")
891 unique-p)))
892
893(defun occur (regexp &optional nlines)
894 "Show all lines in the current buffer containing a match for REGEXP.
895
896If a match spreads across multiple lines, all those lines are shown.
897
898Each line is displayed with NLINES lines before and after, or -NLINES
899before if NLINES is negative.
900NLINES defaults to `list-matching-lines-default-context-lines'.
901Interactively it is the prefix arg.
902
903The lines are shown in a buffer named `*Occur*'.
904It serves as a menu to find any of the occurrences in this buffer.
905\\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
906
907If REGEXP contains upper case characters (excluding those preceded by `\\'),
908the matching is case-sensitive."
909 (interactive (occur-read-primary-args))
910 (occur-1 regexp nlines (list (current-buffer))))
911
912(defun multi-occur (bufs regexp &optional nlines)
913 "Show all lines in buffers BUFS containing a match for REGEXP.
914This function acts on multiple buffers; otherwise, it is exactly like
915`occur'."
916 (interactive
917 (cons
918 (let* ((bufs (list (read-buffer "First buffer to search: "
919 (current-buffer) t)))
920 (buf nil)
921 (ido-ignore-item-temp-list bufs))
922 (while (not (string-equal
923 (setq buf (read-buffer
924 (if (eq read-buffer-function 'ido-read-buffer)
925 "Next buffer to search (C-j to end): "
926 "Next buffer to search (RET to end): ")
927 nil t))
928 ""))
929 (add-to-list 'bufs buf)
930 (setq ido-ignore-item-temp-list bufs))
931 (nreverse (mapcar #'get-buffer bufs)))
932 (occur-read-primary-args)))
933 (occur-1 regexp nlines bufs))
934
935(defun multi-occur-by-filename-regexp (bufregexp regexp &optional nlines)
936 "Show all lines matching REGEXP in buffers named by BUFREGEXP.
937See also `multi-occur'."
938 (interactive
939 (cons
940 (let* ((default (car regexp-history))
941 (input
942 (read-from-minibuffer
943 "List lines in buffers whose filename matches regexp: "
944 nil
945 nil
946 nil
947 'regexp-history)))
948 (if (equal input "")
949 default
950 input))
951 (occur-read-primary-args)))
952 (when bufregexp
953 (occur-1 regexp nlines
954 (delq nil
955 (mapcar (lambda (buf)
956 (when (and (buffer-file-name buf)
957 (string-match bufregexp
958 (buffer-file-name buf)))
959 buf))
960 (buffer-list))))))
961
962(defun occur-1 (regexp nlines bufs &optional buf-name)
963 (unless buf-name
964 (setq buf-name "*Occur*"))
965 (let (occur-buf
966 (active-bufs (delq nil (mapcar #'(lambda (buf)
967 (when (buffer-live-p buf) buf))
968 bufs))))
969 ;; Handle the case where one of the buffers we're searching is the
970 ;; output buffer. Just rename it.
971 (when (member buf-name (mapcar 'buffer-name active-bufs))
972 (with-current-buffer (get-buffer buf-name)
973 (rename-uniquely)))
974
975 ;; Now find or create the output buffer.
976 ;; If we just renamed that buffer, we will make a new one here.
977 (setq occur-buf (get-buffer-create buf-name))
978
979 (with-current-buffer occur-buf
980 (setq buffer-read-only nil)
981 (occur-mode)
982 (erase-buffer)
983 (let ((count (occur-engine
984 regexp active-bufs occur-buf
985 (or nlines list-matching-lines-default-context-lines)
986 (and case-fold-search
987 (isearch-no-upper-case-p regexp t))
988 list-matching-lines-buffer-name-face
989 nil list-matching-lines-face t)))
990 (let* ((bufcount (length active-bufs))
991 (diff (- (length bufs) bufcount)))
992 (message "Searched %d buffer%s%s; %s match%s for `%s'"
993 bufcount (if (= bufcount 1) "" "s")
994 (if (zerop diff) "" (format " (%d killed)" diff))
995 (if (zerop count) "no" (format "%d" count))
996 (if (= count 1) "" "es")
997 regexp))
998 (setq occur-revert-arguments (list regexp nlines bufs)
999 buffer-read-only t)
1000 (if (> count 0)
1001 (progn
1002 (display-buffer occur-buf)
1003 (setq next-error-last-buffer occur-buf))
1004 (kill-buffer occur-buf)))
1005 (run-hooks 'occur-hook))))
1006
1007(defun occur-engine-add-prefix (lines)
1008 (mapcar
1009 #'(lambda (line)
1010 (concat " :" line "\n"))
1011 lines))
1012
1013(defun occur-engine (regexp buffers out-buf nlines case-fold-search
1014 title-face prefix-face match-face keep-props)
1015 (with-current-buffer out-buf
1016 (setq buffer-read-only nil)
1017 (let ((globalcount 0)
1018 (coding nil))
1019 ;; Map over all the buffers
1020 (dolist (buf buffers)
1021 (when (buffer-live-p buf)
1022 (let ((matches 0) ;; count of matched lines
1023 (lines 1) ;; line count
1024 (matchbeg 0)
1025 (origpt nil)
1026 (begpt nil)
1027 (endpt nil)
1028 (marker nil)
1029 (curstring "")
1030 (headerpt (with-current-buffer out-buf (point))))
1031 (save-excursion
1032 (set-buffer buf)
1033 (or coding
1034 ;; Set CODING only if the current buffer locally
1035 ;; binds buffer-file-coding-system.
1036 (not (local-variable-p 'buffer-file-coding-system))
1037 (setq coding buffer-file-coding-system))
1038 (save-excursion
1039 (goto-char (point-min)) ;; begin searching in the buffer
1040 (while (not (eobp))
1041 (setq origpt (point))
1042 (when (setq endpt (re-search-forward regexp nil t))
1043 (setq matches (1+ matches)) ;; increment match count
1044 (setq matchbeg (match-beginning 0))
1045 (setq lines (+ lines (1- (count-lines origpt endpt))))
1046 (save-excursion
1047 (goto-char matchbeg)
1048 (setq begpt (line-beginning-position)
1049 endpt (line-end-position)))
1050 (setq marker (make-marker))
1051 (set-marker marker matchbeg)
1052 (if (and keep-props
1053 (if (boundp 'jit-lock-mode) jit-lock-mode)
1054 (text-property-not-all begpt endpt 'fontified t))
1055 (if (fboundp 'jit-lock-fontify-now)
1056 (jit-lock-fontify-now begpt endpt)))
1057 (setq curstring (buffer-substring begpt endpt))
1058 ;; Depropertize the string, and maybe
1059 ;; highlight the matches
1060 (let ((len (length curstring))
1061 (start 0))
1062 (unless keep-props
1063 (set-text-properties 0 len nil curstring))
1064 (while (and (< start len)
1065 (string-match regexp curstring start))
1066 (add-text-properties
1067 (match-beginning 0) (match-end 0)
1068 (append
1069 `(occur-match t)
1070 (when match-face
1071 ;; Use `face' rather than `font-lock-face' here
1072 ;; so as to override faces copied from the buffer.
1073 `(face ,match-face)))
1074 curstring)
1075 (setq start (match-end 0))))
1076 ;; Generate the string to insert for this match
1077 (let* ((out-line
1078 (concat
1079 ;; Using 7 digits aligns tabs properly.
1080 (apply #'propertize (format "%7d:" lines)
1081 (append
1082 (when prefix-face
1083 `(font-lock-face prefix-face))
1084 '(occur-prefix t)))
1085 ;; We don't put `mouse-face' on the newline,
1086 ;; because that loses. And don't put it
1087 ;; on context lines to reduce flicker.
1088 (propertize curstring 'mouse-face 'highlight)
1089 "\n"))
1090 (data
1091 (if (= nlines 0)
1092 ;; The simple display style
1093 out-line
1094 ;; The complex multi-line display
1095 ;; style. Generate a list of lines,
1096 ;; concatenate them all together.
1097 (apply #'concat
1098 (nconc
1099 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ (abs nlines))) keep-props))))
1100 (list out-line)
1101 (if (> nlines 0)
1102 (occur-engine-add-prefix
1103 (cdr (occur-accumulate-lines (1+ nlines) keep-props)))))))))
1104 ;; Actually insert the match display data
1105 (with-current-buffer out-buf
1106 (let ((beg (point))
1107 (end (progn (insert data) (point))))
1108 (unless (= nlines 0)
1109 (insert "-------\n"))
1110 (add-text-properties
1111 beg end
1112 `(occur-target ,marker help-echo "mouse-2: go to this occurrence")))))
1113 (goto-char endpt))
1114 (if endpt
1115 (progn
1116 (setq lines (1+ lines))
1117 ;; On to the next match...
1118 (forward-line 1))
1119 (goto-char (point-max))))))
1120 (when (not (zerop matches)) ;; is the count zero?
1121 (setq globalcount (+ globalcount matches))
1122 (with-current-buffer out-buf
1123 (goto-char headerpt)
1124 (let ((beg (point))
1125 end)
1126 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1127 matches (if (= matches 1) "" "es")
1128 regexp (buffer-name buf)))
1129 (setq end (point))
1130 (add-text-properties beg end
1131 (append
1132 (when title-face
1133 `(font-lock-face ,title-face))
1134 `(occur-title ,buf))))
1135 (goto-char (point-min)))))))
1136 (if coding
1137 ;; CODING is buffer-file-coding-system of the first buffer
1138 ;; that locally binds it. Let's use it also for the output
1139 ;; buffer.
1140 (set-buffer-file-coding-system coding))
1141 ;; Return the number of matches
1142 globalcount)))
1143
1144\f
1145;; It would be nice to use \\[...], but there is no reasonable way
1146;; to make that display both SPC and Y.
1147(defconst query-replace-help
1148 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1149RET or `q' to exit, Period to replace one match and exit,
1150Comma to replace but not move point immediately,
1151C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1152C-w to delete match and recursive edit,
1153C-l to clear the screen, redisplay, and offer same replacement again,
1154! to replace all remaining matches with no more questions,
1155^ to move point back to previous match,
1156E to edit the replacement string"
1157 "Help message while in `query-replace'.")
1158
1159(defvar query-replace-map (make-sparse-keymap)
1160 "Keymap that defines the responses to questions in `query-replace'.
1161The \"bindings\" in this map are not commands; they are answers.
1162The valid answers include `act', `skip', `act-and-show',
1163`exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1164`automatic', `backup', `exit-prefix', and `help'.")
1165
1166(define-key query-replace-map " " 'act)
1167(define-key query-replace-map "\d" 'skip)
1168(define-key query-replace-map [delete] 'skip)
1169(define-key query-replace-map [backspace] 'skip)
1170(define-key query-replace-map "y" 'act)
1171(define-key query-replace-map "n" 'skip)
1172(define-key query-replace-map "Y" 'act)
1173(define-key query-replace-map "N" 'skip)
1174(define-key query-replace-map "e" 'edit-replacement)
1175(define-key query-replace-map "E" 'edit-replacement)
1176(define-key query-replace-map "," 'act-and-show)
1177(define-key query-replace-map "q" 'exit)
1178(define-key query-replace-map "\r" 'exit)
1179(define-key query-replace-map [return] 'exit)
1180(define-key query-replace-map "." 'act-and-exit)
1181(define-key query-replace-map "\C-r" 'edit)
1182(define-key query-replace-map "\C-w" 'delete-and-edit)
1183(define-key query-replace-map "\C-l" 'recenter)
1184(define-key query-replace-map "!" 'automatic)
1185(define-key query-replace-map "^" 'backup)
1186(define-key query-replace-map "\C-h" 'help)
1187(define-key query-replace-map [f1] 'help)
1188(define-key query-replace-map [help] 'help)
1189(define-key query-replace-map "?" 'help)
1190(define-key query-replace-map "\C-g" 'quit)
1191(define-key query-replace-map "\C-]" 'quit)
1192(define-key query-replace-map "\e" 'exit-prefix)
1193(define-key query-replace-map [escape] 'exit-prefix)
1194
1195(defun replace-match-string-symbols (n)
1196 "Process a list (and any sub-lists), expanding certain symbols.
1197Symbol Expands To
1198N (match-string N) (where N is a string of digits)
1199#N (string-to-number (match-string N))
1200& (match-string 0)
1201#& (string-to-number (match-string 0))
1202# replace-count
1203
1204Note that these symbols must be preceeded by a backslash in order to
1205type them."
1206 (while n
1207 (cond
1208 ((consp (car n))
1209 (replace-match-string-symbols (car n))) ;Process sub-list
1210 ((symbolp (car n))
1211 (let ((name (symbol-name (car n))))
1212 (cond
1213 ((string-match "^[0-9]+$" name)
1214 (setcar n (list 'match-string (string-to-number name))))
1215 ((string-match "^#[0-9]+$" name)
1216 (setcar n (list 'string-to-number
1217 (list 'match-string
1218 (string-to-number (substring name 1))))))
1219 ((string= "&" name)
1220 (setcar n '(match-string 0)))
1221 ((string= "#&" name)
1222 (setcar n '(string-to-number (match-string 0))))
1223 ((string= "#" name)
1224 (setcar n 'replace-count))))))
1225 (setq n (cdr n))))
1226
1227(defun replace-eval-replacement (expression replace-count)
1228 (let ((replacement (eval expression)))
1229 (if (stringp replacement)
1230 replacement
1231 (prin1-to-string replacement t))))
1232
1233(defun replace-quote (replacement)
1234 "Quote a replacement string.
1235This just doubles all backslashes in REPLACEMENT and
1236returns the resulting string. If REPLACEMENT is not
1237a string, it is first passed through `prin1-to-string'
1238with the `noescape' argument set.
1239
1240`match-data' is preserved across the call."
1241 (save-match-data
1242 (replace-regexp-in-string "\\\\" "\\\\"
1243 (if (stringp replacement)
1244 replacement
1245 (prin1-to-string replacement t))
1246 t t)))
1247
1248(defun replace-loop-through-replacements (data replace-count)
1249 ;; DATA is a vector contaning the following values:
1250 ;; 0 next-rotate-count
1251 ;; 1 repeat-count
1252 ;; 2 next-replacement
1253 ;; 3 replacements
1254 (if (= (aref data 0) replace-count)
1255 (progn
1256 (aset data 0 (+ replace-count (aref data 1)))
1257 (let ((next (cdr (aref data 2))))
1258 (aset data 2 (if (consp next) next (aref data 3))))))
1259 (car (aref data 2)))
1260
1261(defun replace-match-data (integers reuse &optional new)
1262 "Like `match-data', but markers in REUSE get invalidated.
1263If NEW is non-NIL, it is set and returned instead of fresh data,
1264but coerced to the correct value of INTEGERS."
1265 (or (and new
1266 (progn
1267 (set-match-data new)
1268 (and (eq new reuse)
1269 (eq (null integers) (markerp (car reuse)))
1270 new)))
1271 (match-data integers
1272 (prog1 reuse
1273 (while reuse
1274 (if (markerp (car reuse))
1275 (set-marker (car reuse) nil))
1276 (setq reuse (cdr reuse)))))))
1277
1278(defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1279 "Make a replacement with `replace-match', editing `\\?'.
1280NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1281check for `\\?' is made to save time. MATCH-DATA is used for the
1282replacement. In case editing is done, it is changed to use markers.
1283
1284The return value is non-NIL if there has been no `\\?' or NOEDIT was
1285passed in. If LITERAL is set, no checking is done, anyway."
1286 (unless (or literal noedit)
1287 (setq noedit t)
1288 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1289 newtext)
1290 (setq newtext
1291 (read-input "Edit replacement string: "
1292 (prog1
1293 (cons
1294 (replace-match "" t t newtext 3)
1295 (1+ (match-beginning 3)))
1296 (setq match-data
1297 (replace-match-data
1298 nil match-data match-data))))
1299 noedit nil)))
1300 (set-match-data match-data)
1301 (replace-match newtext fixedcase literal)
1302 noedit)
1303
1304(defun perform-replace (from-string replacements
1305 query-flag regexp-flag delimited-flag
1306 &optional repeat-count map start end)
1307 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1308Don't use this in your own program unless you want to query and set the mark
1309just as `query-replace' does. Instead, write a simple loop like this:
1310
1311 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1312 (replace-match \"foobar\" nil nil))
1313
1314which will run faster and probably do exactly what you want. Please
1315see the documentation of `replace-match' to find out how to simulate
1316`case-replace'.
1317
1318This function returns nil if and only if there were no matches to
1319make, or the user didn't cancel the call."
1320 (or map (setq map query-replace-map))
1321 (and query-flag minibuffer-auto-raise
1322 (raise-frame (window-frame (minibuffer-window))))
1323 (let ((nocasify (not (and case-fold-search case-replace
1324 (string-equal from-string
1325 (downcase from-string)))))
1326 (case-fold-search (and case-fold-search
1327 (string-equal from-string
1328 (downcase from-string))))
1329 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1330 (search-function (if regexp-flag 're-search-forward 'search-forward))
1331 (search-string from-string)
1332 (real-match-data nil) ; the match data for the current match
1333 (next-replacement nil)
1334 (noedit nil)
1335 (keep-going t)
1336 (stack nil)
1337 (replace-count 0)
1338 (nonempty-match nil)
1339
1340 ;; If non-nil, it is marker saying where in the buffer to stop.
1341 (limit nil)
1342
1343 ;; Data for the next match. If a cons, it has the same format as
1344 ;; (match-data); otherwise it is t if a match is possible at point.
1345 (match-again t)
1346
1347 (message
1348 (if query-flag
1349 (substitute-command-keys
1350 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
1351
1352 ;; If region is active, in Transient Mark mode, operate on region.
1353 (when start
1354 (setq limit (copy-marker (max start end)))
1355 (goto-char (min start end))
1356 (deactivate-mark))
1357
1358 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1359 ;; containing a function and its first argument. The function is
1360 ;; called to generate each replacement like this:
1361 ;; (funcall (car replacements) (cdr replacements) replace-count)
1362 ;; It must return a string.
1363 (cond
1364 ((stringp replacements)
1365 (setq next-replacement replacements
1366 replacements nil))
1367 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1368 (or repeat-count (setq repeat-count 1))
1369 (setq replacements (cons 'replace-loop-through-replacements
1370 (vector repeat-count repeat-count
1371 replacements replacements)))))
1372
1373 (if delimited-flag
1374 (setq search-function 're-search-forward
1375 search-string (concat "\\b"
1376 (if regexp-flag from-string
1377 (regexp-quote from-string))
1378 "\\b")))
1379 (when query-replace-lazy-highlight
1380 (setq isearch-lazy-highlight-last-string nil))
1381
1382 (push-mark)
1383 (undo-boundary)
1384 (unwind-protect
1385 ;; Loop finding occurrences that perhaps should be replaced.
1386 (while (and keep-going
1387 (not (or (eobp) (and limit (>= (point) limit))))
1388 ;; Use the next match if it is already known;
1389 ;; otherwise, search for a match after moving forward
1390 ;; one char if progress is required.
1391 (setq real-match-data
1392 (if (consp match-again)
1393 (progn (goto-char (nth 1 match-again))
1394 (replace-match-data t
1395 real-match-data
1396 match-again))
1397 (and (or match-again
1398 ;; MATCH-AGAIN non-nil means we
1399 ;; accept an adjacent match. If
1400 ;; we don't, move one char to the
1401 ;; right. This takes us a
1402 ;; character too far at the end,
1403 ;; but this is undone after the
1404 ;; while-loop.
1405 (progn
1406 (forward-char 1)
1407 (not (or (eobp)
1408 (and limit (>= (point) limit))))))
1409 (funcall search-function search-string limit t)
1410 ;; For speed, use only integers and
1411 ;; reuse the list used last time.
1412 (replace-match-data t real-match-data)))))
1413 ;; Optionally ignore matches that have a read-only property.
1414 (unless (and query-replace-skip-read-only
1415 (text-property-not-all
1416 (match-beginning 0) (match-end 0)
1417 'read-only nil))
1418
1419 ;; Record whether the match is nonempty, to avoid an infinite loop
1420 ;; repeatedly matching the same empty string.
1421 (setq nonempty-match
1422 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1423
1424 ;; If the match is empty, record that the next one can't be
1425 ;; adjacent.
1426
1427 ;; Otherwise, if matching a regular expression, do the next
1428 ;; match now, since the replacement for this match may
1429 ;; affect whether the next match is adjacent to this one.
1430 ;; If that match is empty, don't use it.
1431 (setq match-again
1432 (and nonempty-match
1433 (or (not regexp-flag)
1434 (and (looking-at search-string)
1435 (let ((match (match-data)))
1436 (and (/= (nth 0 match) (nth 1 match))
1437 match))))))
1438
1439 ;; Calculate the replacement string, if necessary.
1440 (when replacements
1441 (set-match-data real-match-data)
1442 (setq next-replacement
1443 (funcall (car replacements) (cdr replacements)
1444 replace-count)
1445 noedit nil))
1446 (if (not query-flag)
1447 (let ((inhibit-read-only
1448 query-replace-skip-read-only))
1449 (unless (or literal noedit)
1450 (replace-highlight
1451 (nth 0 real-match-data) (nth 1 real-match-data)
1452 start end search-string
1453 (or delimited-flag regexp-flag) case-fold-search))
1454 (setq noedit
1455 (replace-match-maybe-edit
1456 next-replacement nocasify literal
1457 noedit real-match-data)
1458 replace-count (1+ replace-count)))
1459 (undo-boundary)
1460 (let (done replaced key def)
1461 ;; Loop reading commands until one of them sets done,
1462 ;; which means it has finished handling this
1463 ;; occurrence. Any command that sets `done' should
1464 ;; leave behind proper match data for the stack.
1465 ;; Commands not setting `done' need to adjust
1466 ;; `real-match-data'.
1467 (while (not done)
1468 (set-match-data real-match-data)
1469 (replace-highlight
1470 (match-beginning 0) (match-end 0)
1471 start end search-string
1472 (or delimited-flag regexp-flag) case-fold-search)
1473 ;; Bind message-log-max so we don't fill up the message log
1474 ;; with a bunch of identical messages.
1475 (let ((message-log-max nil))
1476 (message message
1477 (query-replace-descr from-string)
1478 (query-replace-descr next-replacement)))
1479 (setq key (read-event))
1480 ;; Necessary in case something happens during read-event
1481 ;; that clobbers the match data.
1482 (set-match-data real-match-data)
1483 (setq key (vector key))
1484 (setq def (lookup-key map key))
1485 ;; Restore the match data while we process the command.
1486 (cond ((eq def 'help)
1487 (with-output-to-temp-buffer "*Help*"
1488 (princ
1489 (concat "Query replacing "
1490 (if regexp-flag "regexp " "")
1491 from-string " with "
1492 next-replacement ".\n\n"
1493 (substitute-command-keys
1494 query-replace-help)))
1495 (with-current-buffer standard-output
1496 (help-mode))))
1497 ((eq def 'exit)
1498 (setq keep-going nil)
1499 (setq done t))
1500 ((eq def 'backup)
1501 (if stack
1502 (let ((elt (pop stack)))
1503 (goto-char (nth 0 elt))
1504 (setq replaced (nth 1 elt)
1505 real-match-data
1506 (replace-match-data
1507 t real-match-data
1508 (nth 2 elt))))
1509 (message "No previous match")
1510 (ding 'no-terminate)
1511 (sit-for 1)))
1512 ((eq def 'act)
1513 (or replaced
1514 (setq noedit
1515 (replace-match-maybe-edit
1516 next-replacement nocasify literal
1517 noedit real-match-data)
1518 replace-count (1+ replace-count)))
1519 (setq done t replaced t))
1520 ((eq def 'act-and-exit)
1521 (or replaced
1522 (setq noedit
1523 (replace-match-maybe-edit
1524 next-replacement nocasify literal
1525 noedit real-match-data)
1526 replace-count (1+ replace-count)))
1527 (setq keep-going nil)
1528 (setq done t replaced t))
1529 ((eq def 'act-and-show)
1530 (if (not replaced)
1531 (setq noedit
1532 (replace-match-maybe-edit
1533 next-replacement nocasify literal
1534 noedit real-match-data)
1535 replace-count (1+ replace-count)
1536 real-match-data (replace-match-data
1537 t real-match-data)
1538 replaced t)))
1539 ((eq def 'automatic)
1540 (or replaced
1541 (setq noedit
1542 (replace-match-maybe-edit
1543 next-replacement nocasify literal
1544 noedit real-match-data)
1545 replace-count (1+ replace-count)))
1546 (setq done t query-flag nil replaced t))
1547 ((eq def 'skip)
1548 (setq done t))
1549 ((eq def 'recenter)
1550 (recenter nil))
1551 ((eq def 'edit)
1552 (let ((opos (point-marker)))
1553 (setq real-match-data (replace-match-data
1554 nil real-match-data
1555 real-match-data))
1556 (goto-char (match-beginning 0))
1557 (save-excursion
1558 (save-window-excursion
1559 (recursive-edit)))
1560 (goto-char opos)
1561 (set-marker opos nil))
1562 ;; Before we make the replacement,
1563 ;; decide whether the search string
1564 ;; can match again just after this match.
1565 (if (and regexp-flag nonempty-match)
1566 (setq match-again (and (looking-at search-string)
1567 (match-data)))))
1568 ;; Edit replacement.
1569 ((eq def 'edit-replacement)
1570 (setq real-match-data (replace-match-data
1571 nil real-match-data
1572 real-match-data)
1573 next-replacement
1574 (read-input "Edit replacement string: "
1575 next-replacement)
1576 noedit nil)
1577 (if replaced
1578 (set-match-data real-match-data)
1579 (setq noedit
1580 (replace-match-maybe-edit
1581 next-replacement nocasify literal noedit
1582 real-match-data)
1583 replaced t))
1584 (setq done t))
1585
1586 ((eq def 'delete-and-edit)
1587 (replace-match "" t t)
1588 (setq real-match-data (replace-match-data
1589 nil real-match-data))
1590 (replace-dehighlight)
1591 (save-excursion (recursive-edit))
1592 (setq replaced t))
1593 ;; Note: we do not need to treat `exit-prefix'
1594 ;; specially here, since we reread
1595 ;; any unrecognized character.
1596 (t
1597 (setq this-command 'mode-exited)
1598 (setq keep-going nil)
1599 (setq unread-command-events
1600 (append (listify-key-sequence key)
1601 unread-command-events))
1602 (setq done t)))
1603 (when query-replace-lazy-highlight
1604 ;; Force lazy rehighlighting only after replacements
1605 (if (not (memq def '(skip backup)))
1606 (setq isearch-lazy-highlight-last-string nil))))
1607 ;; Record previous position for ^ when we move on.
1608 ;; Change markers to numbers in the match data
1609 ;; since lots of markers slow down editing.
1610 (push (list (point) replaced
1611;;; If the replacement has already happened, all we need is the
1612;;; current match start and end. We could get this with a trivial
1613;;; match like
1614;;; (save-excursion (goto-char (match-beginning 0))
1615;;; (search-forward (match-string 0))
1616;;; (match-data t))
1617;;; if we really wanted to avoid manually constructing match data.
1618;;; Adding current-buffer is necessary so that match-data calls can
1619;;; return markers which are appropriate for editing.
1620 (if replaced
1621 (list
1622 (match-beginning 0)
1623 (match-end 0)
1624 (current-buffer))
1625 (match-data t)))
1626 stack)))))
1627
1628 ;; The code preventing adjacent regexp matches in the condition
1629 ;; of the while-loop above will haven taken us one character
1630 ;; beyond the last replacement. Undo that.
1631 (when (and regexp-flag (not match-again) (> replace-count 0))
1632 (backward-char 1))
1633
1634 (replace-dehighlight))
1635 (or unread-command-events
1636 (message "Replaced %d occurrence%s"
1637 replace-count
1638 (if (= replace-count 1) "" "s")))
1639 (and keep-going stack)))
1640
1641(defvar replace-overlay nil)
1642
1643(defun replace-highlight (match-beg match-end range-beg range-end
1644 string regexp case-fold)
1645 (if query-replace-highlight
1646 (if replace-overlay
1647 (move-overlay replace-overlay match-beg match-end (current-buffer))
1648 (setq replace-overlay (make-overlay match-beg match-end))
1649 (overlay-put replace-overlay 'priority 1) ;higher than lazy overlays
1650 (overlay-put replace-overlay 'face 'query-replace)))
1651 (if query-replace-lazy-highlight
1652 (let ((isearch-string string)
1653 (isearch-regexp regexp)
1654 (isearch-case-fold-search case-fold))
1655 (isearch-lazy-highlight-new-loop range-beg range-end))))
1656
1657(defun replace-dehighlight ()
1658 (when replace-overlay
1659 (delete-overlay replace-overlay))
1660 (when query-replace-lazy-highlight
1661 (lazy-highlight-cleanup lazy-highlight-cleanup)
1662 (setq isearch-lazy-highlight-last-string nil)))
1663
1664;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1665;;; replace.el ends here