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