Merge from emacs-23
[bpt/emacs.git] / lisp / replace.el
CommitLineData
60370d40 1;;; replace.el --- replace commands for Emacs
c88ab9ce 2
0d30b337 3;; Copyright (C) 1985, 1986, 1987, 1992, 1994, 1996, 1997, 2000, 2001,
5df4f04c 4;; 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
1e4bd40d 5;; Free Software Foundation, Inc.
3a801d0c 6
30764597 7;; Maintainer: FSF
bd78fa1d 8;; Package: emacs
30764597 9
698e1804
RS
10;; This file is part of GNU Emacs.
11
eb3fa2cf 12;; GNU Emacs is free software: you can redistribute it and/or modify
698e1804 13;; it under the terms of the GNU General Public License as published by
eb3fa2cf
GM
14;; the Free Software Foundation, either version 3 of the License, or
15;; (at your option) any later version.
698e1804
RS
16
17;; GNU Emacs is distributed in the hope that it will be useful,
18;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20;; GNU General Public License for more details.
21
22;; You should have received a copy of the GNU General Public License
eb3fa2cf 23;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
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
9201cc28 33 "Non-nil means `query-replace' should preserve case in replacements."
9d325ebf
RS
34 :type 'boolean
35 :group 'matching)
77176e73 36
84d0a5f8
GM
37(defvar query-replace-history nil
38 "Default history list for query-replace commands.
39See `query-replace-from-history-variable' and
40`query-replace-to-history-variable'.")
770970cb 41
6b59b130
CY
42(defvar query-replace-defaults nil
43 "Default values of FROM-STRING and TO-STRING for `query-replace'.
44This is a cons cell (FROM-STRING . TO-STRING), or nil if there is
45no default value.")
46
5291cbca 47(defvar query-replace-interactive nil
151270f3 48 "Non-nil means `query-replace' uses the last search string.
5291cbca 49That becomes the \"string to replace\".")
151270f3 50
bdb1c08f 51(defcustom query-replace-from-history-variable 'query-replace-history
f54701d1 52 "History list to use for the FROM argument of `query-replace' commands.
bdb1c08f
RS
53The value of this variable should be a symbol; that symbol
54is used as a variable to hold a history list for the strings
55or patterns to be replaced."
56 :group 'matching
cd32a7ba
DN
57 :type 'symbol
58 :version "20.3")
bdb1c08f
RS
59
60(defcustom query-replace-to-history-variable 'query-replace-history
f54701d1 61 "History list to use for the TO argument of `query-replace' commands.
bdb1c08f
RS
62The value of this variable should be a symbol; that symbol
63is used as a variable to hold a history list for replacement
64strings or patterns."
65 :group 'matching
cd32a7ba
DN
66 :type 'symbol
67 :version "20.3")
bdb1c08f 68
1c4fe319 69(defcustom query-replace-skip-read-only nil
9201cc28 70 "Non-nil means `query-replace' and friends ignore read-only matches."
1c4fe319
RS
71 :type 'boolean
72 :group 'matching
bf247b6e 73 :version "22.1")
1c4fe319 74
7abe68aa 75(defcustom query-replace-show-replacement t
9201cc28 76 "Non-nil means to show what actual replacement text will be."
7abe68aa
JL
77 :type 'boolean
78 :group 'matching
79 :version "23.1")
80
afd33362 81(defcustom query-replace-highlight t
9201cc28 82 "Non-nil means to highlight matches during query replacement."
afd33362
JL
83 :type 'boolean
84 :group 'matching)
85
86(defcustom query-replace-lazy-highlight t
9201cc28 87 "Controls the lazy-highlighting during query replacements.
afd33362
JL
88When non-nil, all text in the buffer matching the current match
89is highlighted lazily using isearch lazy highlighting (see
90`lazy-highlight-initial-delay' and `lazy-highlight-interval')."
91 :type 'boolean
92 :group 'lazy-highlight
93 :group 'matching
bf247b6e 94 :version "22.1")
afd33362
JL
95
96(defface query-replace
97 '((t (:inherit isearch)))
98 "Face for highlighting query replacement matches."
99 :group 'matching
bf247b6e 100 :version "22.1")
afd33362 101
6f1df6d9
SM
102(defun query-replace-descr (string)
103 (mapconcat 'isearch-text-char-description string ""))
104
90c9fc2a 105(defun query-replace-read-from (prompt regexp-flag)
6f1df6d9
SM
106 "Query and return the `from' argument of a query-replace operation.
107The return value can also be a pair (FROM . TO) indicating that the user
108wants to replace FROM with TO."
1606466a
SM
109 (if query-replace-interactive
110 (car (if regexp-flag regexp-search-ring search-ring))
2bf2b947
JL
111 (let* ((history-add-new-input nil)
112 (from
1606466a
SM
113 ;; The save-excursion here is in case the user marks and copies
114 ;; a region in order to specify the minibuffer input.
115 ;; That should not clobber the region for the query-replace itself.
116 (save-excursion
117 (read-from-minibuffer
6b59b130 118 (if query-replace-defaults
90c9fc2a 119 (format "%s (default %s -> %s): " prompt
6b59b130
CY
120 (query-replace-descr (car query-replace-defaults))
121 (query-replace-descr (cdr query-replace-defaults)))
90c9fc2a 122 (format "%s: " prompt))
1606466a
SM
123 nil nil nil
124 query-replace-from-history-variable
311f8bac 125 nil t))))
6b59b130 126 (if (and (zerop (length from)) query-replace-defaults)
5dae4b11
CY
127 (cons (car query-replace-defaults)
128 (query-replace-compile-replacement
129 (cdr query-replace-defaults) regexp-flag))
2bf2b947 130 (add-to-history query-replace-from-history-variable from nil t)
6f1df6d9
SM
131 ;; Warn if user types \n or \t, but don't reject the input.
132 (and regexp-flag
133 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
134 (let ((match (match-string 3 from)))
135 (cond
136 ((string= match "\\n")
137 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
138 ((string= match "\\t")
139 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
140 (sit-for 2)))
141 from))))
1606466a 142
78629844
DK
143(defun query-replace-compile-replacement (to regexp-flag)
144 "Maybe convert a regexp replacement TO to Lisp.
145Returns a list suitable for `perform-replace' if necessary,
146the original string if not."
147 (if (and regexp-flag
148 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
7c1c02ac
DK
149 (let (pos list char)
150 (while
151 (progn
152 (setq pos (match-end 0))
153 (push (substring to 0 (- pos 2)) list)
154 (setq char (aref to (1- pos))
155 to (substring to pos))
156 (cond ((eq char ?\#)
157 (push '(number-to-string replace-count) list))
158 ((eq char ?\,)
159 (setq pos (read-from-string to))
160 (push `(replace-quote ,(car pos)) list)
9e5d1b63
RS
161 (let ((end
162 ;; Swallow a space after a symbol
163 ;; if there is a space.
164 (if (and (or (symbolp (car pos))
165 ;; Swallow a space after 'foo
166 ;; but not after (quote foo).
167 (and (eq (car-safe (car pos)) 'quote)
f1f6079c
JL
168 (not (= ?\( (aref to 0)))))
169 (eq (string-match " " to (cdr pos))
170 (cdr pos)))
9e5d1b63
RS
171 (1+ (cdr pos))
172 (cdr pos))))
173 (setq to (substring to end)))))
7c1c02ac 174 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
78629844
DK
175 (setq to (nreverse (delete "" (cons to list))))
176 (replace-match-string-symbols to)
177 (cons 'replace-eval-replacement
178 (if (cdr to)
179 (cons 'concat to)
180 (car to))))
1606466a
SM
181 to))
182
78629844 183
90c9fc2a 184(defun query-replace-read-to (from prompt regexp-flag)
78629844
DK
185 "Query and return the `to' argument of a query-replace operation."
186 (query-replace-compile-replacement
187 (save-excursion
2bf2b947
JL
188 (let* ((history-add-new-input nil)
189 (to (read-from-minibuffer
190 (format "%s %s with: " prompt (query-replace-descr from))
191 nil nil nil
192 query-replace-to-history-variable from t)))
193 (add-to-history query-replace-to-history-variable to nil t)
6b59b130
CY
194 (setq query-replace-defaults (cons from to))
195 to))
78629844
DK
196 regexp-flag))
197
90c9fc2a 198(defun query-replace-read-args (prompt regexp-flag &optional noerror)
1606466a
SM
199 (unless noerror
200 (barf-if-buffer-read-only))
90c9fc2a 201 (let* ((from (query-replace-read-from prompt regexp-flag))
6f1df6d9 202 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
90c9fc2a 203 (query-replace-read-to from prompt regexp-flag))))
10784bac 204 (list from to current-prefix-arg)))
770970cb 205
47d72254 206(defun query-replace (from-string to-string &optional delimited start end)
da44e784
RM
207 "Replace some occurrences of FROM-STRING with TO-STRING.
208As each match is found, the user must type a character saying
209what to do with it. For directions, type \\[help-command] at that time.
210
7ef5c431
KH
211In Transient Mark mode, if the mark is active, operate on the contents
212of the region. Otherwise, operate from point to the end of the buffer.
213
151270f3
RS
214If `query-replace-interactive' is non-nil, the last incremental search
215string is used as FROM-STRING--you don't have to specify it with the
216minibuffer.
217
446d9629
RS
218Matching is independent of case if `case-fold-search' is non-nil and
219FROM-STRING has no uppercase letters. Replacement transfers the case
220pattern of the old text to the new text, if `case-replace' and
221`case-fold-search' are non-nil and FROM-STRING has no uppercase
222letters. \(Transferring the case pattern means that if the old text
223matched is all caps, or capitalized, then its replacement is upcased
224or capitalized.)
9b0bf2b6 225
118a01c9 226Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
81bdc14d 227only matches surrounded by word boundaries.
47d72254 228Fourth and fifth arg START and END specify the region to operate on.
81bdc14d
RS
229
230To customize possible responses, change the \"bindings\" in `query-replace-map'."
04ff2dee
JL
231 (interactive
232 (let ((common
233 (query-replace-read-args
234 (concat "Query replace"
235 (if current-prefix-arg " word" "")
236 (if (and transient-mark-mode mark-active) " in region" ""))
237 nil)))
238 (list (nth 0 common) (nth 1 common) (nth 2 common)
239 ;; These are done separately here
240 ;; so that command-history will record these expressions
241 ;; rather than the values they had this time.
242 (if (and transient-mark-mode mark-active)
243 (region-beginning))
244 (if (and transient-mark-mode mark-active)
245 (region-end)))))
99a7559f 246 (perform-replace from-string to-string t nil delimited nil nil start end))
7ef5c431 247
73fa8346 248(define-key esc-map "%" 'query-replace)
da44e784 249
47d72254 250(defun query-replace-regexp (regexp to-string &optional delimited start end)
da44e784
RM
251 "Replace some things after point matching REGEXP with TO-STRING.
252As each match is found, the user must type a character saying
253what to do with it. For directions, type \\[help-command] at that time.
254
7ef5c431
KH
255In Transient Mark mode, if the mark is active, operate on the contents
256of the region. Otherwise, operate from point to the end of the buffer.
257
151270f3
RS
258If `query-replace-interactive' is non-nil, the last incremental search
259regexp is used as REGEXP--you don't have to specify it with the
260minibuffer.
261
446d9629
RS
262Matching is independent of case if `case-fold-search' is non-nil and
263REGEXP has no uppercase letters. Replacement transfers the case
264pattern of the old text to the new text, if `case-replace' and
265`case-fold-search' are non-nil and REGEXP has no uppercase letters.
266\(Transferring the case pattern means that if the old text matched is
267all caps, or capitalized, then its replacement is upcased or
268capitalized.)
47d72254 269
118a01c9 270Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
da44e784 271only matches surrounded by word boundaries.
47d72254
GM
272Fourth and fifth arg START and END specify the region to operate on.
273
118a01c9
RS
274In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
275and `\\=\\N' (where N is a digit) stands for
2f57bf85 276whatever what matched the Nth `\\(...\\)' in REGEXP.
7c1c02ac
DK
277`\\?' lets you edit the replacement text in the minibuffer
278at the given position for each replacement.
279
ba8d15f9
RS
280In interactive calls, the replacement text can contain `\\,'
281followed by a Lisp expression. Each
282replacement evaluates that expression to compute the replacement
283string. Inside of that expression, `\\&' is a string denoting the
f1f6079c 284whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
ba8d15f9
RS
285for the whole or a partial match converted to a number with
286`string-to-number', and `\\#' itself for the number of replacements
287done so far (starting with zero).
7c1c02ac 288
ba8d15f9
RS
289If the replacement expression is a symbol, write a space after it
290to terminate it. One space there, if any, will be discarded.
7c1c02ac
DK
291
292When using those Lisp features interactively in the replacement
293text, TO-STRING is actually made a list instead of a string.
294Use \\[repeat-complex-command] after this command for details."
10784bac
RS
295 (interactive
296 (let ((common
10ddc30e 297 (query-replace-read-args
04ff2dee
JL
298 (concat "Query replace"
299 (if current-prefix-arg " word" "")
300 " regexp"
301 (if (and transient-mark-mode mark-active) " in region" ""))
f79bdb3a 302 t)))
7c1c02ac
DK
303 (list (nth 0 common) (nth 1 common) (nth 2 common)
304 ;; These are done separately here
305 ;; so that command-history will record these expressions
306 ;; rather than the values they had this time.
307 (if (and transient-mark-mode mark-active)
308 (region-beginning))
309 (if (and transient-mark-mode mark-active)
310 (region-end)))))
99a7559f 311 (perform-replace regexp to-string t t delimited nil nil start end))
2f57bf85 312
cbc127de 313(define-key esc-map [?\C-%] 'query-replace-regexp)
da44e784 314
47d72254 315(defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
84482eb3 316 "Replace some things after point matching REGEXP with the result of TO-EXPR.
fc6a2250
DK
317
318Interactive use of this function is deprecated in favor of the
319`\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
320using `search-forward-regexp' and `replace-match' is preferred.
321
84482eb3
RS
322As each match is found, the user must type a character saying
323what to do with it. For directions, type \\[help-command] at that time.
324
325TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
326reference `replace-count' to get the number of replacements already made.
327If the result of TO-EXPR is not a string, it is converted to one using
328`prin1-to-string' with the NOESCAPE argument (which see).
329
330For convenience, when entering TO-EXPR interactively, you can use `\\&' or
653479ad
AS
331`\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
332N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
84482eb3 333Use `\\#&' or `\\#N' if you want a number instead of a string.
2f57bf85 334In interactive use, `\\#' in itself stands for `replace-count'.
84482eb3
RS
335
336In Transient Mark mode, if the mark is active, operate on the contents
337of the region. Otherwise, operate from point to the end of the buffer.
338
339If `query-replace-interactive' is non-nil, the last incremental search
340regexp is used as REGEXP--you don't have to specify it with the
341minibuffer.
342
343Preserves case in each replacement if `case-replace' and `case-fold-search'
344are non-nil and REGEXP has no uppercase letters.
47d72254 345
84482eb3 346Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
470bbe9b 347only matches that are surrounded by word boundaries.
47d72254 348Fourth and fifth arg START and END specify the region to operate on."
84482eb3 349 (interactive
cc0aea1a 350 (progn
6f1df6d9
SM
351 (barf-if-buffer-read-only)
352 (let* ((from
353 ;; Let-bind the history var to disable the "foo -> bar" default.
354 ;; Maybe we shouldn't disable this default, but for now I'll
355 ;; leave it off. --Stef
356 (let ((query-replace-to-history-variable nil))
357 (query-replace-read-from "Query replace regexp" t)))
5291cbca 358 (to (list (read-from-minibuffer
6f1df6d9
SM
359 (format "Query replace regexp %s with eval: "
360 (query-replace-descr from))
5291cbca 361 nil nil t query-replace-to-history-variable from t))))
84482eb3
RS
362 ;; We make TO a list because replace-match-string-symbols requires one,
363 ;; and the user might enter a single token.
364 (replace-match-string-symbols to)
10784bac
RS
365 (list from (car to) current-prefix-arg
366 (if (and transient-mark-mode mark-active)
367 (region-beginning))
368 (if (and transient-mark-mode mark-active)
cc0aea1a 369 (region-end))))))
d2ce3151 370 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
d83a97ab 371 t 'literal delimited nil nil start end))
84482eb3 372
fc6a2250
DK
373(make-obsolete 'query-replace-regexp-eval
374 "for interactive use, use the special `\\,' feature of
375`query-replace-regexp' instead. Non-interactively, a loop
376using `search-forward-regexp' and `replace-match' is preferred." "22.1")
377
47d72254 378(defun map-query-replace-regexp (regexp to-strings &optional n start end)
da44e784 379 "Replace some matches for REGEXP with various strings, in rotation.
d8f1d2f3
JB
380The second argument TO-STRINGS contains the replacement strings, separated
381by spaces. This command works like `query-replace-regexp' except that
382each successive replacement uses the next successive replacement string,
da44e784
RM
383wrapping around from the last such string to the first.
384
7ef5c431
KH
385In Transient Mark mode, if the mark is active, operate on the contents
386of the region. Otherwise, operate from point to the end of the buffer.
387
da44e784
RM
388Non-interactively, TO-STRINGS may be a list of replacement strings.
389
151270f3
RS
390If `query-replace-interactive' is non-nil, the last incremental search
391regexp is used as REGEXP--you don't have to specify it with the minibuffer.
392
da44e784 393A prefix argument N says to use each replacement string N times
47d72254
GM
394before rotating to the next.
395Fourth and fifth arg START and END specify the region to operate on."
770970cb 396 (interactive
5291cbca 397 (let* ((from (if query-replace-interactive
151270f3
RS
398 (car regexp-search-ring)
399 (read-from-minibuffer "Map query replace (regexp): "
400 nil nil nil
84d0a5f8
GM
401 query-replace-from-history-variable
402 nil t)))
5291cbca 403 (to (read-from-minibuffer
770970cb 404 (format "Query replace %s with (space-separated strings): "
6f1df6d9 405 (query-replace-descr from))
770970cb 406 nil nil nil
84d0a5f8 407 query-replace-to-history-variable from t)))
2f2f7e58
RS
408 (list from to
409 (and current-prefix-arg
410 (prefix-numeric-value current-prefix-arg))
10784bac
RS
411 (if (and transient-mark-mode mark-active)
412 (region-beginning))
413 (if (and transient-mark-mode mark-active)
414 (region-end)))))
da44e784
RM
415 (let (replacements)
416 (if (listp to-strings)
417 (setq replacements to-strings)
418 (while (/= (length to-strings) 0)
419 (if (string-match " " to-strings)
420 (setq replacements
421 (append replacements
422 (list (substring to-strings 0
423 (string-match " " to-strings))))
424 to-strings (substring to-strings
425 (1+ (string-match " " to-strings))))
426 (setq replacements (append replacements (list to-strings))
427 to-strings ""))))
99a7559f 428 (perform-replace regexp replacements t t nil n nil start end)))
da44e784 429
47d72254 430(defun replace-string (from-string to-string &optional delimited start end)
da44e784
RM
431 "Replace occurrences of FROM-STRING with TO-STRING.
432Preserve case in each match if `case-replace' and `case-fold-search'
433are non-nil and FROM-STRING has no uppercase letters.
9b0bf2b6
RS
434\(Preserving case means that if the string matched is all caps, or capitalized,
435then its replacement is upcased or capitalized.)
436
7ef5c431
KH
437In Transient Mark mode, if the mark is active, operate on the contents
438of the region. Otherwise, operate from point to the end of the buffer.
439
118a01c9 440Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
da44e784 441only matches surrounded by word boundaries.
47d72254 442Fourth and fifth arg START and END specify the region to operate on.
da44e784 443
151270f3
RS
444If `query-replace-interactive' is non-nil, the last incremental search
445string is used as FROM-STRING--you don't have to specify it with the
446minibuffer.
447
da44e784
RM
448This function is usually the wrong thing to use in a Lisp program.
449What you probably want is a loop like this:
118a01c9
RS
450 (while (search-forward FROM-STRING nil t)
451 (replace-match TO-STRING nil t))
87532fbe
RS
452which will run faster and will not set the mark or print anything.
453\(You may need a more complex loop if FROM-STRING can match the null string
454and TO-STRING is also null.)"
10784bac
RS
455 (interactive
456 (let ((common
10ddc30e 457 (query-replace-read-args
04ff2dee
JL
458 (concat "Replace"
459 (if current-prefix-arg " word" "")
460 " string"
461 (if (and transient-mark-mode mark-active) " in region" ""))
f79bdb3a 462 nil)))
10784bac
RS
463 (list (nth 0 common) (nth 1 common) (nth 2 common)
464 (if (and transient-mark-mode mark-active)
465 (region-beginning))
466 (if (and transient-mark-mode mark-active)
467 (region-end)))))
99a7559f 468 (perform-replace from-string to-string nil nil delimited nil nil start end))
da44e784 469
47d72254 470(defun replace-regexp (regexp to-string &optional delimited start end)
da44e784 471 "Replace things after point matching REGEXP with TO-STRING.
118a01c9 472Preserve case in each match if `case-replace' and `case-fold-search'
da44e784 473are non-nil and REGEXP has no uppercase letters.
47d72254
GM
474
475In Transient Mark mode, if the mark is active, operate on the contents
476of the region. Otherwise, operate from point to the end of the buffer.
477
118a01c9 478Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
da44e784 479only matches surrounded by word boundaries.
47d72254
GM
480Fourth and fifth arg START and END specify the region to operate on.
481
118a01c9
RS
482In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
483and `\\=\\N' (where N is a digit) stands for
7c1c02ac
DK
484whatever what matched the Nth `\\(...\\)' in REGEXP.
485`\\?' lets you edit the replacement text in the minibuffer
486at the given position for each replacement.
487
488In interactive calls, the replacement text may contain `\\,'
489followed by a Lisp expression used as part of the replacement
490text. Inside of that expression, `\\&' is a string denoting the
107173cf
JB
491whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
492numeric values from `string-to-number', and `\\#' itself for
493`replace-count', the number of replacements occurred so far.
7c1c02ac
DK
494
495If your Lisp expression is an identifier and the next letter in
496the replacement string would be interpreted as part of it, you
497can wrap it with an expression like `\\,(or \\#)'. Incidentally,
498for this particular case you may also enter `\\#' in the
499replacement text directly.
500
501When using those Lisp features interactively in the replacement
502text, TO-STRING is actually made a list instead of a string.
503Use \\[repeat-complex-command] after this command for details.
da44e784 504
151270f3
RS
505If `query-replace-interactive' is non-nil, the last incremental search
506regexp is used as REGEXP--you don't have to specify it with the minibuffer.
507
da44e784
RM
508This function is usually the wrong thing to use in a Lisp program.
509What you probably want is a loop like this:
510 (while (re-search-forward REGEXP nil t)
118a01c9 511 (replace-match TO-STRING nil nil))
da44e784 512which will run faster and will not set the mark or print anything."
10784bac
RS
513 (interactive
514 (let ((common
10ddc30e 515 (query-replace-read-args
04ff2dee
JL
516 (concat "Replace"
517 (if current-prefix-arg " word" "")
518 " regexp"
519 (if (and transient-mark-mode mark-active) " in region" ""))
f79bdb3a 520 t)))
10784bac
RS
521 (list (nth 0 common) (nth 1 common) (nth 2 common)
522 (if (and transient-mark-mode mark-active)
523 (region-beginning))
524 (if (and transient-mark-mode mark-active)
525 (region-end)))))
99a7559f 526 (perform-replace regexp to-string nil t delimited nil nil start end))
e32eb3e6 527
4c53bd2b
RS
528\f
529(defvar regexp-history nil
fae97ed8
EZ
530 "History list for some commands that read regular expressions.
531
532Maximum length of the history list is determined by the value
533of `history-length', which see.")
da44e784 534
15af15e5
TO
535(defvar occur-collect-regexp-history '("\\1")
536 "History of regexp for occur's collect operation")
537
10965505 538(defun read-regexp (prompt &optional default-value)
96f606c5 539 "Read regexp as a string using the regexp history and some useful defaults.
714da757 540Prompt for a regular expression with PROMPT (without a colon and
10965505
JL
541space) in the minibuffer. The optional argument DEFAULT-VALUE
542provides the value to display in the minibuffer prompt that is
543returned if the user just types RET.
544Values available via M-n are the string at point, the last isearch
545regexp, the last isearch string, and the last replacement regexp."
714da757 546 (let* ((defaults
96f606c5
JL
547 (list (regexp-quote
548 (or (funcall (or find-tag-default-function
549 (get major-mode 'find-tag-default-function)
550 'find-tag-default))
551 ""))
552 (car regexp-search-ring)
553 (regexp-quote (or (car search-ring) ""))
554 (car (symbol-value
555 query-replace-from-history-variable))))
556 (defaults (delete-dups (delq nil (delete "" defaults))))
557 ;; Don't add automatically the car of defaults for empty input
558 (history-add-new-input nil)
559 (input
560 (read-from-minibuffer
10965505
JL
561 (if default-value
562 (format "%s (default %s): " prompt
563 (query-replace-descr default-value))
96f606c5
JL
564 (format "%s: " prompt))
565 nil nil nil 'regexp-history defaults t)))
566 (if (equal input "")
99910cf4 567 (or default-value input)
96f606c5
JL
568 (prog1 input
569 (add-to-history 'regexp-history input)))))
570
e32eb3e6 571
31e1d920 572(defalias 'delete-non-matching-lines 'keep-lines)
e32eb3e6
GM
573(defalias 'delete-matching-lines 'flush-lines)
574(defalias 'count-matches 'how-many)
575
576
577(defun keep-lines-read-args (prompt)
578 "Read arguments for `keep-lines' and friends.
579Prompt for a regexp with PROMPT.
2ced751f 580Value is a list, (REGEXP)."
99910cf4 581 (list (read-regexp prompt) nil nil t))
e32eb3e6 582
bace7209 583(defun keep-lines (regexp &optional rstart rend interactive)
698e1804
RS
584 "Delete all lines except those containing matches for REGEXP.
585A match split across lines preserves all the lines it lies in.
bace7209
LT
586When called from Lisp (and usually interactively as well, see below)
587applies to all lines starting after point.
d2a0ee8b 588
3be42fcd
JL
589If REGEXP contains upper case characters (excluding those preceded by `\\')
590and `search-upper-case' is non-nil, the matching is case-sensitive.
e32eb3e6
GM
591
592Second and third arg RSTART and REND specify the region to operate on.
bace7209
LT
593This command operates on (the accessible part of) all lines whose
594accessible part is entirely contained in the region determined by RSTART
595and REND. (A newline ending a line counts as part of that line.)
e32eb3e6 596
2ced751f 597Interactively, in Transient Mark mode when the mark is active, operate
bace7209
LT
598on all lines whose accessible part is entirely contained in the region.
599Otherwise, the command applies to all lines starting after point.
600When calling this function from Lisp, you can pretend that it was
601called interactively by passing a non-nil INTERACTIVE argument.
602
603This function starts looking for the next match from the end of
604the previous match. Hence, it ignores matches that overlap
605a previously found match."
2ced751f 606
e32eb3e6 607 (interactive
98faf1bb
RS
608 (progn
609 (barf-if-buffer-read-only)
96f606c5 610 (keep-lines-read-args "Keep lines containing match for regexp")))
e32eb3e6 611 (if rstart
119831da
RS
612 (progn
613 (goto-char (min rstart rend))
bace7209
LT
614 (setq rend
615 (progn
616 (save-excursion
617 (goto-char (max rstart rend))
618 (unless (or (bolp) (eobp))
619 (forward-line 0))
620 (point-marker)))))
621 (if (and interactive transient-mark-mode mark-active)
2ced751f 622 (setq rstart (region-beginning)
bace7209
LT
623 rend (progn
624 (goto-char (region-end))
625 (unless (or (bolp) (eobp))
626 (forward-line 0))
627 (point-marker)))
2ced751f
RS
628 (setq rstart (point)
629 rend (point-max-marker)))
630 (goto-char rstart))
698e1804
RS
631 (save-excursion
632 (or (bolp) (forward-line 1))
d2a0ee8b 633 (let ((start (point))
3be42fcd
JL
634 (case-fold-search
635 (if (and case-fold-search search-upper-case)
636 (isearch-no-upper-case-p regexp t)
637 case-fold-search)))
e32eb3e6 638 (while (< (point) rend)
698e1804 639 ;; Start is first char not preserved by previous match.
e32eb3e6
GM
640 (if (not (re-search-forward regexp rend 'move))
641 (delete-region start rend)
698e1804 642 (let ((end (save-excursion (goto-char (match-beginning 0))
bace7209 643 (forward-line 0)
698e1804
RS
644 (point))))
645 ;; Now end is first char preserved by the new match.
646 (if (< start end)
647 (delete-region start end))))
d99118b0 648
e32eb3e6 649 (setq start (save-excursion (forward-line 1) (point)))
698e1804 650 ;; If the match was empty, avoid matching again at same place.
e32eb3e6
GM
651 (and (< (point) rend)
652 (= (match-beginning 0) (match-end 0))
bace7209
LT
653 (forward-char 1)))))
654 (set-marker rend nil)
655 nil)
698e1804 656
e32eb3e6 657
bace7209
LT
658(defun flush-lines (regexp &optional rstart rend interactive)
659 "Delete lines containing matches for REGEXP.
660When called from Lisp (and usually when called interactively as
661well, see below), applies to the part of the buffer after point.
662The line point is in is deleted if and only if it contains a
663match for regexp starting after point.
d2a0ee8b 664
3be42fcd
JL
665If REGEXP contains upper case characters (excluding those preceded by `\\')
666and `search-upper-case' is non-nil, the matching is case-sensitive.
e32eb3e6
GM
667
668Second and third arg RSTART and REND specify the region to operate on.
bace7209
LT
669Lines partially contained in this region are deleted if and only if
670they contain a match entirely contained in it.
e32eb3e6 671
2ced751f
RS
672Interactively, in Transient Mark mode when the mark is active, operate
673on the contents of the region. Otherwise, operate from point to the
bace7209
LT
674end of (the accessible portion of) the buffer. When calling this function
675from Lisp, you can pretend that it was called interactively by passing
676a non-nil INTERACTIVE argument.
677
678If a match is split across lines, all the lines it lies in are deleted.
679They are deleted _before_ looking for the next match. Hence, a match
680starting on the same line at which another match ended is ignored."
2ced751f 681
e32eb3e6 682 (interactive
98faf1bb
RS
683 (progn
684 (barf-if-buffer-read-only)
96f606c5 685 (keep-lines-read-args "Flush lines containing match for regexp")))
e32eb3e6 686 (if rstart
119831da
RS
687 (progn
688 (goto-char (min rstart rend))
689 (setq rend (copy-marker (max rstart rend))))
bace7209 690 (if (and interactive transient-mark-mode mark-active)
2ced751f
RS
691 (setq rstart (region-beginning)
692 rend (copy-marker (region-end)))
693 (setq rstart (point)
694 rend (point-max-marker)))
695 (goto-char rstart))
3be42fcd
JL
696 (let ((case-fold-search
697 (if (and case-fold-search search-upper-case)
698 (isearch-no-upper-case-p regexp t)
699 case-fold-search)))
d2a0ee8b 700 (save-excursion
e32eb3e6
GM
701 (while (and (< (point) rend)
702 (re-search-forward regexp rend t))
d2a0ee8b 703 (delete-region (save-excursion (goto-char (match-beginning 0))
bace7209 704 (forward-line 0)
d2a0ee8b 705 (point))
bace7209
LT
706 (progn (forward-line 1) (point))))))
707 (set-marker rend nil)
708 nil)
698e1804 709
e32eb3e6 710
bace7209
LT
711(defun how-many (regexp &optional rstart rend interactive)
712 "Print and return number of matches for REGEXP following point.
713When called from Lisp and INTERACTIVE is omitted or nil, just return
714the number, do not print it; if INTERACTIVE is t, the function behaves
3f2372cb 715in all respects as if it had been called interactively.
d2a0ee8b 716
3be42fcd
JL
717If REGEXP contains upper case characters (excluding those preceded by `\\')
718and `search-upper-case' is non-nil, the matching is case-sensitive.
e32eb3e6
GM
719
720Second and third arg RSTART and REND specify the region to operate on.
721
2ced751f
RS
722Interactively, in Transient Mark mode when the mark is active, operate
723on the contents of the region. Otherwise, operate from point to the
bace7209
LT
724end of (the accessible portion of) the buffer.
725
726This function starts looking for the next match from the end of
727the previous match. Hence, it ignores matches that overlap
728a previously found match."
2ced751f 729
e32eb3e6 730 (interactive
96f606c5 731 (keep-lines-read-args "How many matches for regexp"))
f601efb0
SM
732 (save-excursion
733 (if rstart
bace7209
LT
734 (progn
735 (goto-char (min rstart rend))
736 (setq rend (max rstart rend)))
737 (if (and interactive transient-mark-mode mark-active)
2ced751f 738 (setq rstart (region-beginning)
bace7209 739 rend (region-end))
2ced751f 740 (setq rstart (point)
bace7209 741 rend (point-max)))
2ced751f 742 (goto-char rstart))
f601efb0
SM
743 (let ((count 0)
744 opoint
3be42fcd
JL
745 (case-fold-search
746 (if (and case-fold-search search-upper-case)
747 (isearch-no-upper-case-p regexp t)
748 case-fold-search)))
f601efb0
SM
749 (while (and (< (point) rend)
750 (progn (setq opoint (point))
751 (re-search-forward regexp rend t)))
752 (if (= opoint (point))
753 (forward-char 1)
754 (setq count (1+ count))))
bace7209
LT
755 (when interactive (message "%d occurrence%s"
756 count
757 (if (= count 1) "" "s")))
758 count)))
e32eb3e6 759
4c53bd2b 760\f
f601efb0
SM
761(defvar occur-mode-map
762 (let ((map (make-sparse-keymap)))
cedbd3f0 763 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
f601efb0
SM
764 (define-key map [mouse-2] 'occur-mode-mouse-goto)
765 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
766 (define-key map "\C-m" 'occur-mode-goto-occurrence)
daae70bf 767 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
365486d6 768 (define-key map "\C-o" 'occur-mode-display-occurrence)
f601efb0
SM
769 (define-key map "\M-n" 'occur-next)
770 (define-key map "\M-p" 'occur-prev)
d99118b0
SS
771 (define-key map "r" 'occur-rename-buffer)
772 (define-key map "c" 'clone-buffer)
f601efb0 773 (define-key map "g" 'revert-buffer)
d99118b0
SS
774 (define-key map "q" 'quit-window)
775 (define-key map "z" 'kill-this-buffer)
b938735a 776 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
85ea5b19
DN
777 (define-key map [menu-bar] (make-sparse-keymap))
778 (define-key map [menu-bar occur]
8f43cbf3 779 `(cons ,(purecopy "Occur") map))
85ea5b19
DN
780 (define-key map [next-error-follow-minor-mode]
781 (menu-bar-make-mm-toggle next-error-follow-minor-mode
782 "Auto Occurrence Display"
783 "Display another occurrence when moving the cursor"))
6d341a2a 784 (define-key map [separator-1] menu-bar-separator)
9201cc28 785 (define-key map [kill-this-buffer]
8f43cbf3
DN
786 `(menu-item ,(purecopy "Kill occur buffer") kill-this-buffer
787 :help ,(purecopy "Kill the current *Occur* buffer")))
9201cc28 788 (define-key map [quit-window]
8f43cbf3
DN
789 `(menu-item ,(purecopy "Quit occur window") quit-window
790 :help ,(purecopy "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame")))
9201cc28 791 (define-key map [revert-buffer]
8f43cbf3
DN
792 `(menu-item ,(purecopy "Revert occur buffer") revert-buffer
793 :help ,(purecopy "Replace the text in the *Occur* buffer with the results of rerunning occur")))
9201cc28 794 (define-key map [clone-buffer]
8f43cbf3
DN
795 `(menu-item ,(purecopy "Clone occur buffer") clone-buffer
796 :help ,(purecopy "Create and return a twin copy of the current *Occur* buffer")))
9201cc28 797 (define-key map [occur-rename-buffer]
8f43cbf3
DN
798 `(menu-item ,(purecopy "Rename occur buffer") occur-rename-buffer
799 :help ,(purecopy "Rename the current *Occur* buffer to *Occur: original-buffer-name*.")))
a3c20c83 800 (define-key map [separator-2] menu-bar-separator)
85ea5b19 801 (define-key map [occur-mode-goto-occurrence-other-window]
8f43cbf3
DN
802 `(menu-item ,(purecopy "Go To Occurrence Other Window") occur-mode-goto-occurrence-other-window
803 :help ,(purecopy "Go to the occurrence the current line describes, in another window")))
85ea5b19 804 (define-key map [occur-mode-goto-occurrence]
8f43cbf3
DN
805 `(menu-item ,(purecopy "Go To Occurrence") occur-mode-goto-occurrence
806 :help ,(purecopy "Go to the occurrence the current line describes")))
85ea5b19 807 (define-key map [occur-mode-display-occurrence]
8f43cbf3
DN
808 `(menu-item ,(purecopy "Display Occurrence") occur-mode-display-occurrence
809 :help ,(purecopy "Display in another window the occurrence the current line describes")))
9201cc28 810 (define-key map [occur-next]
8f43cbf3
DN
811 `(menu-item ,(purecopy "Move to next match") occur-next
812 :help ,(purecopy "Move to the Nth (default 1) next match in an Occur mode buffer")))
9201cc28 813 (define-key map [occur-prev]
8f43cbf3
DN
814 `(menu-item ,(purecopy "Move to previous match") occur-prev
815 :help ,(purecopy "Move to the Nth (default 1) previous match in an Occur mode buffer")))
f601efb0
SM
816 map)
817 "Keymap for `occur-mode'.")
698e1804 818
46b3d18e
RS
819(defvar occur-revert-arguments nil
820 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
821See `occur-revert-function'.")
698e1804 822
c9ae8cbb
JB
823(defcustom occur-mode-hook '(turn-on-font-lock)
824 "Hook run when entering Occur mode."
825 :type 'hook
826 :group 'matching)
827
828(defcustom occur-hook nil
c7d2f2cc 829 "Hook run by Occur when there are any matches."
daae70bf
CW
830 :type 'hook
831 :group 'matching)
832
8e62d5e8
CD
833(defcustom occur-mode-find-occurrence-hook nil
834 "Hook run by Occur after locating an occurrence.
835This will be called with the cursor position at the occurrence. An application
836for this is to reveal context in an outline-mode when the occurrence is hidden."
837 :type 'hook
838 :group 'matching)
839
de3c9b09 840(put 'occur-mode 'mode-class 'special)
505847d4 841(defun occur-mode ()
698e1804 842 "Major mode for output from \\[occur].
0081c8a1
RS
843\\<occur-mode-map>Move point to one of the items in this buffer, then use
844\\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
845Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
846
698e1804 847\\{occur-mode-map}"
ce8b7b9f 848 (interactive)
505847d4
RS
849 (kill-all-local-variables)
850 (use-local-map occur-mode-map)
851 (setq major-mode 'occur-mode)
852 (setq mode-name "Occur")
f601efb0 853 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
c9ae8cbb 854 (make-local-variable 'occur-revert-arguments)
fbefbe33 855 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
423e4de7 856 (setq next-error-function 'occur-next-error)
92e9557c 857 (run-mode-hooks 'occur-mode-hook))
698e1804 858
a41284da 859(defun occur-revert-function (ignore1 ignore2)
46b3d18e 860 "Handle `revert-buffer' for Occur mode buffers."
e1690783 861 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
a41284da 862
78bead73 863(defun occur-mode-find-occurrence ()
46b3d18e
RS
864 (let ((pos (get-text-property (point) 'occur-target)))
865 (unless pos
68608d9c 866 (error "No occurrence on this line"))
46b3d18e
RS
867 (unless (buffer-live-p (marker-buffer pos))
868 (error "Buffer for this occurrence was killed"))
869 pos))
78bead73 870
cedbd3f0
SM
871(defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
872(defun occur-mode-goto-occurrence (&optional event)
78bead73 873 "Go to the occurrence the current line describes."
cedbd3f0
SM
874 (interactive (list last-nonmenu-event))
875 (let ((pos
876 (if (null event)
877 ;; Actually `event-end' works correctly with a nil argument as
878 ;; well, so we could dispense with this test, but let's not
879 ;; rely on this undocumented behavior.
880 (occur-mode-find-occurrence)
881 (with-current-buffer (window-buffer (posn-window (event-end event)))
882 (save-excursion
883 (goto-char (posn-point (event-end event)))
884 (occur-mode-find-occurrence)))))
885 same-window-buffer-names
886 same-window-regexps)
7e1d31d4 887 (pop-to-buffer (marker-buffer pos))
8e62d5e8
CD
888 (goto-char pos)
889 (run-hooks 'occur-mode-find-occurrence-hook)))
8d15583f 890
029024e2
RS
891(defun occur-mode-goto-occurrence-other-window ()
892 "Go to the occurrence the current line describes, in another window."
893 (interactive)
46b3d18e
RS
894 (let ((pos (occur-mode-find-occurrence)))
895 (switch-to-buffer-other-window (marker-buffer pos))
8e62d5e8
CD
896 (goto-char pos)
897 (run-hooks 'occur-mode-find-occurrence-hook)))
029024e2 898
365486d6
RS
899(defun occur-mode-display-occurrence ()
900 "Display in another window the occurrence the current line describes."
901 (interactive)
46b3d18e
RS
902 (let ((pos (occur-mode-find-occurrence))
903 window
904 ;; Bind these to ensure `display-buffer' puts it in another window.
365486d6 905 same-window-buffer-names
46b3d18e
RS
906 same-window-regexps)
907 (setq window (display-buffer (marker-buffer pos)))
365486d6
RS
908 ;; This is the way to set point in the proper window.
909 (save-selected-window
910 (select-window window)
8e62d5e8
CD
911 (goto-char pos)
912 (run-hooks 'occur-mode-find-occurrence-hook))))
365486d6 913
123d5548 914(defun occur-find-match (n search message)
8d15583f
RS
915 (if (not n) (setq n 1))
916 (let ((r))
917 (while (> n 0)
123d5548
JB
918 (setq r (funcall search (point) 'occur-match))
919 (and r
920 (get-text-property r 'occur-match)
921 (setq r (funcall search r 'occur-match)))
8d15583f 922 (if r
123d5548
JB
923 (goto-char r)
924 (error message))
8d15583f
RS
925 (setq n (1- n)))))
926
123d5548
JB
927(defun occur-next (&optional n)
928 "Move to the Nth (default 1) next match in an Occur mode buffer."
929 (interactive "p")
930 (occur-find-match n #'next-single-property-change "No more matches"))
931
8d15583f 932(defun occur-prev (&optional n)
46b3d18e 933 "Move to the Nth (default 1) previous match in an Occur mode buffer."
8d15583f 934 (interactive "p")
123d5548 935 (occur-find-match n #'previous-single-property-change "No earlier matches"))
423e4de7
KS
936
937(defun occur-next-error (&optional argp reset)
938 "Move to the Nth (default 1) next match in an Occur mode buffer.
939Compatibility function for \\[next-error] invocations."
940 (interactive "p")
5f9e0ca5 941 ;; we need to run occur-find-match from within the Occur buffer
f1f007dc 942 (with-current-buffer
f42a241b 943 ;; Choose the buffer and make it current.
5f9e0ca5
TZ
944 (if (next-error-buffer-p (current-buffer))
945 (current-buffer)
f42a241b
RS
946 (next-error-find-buffer nil nil
947 (lambda ()
948 (eq major-mode 'occur-mode))))
f1f007dc
JL
949
950 (goto-char (cond (reset (point-min))
951 ((< argp 0) (line-beginning-position))
6c6605b2
JL
952 ((> argp 0) (line-end-position))
953 ((point))))
5f9e0ca5 954 (occur-find-match
f1f007dc
JL
955 (abs argp)
956 (if (> 0 argp)
5f9e0ca5
TZ
957 #'previous-single-property-change
958 #'next-single-property-change)
959 "No more matches")
960 ;; In case the *Occur* buffer is visible in a nonselected window.
084c41ca
SM
961 (let ((win (get-buffer-window (current-buffer) t)))
962 (if win (set-window-point win (point))))
5f9e0ca5 963 (occur-mode-goto-occurrence)))
4c53bd2b 964\f
aaaecfcd
JL
965(defface match
966 '((((class color) (min-colors 88) (background light))
5183d4c9 967 :background "yellow1")
aaaecfcd 968 (((class color) (min-colors 88) (background dark))
4bc30b74 969 :background "RoyalBlue3")
330167fc
RS
970 (((class color) (min-colors 8) (background light))
971 :background "yellow" :foreground "black")
972 (((class color) (min-colors 8) (background dark))
aaaecfcd
JL
973 :background "blue" :foreground "white")
974 (((type tty) (class mono))
975 :inverse-video t)
976 (t :background "gray"))
977 "Face used to highlight matches permanently."
978 :group 'matching
bf247b6e 979 :version "22.1")
aaaecfcd 980
9d325ebf 981(defcustom list-matching-lines-default-context-lines 0
9201cc28 982 "Default number of context lines included around `list-matching-lines' matches.
e730be7f 983A negative number means to include that many lines before the match.
9d325ebf
RS
984A positive number means to include that many lines both before and after."
985 :type 'integer
986 :group 'matching)
698e1804 987
31e1d920 988(defalias 'list-matching-lines 'occur)
698e1804 989
aaaecfcd 990(defcustom list-matching-lines-face 'match
9201cc28 991 "Face used by \\[list-matching-lines] to show the text that matches.
68608d9c
CW
992If the value is nil, don't highlight the matching portions specially."
993 :type 'face
994 :group 'matching)
995
996(defcustom list-matching-lines-buffer-name-face 'underline
9201cc28 997 "Face used by \\[list-matching-lines] to show the names of buffers.
68608d9c
CW
998If the value is nil, don't highlight the buffer names specially."
999 :type 'face
1000 :group 'matching)
1001
8b363e6f
JL
1002(defcustom occur-excluded-properties
1003 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1004 yank-handler follow-link)
9201cc28 1005 "Text properties to discard when copying lines to the *Occur* buffer.
8b363e6f
JL
1006The value should be a list of text properties to discard or t,
1007which means to discard all text properties."
1008 :type '(choice (const :tag "All" t) (repeat symbol))
1009 :group 'matching
1010 :version "22.1")
1011
68608d9c 1012(defun occur-read-primary-args ()
15af15e5
TO
1013 (let* ((perform-collect (consp current-prefix-arg))
1014 (regexp (read-regexp (if perform-collect
1015 "Collect strings matching regexp"
1016 "List lines matching regexp")
1017 (car regexp-history))))
1018 (list regexp
1019 (if perform-collect
1020 ;; Perform collect operation
1021 (if (zerop (regexp-opt-depth regexp))
1022 ;; No subexpression so collect the entire match.
1023 "\\&"
1024 ;; Get the regexp for collection pattern.
1025 (let ((default (car occur-collect-regexp-history)))
1026 (read-string
1027 (format "Regexp to collect (default %s): " default)
1028 nil 'occur-collect-regexp-history default)))
1029 ;; Otherwise normal occur takes numerical prefix argument.
1030 (when current-prefix-arg
1031 (prefix-numeric-value current-prefix-arg))))))
c9daced0 1032
a653724b 1033(defun occur-rename-buffer (&optional unique-p interactive-p)
d99118b0 1034 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
47c88c06 1035Here `original-buffer-name' is the buffer name where Occur was originally run.
a653724b
JB
1036When given the prefix argument, or called non-interactively, the renaming
1037will not clobber the existing buffer(s) of that name, but use
1038`generate-new-buffer-name' instead. You can add this to `occur-hook'
1039if you always want a separate *Occur* buffer for each buffer where you
1040invoke `occur'."
1041 (interactive "P\np")
d99118b0
SS
1042 (with-current-buffer
1043 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1044 (rename-buffer (concat "*Occur: "
1045 (mapconcat #'buffer-name
1046 (car (cddr occur-revert-arguments)) "/")
1047 "*")
a653724b 1048 (or unique-p (not interactive-p)))))
d99118b0 1049
698e1804 1050(defun occur (regexp &optional nlines)
99976f85 1051 "Show all lines in the current buffer containing a match for REGEXP.
774642e5 1052If a match spreads across multiple lines, all those lines are shown.
698e1804 1053
da44e784
RM
1054Each line is displayed with NLINES lines before and after, or -NLINES
1055before if NLINES is negative.
1056NLINES defaults to `list-matching-lines-default-context-lines'.
698e1804
RS
1057Interactively it is the prefix arg.
1058
4c53bd2b 1059The lines are shown in a buffer named `*Occur*'.
698e1804 1060It serves as a menu to find any of the occurrences in this buffer.
de3c9b09 1061\\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
9483d601 1062
3be42fcd 1063If REGEXP contains upper case characters (excluding those preceded by `\\')
15af15e5
TO
1064and `search-upper-case' is non-nil, the matching is case-sensitive.
1065
1066When NLINES is a string or when the function is called
1067interactively with prefix argument without a number (`C-u' alone
1068as prefix) the matching strings are collected into the `*Occur*'
1069buffer by using NLINES as a replacement regexp. NLINES may
1070contain \\& and \\N which convention follows `replace-match'.
1071For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1072\"\\1\" for NLINES collects all the function names in a lisp
1073program. When there is no parenthesized subexpressions in REGEXP
1074the entire match is collected. In any case the searched buffers
1075are not modified."
68608d9c
CW
1076 (interactive (occur-read-primary-args))
1077 (occur-1 regexp nlines (list (current-buffer))))
1078
1079(defun multi-occur (bufs regexp &optional nlines)
1080 "Show all lines in buffers BUFS containing a match for REGEXP.
1081This function acts on multiple buffers; otherwise, it is exactly like
191b577e
RS
1082`occur'. When you invoke this command interactively, you must specify
1083the buffer names that you want, one by one."
a5dfed3e 1084 (interactive
68608d9c 1085 (cons
52698d45
KS
1086 (let* ((bufs (list (read-buffer "First buffer to search: "
1087 (current-buffer) t)))
1088 (buf nil)
1089 (ido-ignore-item-temp-list bufs))
68608d9c 1090 (while (not (string-equal
f1180544 1091 (setq buf (read-buffer
52698d45
KS
1092 (if (eq read-buffer-function 'ido-read-buffer)
1093 "Next buffer to search (C-j to end): "
1094 "Next buffer to search (RET to end): ")
1095 nil t))
68608d9c 1096 ""))
52698d45
KS
1097 (add-to-list 'bufs buf)
1098 (setq ido-ignore-item-temp-list bufs))
68608d9c
CW
1099 (nreverse (mapcar #'get-buffer bufs)))
1100 (occur-read-primary-args)))
1101 (occur-1 regexp nlines bufs))
1102
191b577e
RS
1103(defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1104 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1105Normally BUFREGEXP matches against each buffer's visited file name,
1106but if you specify a prefix argument, it matches against the buffer name.
68608d9c
CW
1107See also `multi-occur'."
1108 (interactive
1109 (cons
1110 (let* ((default (car regexp-history))
1111 (input
1112 (read-from-minibuffer
689f4394 1113 (if current-prefix-arg
191b577e
RS
1114 "List lines in buffers whose names match regexp: "
1115 "List lines in buffers whose filenames match regexp: ")
68608d9c
CW
1116 nil
1117 nil
1118 nil
1119 'regexp-history)))
1120 (if (equal input "")
1121 default
1122 input))
1123 (occur-read-primary-args)))
1124 (when bufregexp
689f4394 1125 (occur-1 regexp nil
68608d9c
CW
1126 (delq nil
1127 (mapcar (lambda (buf)
191b577e
RS
1128 (when (if allbufs
1129 (string-match bufregexp
1130 (buffer-name buf))
1131 (and (buffer-file-name buf)
1132 (string-match bufregexp
1133 (buffer-file-name buf))))
68608d9c
CW
1134 buf))
1135 (buffer-list))))))
1136
e1690783 1137(defun occur-1 (regexp nlines bufs &optional buf-name)
360289a6
JL
1138 (unless (and regexp (not (equal regexp "")))
1139 (error "Occur doesn't work with the empty regexp"))
e1690783
CW
1140 (unless buf-name
1141 (setq buf-name "*Occur*"))
f42a241b 1142 (let (occur-buf
70ed2a76
CW
1143 (active-bufs (delq nil (mapcar #'(lambda (buf)
1144 (when (buffer-live-p buf) buf))
1145 bufs))))
1146 ;; Handle the case where one of the buffers we're searching is the
f42a241b
RS
1147 ;; output buffer. Just rename it.
1148 (when (member buf-name (mapcar 'buffer-name active-bufs))
1149 (with-current-buffer (get-buffer buf-name)
1150 (rename-uniquely)))
1151
1152 ;; Now find or create the output buffer.
1153 ;; If we just renamed that buffer, we will make a new one here.
1154 (setq occur-buf (get-buffer-create buf-name))
1155
68608d9c 1156 (with-current-buffer occur-buf
15af15e5
TO
1157 (if (stringp nlines)
1158 (fundamental-mode) ;; This is for collect opeartion.
1159 (occur-mode))
8121414a
CY
1160 (let ((inhibit-read-only t)
1161 ;; Don't generate undo entries for creation of the initial contents.
1162 (buffer-undo-list t))
06df7f87 1163 (erase-buffer)
15af15e5
TO
1164 (let ((count
1165 (if (stringp nlines)
1166 ;; Treat nlines as a regexp to collect.
1167 (let ((bufs active-bufs)
1168 (count 0))
1169 (while bufs
1170 (with-current-buffer (car bufs)
1171 (save-excursion
1172 (goto-char (point-min))
1173 (while (re-search-forward regexp nil t)
1174 ;; Insert the replacement regexp.
1175 (let ((str (match-substitute-replacement nlines)))
1176 (if str
1177 (with-current-buffer occur-buf
1178 (insert str)
1179 (setq count (1+ count))
1180 (or (zerop (current-column))
1181 (insert "\n"))))))))
1182 (setq bufs (cdr bufs)))
1183 count)
1184 ;; Perform normal occur.
1185 (occur-engine
1186 regexp active-bufs occur-buf
1187 (or nlines list-matching-lines-default-context-lines)
1188 (if (and case-fold-search search-upper-case)
1189 (isearch-no-upper-case-p regexp t)
1190 case-fold-search)
1191 list-matching-lines-buffer-name-face
1192 nil list-matching-lines-face
1193 (not (eq occur-excluded-properties t))))))
06df7f87
EZ
1194 (let* ((bufcount (length active-bufs))
1195 (diff (- (length bufs) bufcount)))
d66ecdbb 1196 (message "Searched %d buffer%s%s; %s match%s%s"
06df7f87
EZ
1197 bufcount (if (= bufcount 1) "" "s")
1198 (if (zerop diff) "" (format " (%d killed)" diff))
1199 (if (zerop count) "no" (format "%d" count))
1200 (if (= count 1) "" "es")
d66ecdbb
JL
1201 ;; Don't display regexp if with remaining text
1202 ;; it is longer than window-width.
1203 (if (> (+ (length regexp) 42) (window-width))
1204 "" (format " for `%s'" (query-replace-descr regexp)))))
06df7f87 1205 (setq occur-revert-arguments (list regexp nlines bufs))
c7d2f2cc
JB
1206 (if (= count 0)
1207 (kill-buffer occur-buf)
1208 (display-buffer occur-buf)
1209 (setq next-error-last-buffer occur-buf)
1210 (setq buffer-read-only t)
1211 (set-buffer-modified-p nil)
1212 (run-hooks 'occur-hook)))))))
68608d9c 1213
46b3d18e
RS
1214(defun occur-engine (regexp buffers out-buf nlines case-fold-search
1215 title-face prefix-face match-face keep-props)
1216 (with-current-buffer out-buf
5cb4031d
KH
1217 (let ((globalcount 0)
1218 (coding nil))
46b3d18e
RS
1219 ;; Map over all the buffers
1220 (dolist (buf buffers)
1221 (when (buffer-live-p buf)
1222 (let ((matches 0) ;; count of matched lines
1223 (lines 1) ;; line count
dc2d2590
JL
1224 (prev-after-lines nil) ;; context lines of prev match
1225 (prev-lines nil) ;; line number of prev match endpt
46b3d18e 1226 (matchbeg 0)
46b3d18e
RS
1227 (origpt nil)
1228 (begpt nil)
1229 (endpt nil)
1230 (marker nil)
1231 (curstring "")
dc2d2590 1232 (ret nil)
bc16bf5e 1233 (inhibit-field-text-motion t)
46b3d18e 1234 (headerpt (with-current-buffer out-buf (point))))
cedbd3f0 1235 (with-current-buffer buf
5cb4031d
KH
1236 (or coding
1237 ;; Set CODING only if the current buffer locally
1238 ;; binds buffer-file-coding-system.
1239 (not (local-variable-p 'buffer-file-coding-system))
1240 (setq coding buffer-file-coding-system))
68608d9c 1241 (save-excursion
46b3d18e
RS
1242 (goto-char (point-min)) ;; begin searching in the buffer
1243 (while (not (eobp))
1244 (setq origpt (point))
1245 (when (setq endpt (re-search-forward regexp nil t))
1246 (setq matches (1+ matches)) ;; increment match count
5291cbca 1247 (setq matchbeg (match-beginning 0))
774642e5 1248 ;; Get beginning of first match line and end of the last.
f1f007dc
JL
1249 (save-excursion
1250 (goto-char matchbeg)
774642e5
JL
1251 (setq begpt (line-beginning-position))
1252 (goto-char endpt)
1253 (setq endpt (line-end-position)))
1254 ;; Sum line numbers up to the first match line.
1255 (setq lines (+ lines (count-lines origpt begpt)))
46b3d18e
RS
1256 (setq marker (make-marker))
1257 (set-marker marker matchbeg)
53e87c57 1258 (setq curstring (occur-engine-line begpt endpt keep-props))
8b363e6f 1259 ;; Highlight the matches
46b3d18e
RS
1260 (let ((len (length curstring))
1261 (start 0))
46b3d18e
RS
1262 (while (and (< start len)
1263 (string-match regexp curstring start))
f1f007dc
JL
1264 (add-text-properties
1265 (match-beginning 0) (match-end 0)
1266 (append
1267 `(occur-match t)
1268 (when match-face
1269 ;; Use `face' rather than `font-lock-face' here
1270 ;; so as to override faces copied from the buffer.
1271 `(face ,match-face)))
1272 curstring)
46b3d18e
RS
1273 (setq start (match-end 0))))
1274 ;; Generate the string to insert for this match
774642e5
JL
1275 (let* ((match-prefix
1276 ;; Using 7 digits aligns tabs properly.
1277 (apply #'propertize (format "%7d:" lines)
1278 (append
1279 (when prefix-face
1280 `(font-lock-face prefix-face))
1281 `(occur-prefix t mouse-face (highlight)
1282 occur-target ,marker follow-link t
1283 help-echo "mouse-2: go to this occurrence"))))
1284 (match-str
1285 ;; We don't put `mouse-face' on the newline,
1286 ;; because that loses. And don't put it
1287 ;; on context lines to reduce flicker.
1288 (propertize curstring 'mouse-face (list 'highlight)
1289 'occur-target marker
1290 'follow-link t
1291 'help-echo
1292 "mouse-2: go to this occurrence"))
1293 (out-line
46b3d18e 1294 (concat
774642e5
JL
1295 match-prefix
1296 ;; Add non-numeric prefix to all non-first lines
1297 ;; of multi-line matches.
1298 (replace-regexp-in-string
1299 "\n"
1300 "\n :"
1301 match-str)
61f570e2
RF
1302 ;; Add marker at eol, but no mouse props.
1303 (propertize "\n" 'occur-target marker)))
46b3d18e
RS
1304 (data
1305 (if (= nlines 0)
1306 ;; The simple display style
1307 out-line
f8edc67e 1308 ;; The complex multi-line display style.
dc2d2590
JL
1309 (setq ret (occur-context-lines
1310 out-line nlines keep-props begpt endpt
1311 lines prev-lines prev-after-lines))
1312 ;; Set first elem of the returned list to `data',
1313 ;; and the second elem to `prev-after-lines'.
1314 (setq prev-after-lines (nth 1 ret))
1315 (nth 0 ret))))
46b3d18e
RS
1316 ;; Actually insert the match display data
1317 (with-current-buffer out-buf
1318 (let ((beg (point))
dc2d2590 1319 (end (progn (insert data) (point)))))))
46b3d18e 1320 (goto-char endpt))
e1690783
CW
1321 (if endpt
1322 (progn
774642e5
JL
1323 ;; Sum line numbers between first and last match lines.
1324 (setq lines (+ lines (count-lines begpt endpt)
1325 ;; Add 1 for empty last match line since
1326 ;; count-lines returns 1 line less.
1327 (if (and (bolp) (eolp)) 1 0)))
e1690783
CW
1328 ;; On to the next match...
1329 (forward-line 1))
dc2d2590
JL
1330 (goto-char (point-max)))
1331 (setq prev-lines (1- lines)))
1332 ;; Flush remaining context after-lines.
1333 (when prev-after-lines
1334 (with-current-buffer out-buf
1335 (insert (apply #'concat (occur-engine-add-prefix
1336 prev-after-lines)))))))
46b3d18e 1337 (when (not (zerop matches)) ;; is the count zero?
daae70bf 1338 (setq globalcount (+ globalcount matches))
46b3d18e
RS
1339 (with-current-buffer out-buf
1340 (goto-char headerpt)
1341 (let ((beg (point))
1342 end)
d66ecdbb 1343 (insert (format "%d match%s%s in buffer: %s\n"
dbed3cd3 1344 matches (if (= matches 1) "" "es")
d66ecdbb
JL
1345 ;; Don't display regexp for multi-buffer.
1346 (if (> (length buffers) 1)
1347 "" (format " for \"%s\""
1348 (query-replace-descr regexp)))
1349 (buffer-name buf)))
46b3d18e
RS
1350 (setq end (point))
1351 (add-text-properties beg end
1352 (append
1353 (when title-face
506a6d7e
CW
1354 `(font-lock-face ,title-face))
1355 `(occur-title ,buf))))
46b3d18e 1356 (goto-char (point-min)))))))
d66ecdbb
JL
1357 ;; Display total match count and regexp for multi-buffer.
1358 (when (and (not (zerop globalcount)) (> (length buffers) 1))
1359 (goto-char (point-min))
1360 (let ((beg (point))
1361 end)
1362 (insert (format "%d match%s total for \"%s\":\n"
1363 globalcount (if (= globalcount 1) "" "es")
1364 (query-replace-descr regexp)))
1365 (setq end (point))
1366 (add-text-properties beg end (when title-face
1367 `(font-lock-face ,title-face))))
1368 (goto-char (point-min)))
5cb4031d
KH
1369 (if coding
1370 ;; CODING is buffer-file-coding-system of the first buffer
1371 ;; that locally binds it. Let's use it also for the output
1372 ;; buffer.
1373 (set-buffer-file-coding-system coding))
46b3d18e
RS
1374 ;; Return the number of matches
1375 globalcount)))
68608d9c 1376
53e87c57 1377(defun occur-engine-line (beg end &optional keep-props)
f14d1172
JL
1378 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1379 (text-property-not-all beg end 'fontified t))
1380 (if (fboundp 'jit-lock-fontify-now)
1381 (jit-lock-fontify-now beg end)))
1382 (if (and keep-props (not (eq occur-excluded-properties t)))
1383 (let ((str (buffer-substring beg end)))
1384 (remove-list-of-text-properties
1385 0 (length str) occur-excluded-properties str)
1386 str)
1387 (buffer-substring-no-properties beg end)))
1388
0ef84fc8
JL
1389(defun occur-engine-add-prefix (lines)
1390 (mapcar
1391 #'(lambda (line)
1392 (concat " :" line "\n"))
1393 lines))
1394
1395(defun occur-accumulate-lines (count &optional keep-props pt)
1396 (save-excursion
1397 (when pt
1398 (goto-char pt))
1399 (let ((forwardp (> count 0))
1400 result beg end moved)
1401 (while (not (or (zerop count)
1402 (if forwardp
1403 (eobp)
1404 (and (bobp) (not moved)))))
1405 (setq count (+ count (if forwardp -1 1)))
1406 (setq beg (line-beginning-position)
1407 end (line-end-position))
1408 (push (occur-engine-line beg end keep-props) result)
1409 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1410 (nreverse result))))
1411
f8edc67e
RS
1412;; Generate context display for occur.
1413;; OUT-LINE is the line where the match is.
1414;; NLINES and KEEP-PROPS are args to occur-engine.
dc2d2590
JL
1415;; LINES is line count of the current match,
1416;; PREV-LINES is line count of the previous match,
1417;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
f8edc67e
RS
1418;; Generate a list of lines, add prefixes to all but OUT-LINE,
1419;; then concatenate them all together.
dc2d2590
JL
1420(defun occur-context-lines (out-line nlines keep-props begpt endpt
1421 lines prev-lines prev-after-lines)
1422 ;; Find after- and before-context lines of the current match.
1423 (let ((before-lines
1424 (nreverse (cdr (occur-accumulate-lines
1425 (- (1+ (abs nlines))) keep-props begpt))))
1426 (after-lines
1427 (cdr (occur-accumulate-lines
1428 (1+ nlines) keep-props endpt)))
1429 separator)
1430
1431 ;; Combine after-lines of the previous match
1432 ;; with before-lines of the current match.
1433
1434 (when prev-after-lines
1435 ;; Don't overlap prev after-lines with current before-lines.
1436 (if (>= (+ prev-lines (length prev-after-lines))
1437 (- lines (length before-lines)))
1438 (setq prev-after-lines
1439 (butlast prev-after-lines
1440 (- (length prev-after-lines)
1441 (- lines prev-lines (length before-lines) 1))))
1442 ;; Separate non-overlapping context lines with a dashed line.
1443 (setq separator "-------\n")))
1444
1445 (when prev-lines
1446 ;; Don't overlap current before-lines with previous match line.
1447 (if (<= (- lines (length before-lines))
1448 prev-lines)
1449 (setq before-lines
1450 (nthcdr (- (length before-lines)
1451 (- lines prev-lines 1))
1452 before-lines))
1453 ;; Separate non-overlapping before-context lines.
1454 (unless (> nlines 0)
1455 (setq separator "-------\n"))))
1456
1457 (list
1458 ;; Return a list where the first element is the output line.
1459 (apply #'concat
1460 (append
1461 (and prev-after-lines
1462 (occur-engine-add-prefix prev-after-lines))
1463 (and separator (list separator))
1464 (occur-engine-add-prefix before-lines)
1465 (list out-line)))
1466 ;; And the second element is the list of context after-lines.
1467 (if (> nlines 0) after-lines))))
1468
698e1804 1469\f
81bdc14d
RS
1470;; It would be nice to use \\[...], but there is no reasonable way
1471;; to make that display both SPC and Y.
698e1804
RS
1472(defconst query-replace-help
1473 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
be44f62c 1474RET or `q' to exit, Period to replace one match and exit,
698e1804
RS
1475Comma to replace but not move point immediately,
1476C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1477C-w to delete match and recursive edit,
1478C-l to clear the screen, redisplay, and offer same replacement again,
1479! to replace all remaining matches with no more questions,
7ce278f3
GM
1480^ to move point back to previous match,
1481E to edit the replacement string"
f54701d1 1482 "Help message while in `query-replace'.")
698e1804 1483
cedbd3f0
SM
1484(defvar query-replace-map
1485 (let ((map (make-sparse-keymap)))
1486 (define-key map " " 'act)
1487 (define-key map "\d" 'skip)
1488 (define-key map [delete] 'skip)
1489 (define-key map [backspace] 'skip)
1490 (define-key map "y" 'act)
1491 (define-key map "n" 'skip)
1492 (define-key map "Y" 'act)
1493 (define-key map "N" 'skip)
1494 (define-key map "e" 'edit-replacement)
1495 (define-key map "E" 'edit-replacement)
1496 (define-key map "," 'act-and-show)
1497 (define-key map "q" 'exit)
1498 (define-key map "\r" 'exit)
1499 (define-key map [return] 'exit)
1500 (define-key map "." 'act-and-exit)
1501 (define-key map "\C-r" 'edit)
1502 (define-key map "\C-w" 'delete-and-edit)
1503 (define-key map "\C-l" 'recenter)
1504 (define-key map "!" 'automatic)
1505 (define-key map "^" 'backup)
1506 (define-key map "\C-h" 'help)
1507 (define-key map [f1] 'help)
1508 (define-key map [help] 'help)
1509 (define-key map "?" 'help)
1510 (define-key map "\C-g" 'quit)
1511 (define-key map "\C-]" 'quit)
1512 (define-key map "\e" 'exit-prefix)
1513 (define-key map [escape] 'exit-prefix)
1514 map)
81bdc14d
RS
1515 "Keymap that defines the responses to questions in `query-replace'.
1516The \"bindings\" in this map are not commands; they are answers.
1517The valid answers include `act', `skip', `act-and-show',
1518`exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
d9121bc0 1519`automatic', `backup', `exit-prefix', and `help'.")
81bdc14d 1520
b591f338
JL
1521(defvar multi-query-replace-map
1522 (let ((map (make-sparse-keymap)))
1523 (set-keymap-parent map query-replace-map)
1524 (define-key map "Y" 'automatic-all)
1525 (define-key map "N" 'exit-current)
1526 map)
1527 "Keymap that defines additional bindings for multi-buffer replacements.
1528It extends its parent map `query-replace-map' with new bindings to
1529operate on a set of buffers/files. The difference with its parent map
1530is the additional answers `automatic-all' to replace all remaining
1531matches in all remaining buffers with no more questions, and
1532`exit-current' to skip remaining matches in the current buffer
1533and to continue with the next buffer in the sequence.")
1534
84482eb3 1535(defun replace-match-string-symbols (n)
e730be7f
DL
1536 "Process a list (and any sub-lists), expanding certain symbols.
1537Symbol Expands To
1538N (match-string N) (where N is a string of digits)
1539#N (string-to-number (match-string N))
1540& (match-string 0)
1541#& (string-to-number (match-string 0))
2f57bf85 1542# replace-count
e730be7f
DL
1543
1544Note that these symbols must be preceeded by a backslash in order to
f72f9f1a
RS
1545type them using Lisp syntax."
1546 (while (consp n)
84482eb3
RS
1547 (cond
1548 ((consp (car n))
1549 (replace-match-string-symbols (car n))) ;Process sub-list
1550 ((symbolp (car n))
1551 (let ((name (symbol-name (car n))))
1552 (cond
1553 ((string-match "^[0-9]+$" name)
1554 (setcar n (list 'match-string (string-to-number name))))
1555 ((string-match "^#[0-9]+$" name)
1556 (setcar n (list 'string-to-number
1557 (list 'match-string
1558 (string-to-number (substring name 1))))))
1559 ((string= "&" name)
1560 (setcar n '(match-string 0)))
1561 ((string= "#&" name)
2f57bf85
DK
1562 (setcar n '(string-to-number (match-string 0))))
1563 ((string= "#" name)
1564 (setcar n 'replace-count))))))
84482eb3
RS
1565 (setq n (cdr n))))
1566
1567(defun replace-eval-replacement (expression replace-count)
1568 (let ((replacement (eval expression)))
1569 (if (stringp replacement)
1570 replacement
1571 (prin1-to-string replacement t))))
1572
2f57bf85
DK
1573(defun replace-quote (replacement)
1574 "Quote a replacement string.
1575This just doubles all backslashes in REPLACEMENT and
1576returns the resulting string. If REPLACEMENT is not
1577a string, it is first passed through `prin1-to-string'
1578with the `noescape' argument set.
1579
1580`match-data' is preserved across the call."
1581 (save-match-data
1582 (replace-regexp-in-string "\\\\" "\\\\"
1583 (if (stringp replacement)
1584 replacement
1585 (prin1-to-string replacement t))
1586 t t)))
1587
84482eb3
RS
1588(defun replace-loop-through-replacements (data replace-count)
1589 ;; DATA is a vector contaning the following values:
1590 ;; 0 next-rotate-count
1591 ;; 1 repeat-count
1592 ;; 2 next-replacement
1593 ;; 3 replacements
1594 (if (= (aref data 0) replace-count)
1595 (progn
1596 (aset data 0 (+ replace-count (aref data 1)))
1597 (let ((next (cdr (aref data 2))))
1598 (aset data 2 (if (consp next) next (aref data 3))))))
1599 (car (aref data 2)))
1600
7c1c02ac
DK
1601(defun replace-match-data (integers reuse &optional new)
1602 "Like `match-data', but markers in REUSE get invalidated.
6a964bb1 1603If NEW is non-nil, it is set and returned instead of fresh data,
7c1c02ac
DK
1604but coerced to the correct value of INTEGERS."
1605 (or (and new
1606 (progn
1607 (set-match-data new)
1608 (and (eq new reuse)
1609 (eq (null integers) (markerp (car reuse)))
1610 new)))
10ddc30e 1611 (match-data integers reuse t)))
7c1c02ac
DK
1612
1613(defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1614 "Make a replacement with `replace-match', editing `\\?'.
15fd7d5d 1615NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
7c1c02ac
DK
1616check for `\\?' is made to save time. MATCH-DATA is used for the
1617replacement. In case editing is done, it is changed to use markers.
1618
6a964bb1 1619The return value is non-nil if there has been no `\\?' or NOEDIT was
7c1c02ac
DK
1620passed in. If LITERAL is set, no checking is done, anyway."
1621 (unless (or literal noedit)
1622 (setq noedit t)
1623 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1624 newtext)
1625 (setq newtext
3981e5b5
JB
1626 (read-string "Edit replacement string: "
1627 (prog1
1628 (cons
1629 (replace-match "" t t newtext 3)
1630 (1+ (match-beginning 3)))
1631 (setq match-data
1632 (replace-match-data
1633 nil match-data match-data))))
7c1c02ac
DK
1634 noedit nil)))
1635 (set-match-data match-data)
1636 (replace-match newtext fixedcase literal)
1637 noedit)
1638
c35a09fc
CY
1639(defvar replace-search-function 'search-forward
1640 "Function to use when searching for strings to replace.
1641It is used by `query-replace' and `replace-string', and is called
1642with three arguments, as if it were `search-forward'.")
1643
1644(defvar replace-re-search-function 're-search-forward
1645 "Function to use when searching for regexps to replace.
1646It is used by `query-replace-regexp', `replace-regexp',
96f606c5
JL
1647`query-replace-regexp-eval', and `map-query-replace-regexp'.
1648It is called with three arguments, as if it were
1649`re-search-forward'.")
c35a09fc 1650
d99118b0 1651(defun perform-replace (from-string replacements
698e1804 1652 query-flag regexp-flag delimited-flag
99a7559f 1653 &optional repeat-count map start end)
698e1804
RS
1654 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1655Don't use this in your own program unless you want to query and set the mark
1656just as `query-replace' does. Instead, write a simple loop like this:
698665d1
GM
1657
1658 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
698e1804 1659 (replace-match \"foobar\" nil nil))
698665d1
GM
1660
1661which will run faster and probably do exactly what you want. Please
1662see the documentation of `replace-match' to find out how to simulate
588c915a
CW
1663`case-replace'.
1664
1665This function returns nil if and only if there were no matches to
1666make, or the user didn't cancel the call."
81bdc14d 1667 (or map (setq map query-replace-map))
1c1dadab
RS
1668 (and query-flag minibuffer-auto-raise
1669 (raise-frame (window-frame (minibuffer-window))))
26cc71af 1670 (let* ((case-fold-search
3be42fcd
JL
1671 (if (and case-fold-search search-upper-case)
1672 (isearch-no-upper-case-p from-string regexp-flag)
1673 case-fold-search))
26cc71af
SM
1674 (nocasify (not (and case-replace case-fold-search)))
1675 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
c35a09fc
CY
1676 (search-function
1677 (if regexp-flag
1678 replace-re-search-function
1679 replace-search-function))
26cc71af
SM
1680 (search-string from-string)
1681 (real-match-data nil) ; The match data for the current match.
1682 (next-replacement nil)
1683 ;; This is non-nil if we know there is nothing for the user
1684 ;; to edit in the replacement.
1685 (noedit nil)
1686 (keep-going t)
1687 (stack nil)
1688 (replace-count 0)
1689 (nonempty-match nil)
b591f338 1690 (multi-buffer nil)
2952b1ae 1691 (recenter-last-op nil) ; Start cycling order with initial position.
26cc71af
SM
1692
1693 ;; If non-nil, it is marker saying where in the buffer to stop.
1694 (limit nil)
1695
1696 ;; Data for the next match. If a cons, it has the same format as
1697 ;; (match-data); otherwise it is t if a match is possible at point.
1698 (match-again t)
1699
1700 (message
1701 (if query-flag
1702 (apply 'propertize
1703 (substitute-command-keys
1704 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1705 minibuffer-prompt-properties))))
7ef5c431
KH
1706
1707 ;; If region is active, in Transient Mark mode, operate on region.
47d72254
GM
1708 (when start
1709 (setq limit (copy-marker (max start end)))
1710 (goto-char (min start end))
1711 (deactivate-mark))
84482eb3 1712
b591f338
JL
1713 ;; If last typed key in previous call of multi-buffer perform-replace
1714 ;; was `automatic-all', don't ask more questions in next files
1e4bd40d 1715 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
b591f338
JL
1716 (setq query-flag nil multi-buffer t))
1717
84482eb3
RS
1718 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1719 ;; containing a function and its first argument. The function is
1720 ;; called to generate each replacement like this:
1721 ;; (funcall (car replacements) (cdr replacements) replace-count)
1722 ;; It must return a string.
1723 (cond
1724 ((stringp replacements)
1725 (setq next-replacement replacements
1726 replacements nil))
1727 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1728 (or repeat-count (setq repeat-count 1))
1729 (setq replacements (cons 'replace-loop-through-replacements
1730 (vector repeat-count repeat-count
1731 replacements replacements)))))
1732
698e1804
RS
1733 (if delimited-flag
1734 (setq search-function 're-search-forward
1735 search-string (concat "\\b"
1736 (if regexp-flag from-string
1737 (regexp-quote from-string))
1738 "\\b")))
ccec9764 1739 (when query-replace-lazy-highlight
444697a1 1740 (setq isearch-lazy-highlight-last-string nil))
35d59c0f 1741
698e1804
RS
1742 (push-mark)
1743 (undo-boundary)
e782e9f2
RS
1744 (unwind-protect
1745 ;; Loop finding occurrences that perhaps should be replaced.
1746 (while (and keep-going
22a76778 1747 (not (or (eobp) (and limit (>= (point) limit))))
5632eb27
PE
1748 ;; Use the next match if it is already known;
1749 ;; otherwise, search for a match after moving forward
1750 ;; one char if progress is required.
1751 (setq real-match-data
b3aad29e
CY
1752 (cond ((consp match-again)
1753 (goto-char (nth 1 match-again))
1754 (replace-match-data
1755 t real-match-data match-again))
1756 ;; MATCH-AGAIN non-nil means accept an
1757 ;; adjacent match.
1758 (match-again
1759 (and
1760 (funcall search-function search-string
1761 limit t)
1762 ;; For speed, use only integers and
1763 ;; reuse the list used last time.
1764 (replace-match-data t real-match-data)))
1765 ((and (< (1+ (point)) (point-max))
1766 (or (null limit)
1767 (< (1+ (point)) limit)))
1768 ;; If not accepting adjacent matches,
1769 ;; move one char to the right before
1770 ;; searching again. Undo the motion
1771 ;; if the search fails.
1772 (let ((opoint (point)))
1773 (forward-char 1)
1774 (if (funcall
1775 search-function search-string
1776 limit t)
1777 (replace-match-data
1778 t real-match-data)
1779 (goto-char opoint)
1780 nil))))))
6a964bb1 1781
c0b45763
RS
1782 ;; Record whether the match is nonempty, to avoid an infinite loop
1783 ;; repeatedly matching the same empty string.
1784 (setq nonempty-match
1785 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1786
1787 ;; If the match is empty, record that the next one can't be
1788 ;; adjacent.
1789
1790 ;; Otherwise, if matching a regular expression, do the next
1791 ;; match now, since the replacement for this match may
1792 ;; affect whether the next match is adjacent to this one.
1793 ;; If that match is empty, don't use it.
1794 (setq match-again
1795 (and nonempty-match
1796 (or (not regexp-flag)
1797 (and (looking-at search-string)
1798 (let ((match (match-data)))
1799 (and (/= (nth 0 match) (nth 1 match))
1800 match))))))
1801
1c4fe319
RS
1802 ;; Optionally ignore matches that have a read-only property.
1803 (unless (and query-replace-skip-read-only
1804 (text-property-not-all
c0b45763 1805 (nth 0 real-match-data) (nth 1 real-match-data)
1c4fe319
RS
1806 'read-only nil))
1807
1c4fe319
RS
1808 ;; Calculate the replacement string, if necessary.
1809 (when replacements
1810 (set-match-data real-match-data)
1811 (setq next-replacement
1812 (funcall (car replacements) (cdr replacements)
2f857176 1813 replace-count)))
1c4fe319 1814 (if (not query-flag)
f2e7b9ef 1815 (progn
15fd7d5d 1816 (unless (or literal noedit)
444697a1
JL
1817 (replace-highlight
1818 (nth 0 real-match-data) (nth 1 real-match-data)
1819 start end search-string
1820 (or delimited-flag regexp-flag) case-fold-search))
7c1c02ac
DK
1821 (setq noedit
1822 (replace-match-maybe-edit
1823 next-replacement nocasify literal
1824 noedit real-match-data)
1825 replace-count (1+ replace-count)))
1c4fe319
RS
1826 (undo-boundary)
1827 (let (done replaced key def)
1828 ;; Loop reading commands until one of them sets done,
7c1c02ac
DK
1829 ;; which means it has finished handling this
1830 ;; occurrence. Any command that sets `done' should
1831 ;; leave behind proper match data for the stack.
1832 ;; Commands not setting `done' need to adjust
1833 ;; `real-match-data'.
1c4fe319
RS
1834 (while (not done)
1835 (set-match-data real-match-data)
444697a1
JL
1836 (replace-highlight
1837 (match-beginning 0) (match-end 0)
1838 start end search-string
1839 (or delimited-flag regexp-flag) case-fold-search)
1c4fe319
RS
1840 ;; Bind message-log-max so we don't fill up the message log
1841 ;; with a bunch of identical messages.
7abe68aa
JL
1842 (let ((message-log-max nil)
1843 (replacement-presentation
1844 (if query-replace-show-replacement
1845 (save-match-data
1846 (set-match-data real-match-data)
1847 (match-substitute-replacement next-replacement
1848 nocasify literal))
1849 next-replacement)))
b938735a
JL
1850 (message message
1851 (query-replace-descr from-string)
7abe68aa 1852 (query-replace-descr replacement-presentation)))
1c4fe319
RS
1853 (setq key (read-event))
1854 ;; Necessary in case something happens during read-event
1855 ;; that clobbers the match data.
1856 (set-match-data real-match-data)
1857 (setq key (vector key))
1858 (setq def (lookup-key map key))
1859 ;; Restore the match data while we process the command.
1860 (cond ((eq def 'help)
1861 (with-output-to-temp-buffer "*Help*"
1862 (princ
1863 (concat "Query replacing "
04ff2dee 1864 (if delimited-flag "word " "")
1c4fe319
RS
1865 (if regexp-flag "regexp " "")
1866 from-string " with "
1867 next-replacement ".\n\n"
1868 (substitute-command-keys
1869 query-replace-help)))
1870 (with-current-buffer standard-output
1871 (help-mode))))
1872 ((eq def 'exit)
1873 (setq keep-going nil)
1874 (setq done t))
b591f338
JL
1875 ((eq def 'exit-current)
1876 (setq multi-buffer t keep-going nil done t))
1c4fe319
RS
1877 ((eq def 'backup)
1878 (if stack
588c915a 1879 (let ((elt (pop stack)))
7c1c02ac
DK
1880 (goto-char (nth 0 elt))
1881 (setq replaced (nth 1 elt)
1882 real-match-data
1883 (replace-match-data
1884 t real-match-data
1885 (nth 2 elt))))
1c4fe319
RS
1886 (message "No previous match")
1887 (ding 'no-terminate)
1888 (sit-for 1)))
1889 ((eq def 'act)
1890 (or replaced
7c1c02ac
DK
1891 (setq noedit
1892 (replace-match-maybe-edit
1893 next-replacement nocasify literal
1894 noedit real-match-data)
1895 replace-count (1+ replace-count)))
1c4fe319
RS
1896 (setq done t replaced t))
1897 ((eq def 'act-and-exit)
1898 (or replaced
7c1c02ac 1899 (setq noedit
da6eb51c 1900 (replace-match-maybe-edit
7c1c02ac
DK
1901 next-replacement nocasify literal
1902 noedit real-match-data)
1903 replace-count (1+ replace-count)))
1c4fe319
RS
1904 (setq keep-going nil)
1905 (setq done t replaced t))
1906 ((eq def 'act-and-show)
1907 (if (not replaced)
7c1c02ac
DK
1908 (setq noedit
1909 (replace-match-maybe-edit
1910 next-replacement nocasify literal
1911 noedit real-match-data)
1912 replace-count (1+ replace-count)
1913 real-match-data (replace-match-data
1914 t real-match-data)
1915 replaced t)))
b591f338 1916 ((or (eq def 'automatic) (eq def 'automatic-all))
1c4fe319 1917 (or replaced
7c1c02ac
DK
1918 (setq noedit
1919 (replace-match-maybe-edit
1920 next-replacement nocasify literal
1921 noedit real-match-data)
1922 replace-count (1+ replace-count)))
b591f338
JL
1923 (setq done t query-flag nil replaced t)
1924 (if (eq def 'automatic-all) (setq multi-buffer t)))
1c4fe319
RS
1925 ((eq def 'skip)
1926 (setq done t))
1927 ((eq def 'recenter)
2952b1ae
JL
1928 ;; `this-command' has the value `query-replace',
1929 ;; so we need to bind it to `recenter-top-bottom'
1930 ;; to allow it to detect a sequence of `C-l'.
1931 (let ((this-command 'recenter-top-bottom)
1932 (last-command 'recenter-top-bottom))
1933 (recenter-top-bottom)))
1c4fe319
RS
1934 ((eq def 'edit)
1935 (let ((opos (point-marker)))
7c1c02ac
DK
1936 (setq real-match-data (replace-match-data
1937 nil real-match-data
1938 real-match-data))
1c4fe319 1939 (goto-char (match-beginning 0))
86914dcc
RS
1940 (save-excursion
1941 (save-window-excursion
1942 (recursive-edit)))
7c1c02ac
DK
1943 (goto-char opos)
1944 (set-marker opos nil))
1c4fe319
RS
1945 ;; Before we make the replacement,
1946 ;; decide whether the search string
1947 ;; can match again just after this match.
1948 (if (and regexp-flag nonempty-match)
1949 (setq match-again (and (looking-at search-string)
1950 (match-data)))))
1c4fe319
RS
1951 ;; Edit replacement.
1952 ((eq def 'edit-replacement)
7c1c02ac
DK
1953 (setq real-match-data (replace-match-data
1954 nil real-match-data
1955 real-match-data)
1956 next-replacement
3981e5b5
JB
1957 (read-string "Edit replacement string: "
1958 next-replacement)
7c1c02ac
DK
1959 noedit nil)
1960 (if replaced
1961 (set-match-data real-match-data)
1962 (setq noedit
1963 (replace-match-maybe-edit
1964 next-replacement nocasify literal noedit
1965 real-match-data)
1966 replaced t))
1c4fe319 1967 (setq done t))
d99118b0 1968
1c4fe319 1969 ((eq def 'delete-and-edit)
7c1c02ac
DK
1970 (replace-match "" t t)
1971 (setq real-match-data (replace-match-data
1972 nil real-match-data))
1973 (replace-dehighlight)
1974 (save-excursion (recursive-edit))
1c4fe319
RS
1975 (setq replaced t))
1976 ;; Note: we do not need to treat `exit-prefix'
1977 ;; specially here, since we reread
1978 ;; any unrecognized character.
1979 (t
1980 (setq this-command 'mode-exited)
1981 (setq keep-going nil)
1982 (setq unread-command-events
1983 (append (listify-key-sequence key)
1984 unread-command-events))
35d59c0f 1985 (setq done t)))
ccec9764 1986 (when query-replace-lazy-highlight
2952b1ae 1987 ;; Force lazy rehighlighting only after replacements.
ccec9764 1988 (if (not (memq def '(skip backup)))
2952b1ae
JL
1989 (setq isearch-lazy-highlight-last-string nil)))
1990 (unless (eq def 'recenter)
1991 ;; Reset recenter cycling order to initial position.
1992 (setq recenter-last-op nil)))
1c4fe319
RS
1993 ;; Record previous position for ^ when we move on.
1994 ;; Change markers to numbers in the match data
1995 ;; since lots of markers slow down editing.
7c1c02ac 1996 (push (list (point) replaced
bace7209
LT
1997;;; If the replacement has already happened, all we need is the
1998;;; current match start and end. We could get this with a trivial
1999;;; match like
2000;;; (save-excursion (goto-char (match-beginning 0))
2001;;; (search-forward (match-string 0))
2002;;; (match-data t))
2003;;; if we really wanted to avoid manually constructing match data.
2004;;; Adding current-buffer is necessary so that match-data calls can
2005;;; return markers which are appropriate for editing.
7c1c02ac
DK
2006 (if replaced
2007 (list
2008 (match-beginning 0)
2009 (match-end 0)
2010 (current-buffer))
2011 (match-data t)))
2012 stack)))))
889617de 2013
e782e9f2 2014 (replace-dehighlight))
4d33492a
RS
2015 (or unread-command-events
2016 (message "Replaced %d occurrence%s"
2017 replace-count
2018 (if (= replace-count 1) "" "s")))
b591f338 2019 (or (and keep-going stack) multi-buffer)))
698e1804 2020
e782e9f2
RS
2021(defvar replace-overlay nil)
2022
444697a1
JL
2023(defun replace-highlight (match-beg match-end range-beg range-end
2024 string regexp case-fold)
ccec9764
JL
2025 (if query-replace-highlight
2026 (if replace-overlay
d532160f
RS
2027 (move-overlay replace-overlay match-beg match-end (current-buffer))
2028 (setq replace-overlay (make-overlay match-beg match-end))
a46961de 2029 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
ccec9764 2030 (overlay-put replace-overlay 'face 'query-replace)))
444697a1
JL
2031 (if query-replace-lazy-highlight
2032 (let ((isearch-string string)
2033 (isearch-regexp regexp)
0b60cc09 2034 (search-whitespace-regexp nil)
e54a1075
JB
2035 (isearch-case-fold-search case-fold)
2036 (isearch-forward t)
2037 (isearch-error nil))
201d895a
JL
2038 ;; Set isearch-word to nil because word-replace is regexp-based,
2039 ;; so `isearch-search-fun' should not use `word-search-forward'.
2040 (if (and isearch-word isearch-regexp) (setq isearch-word nil))
444697a1 2041 (isearch-lazy-highlight-new-loop range-beg range-end))))
ccec9764 2042
e782e9f2 2043(defun replace-dehighlight ()
ccec9764
JL
2044 (when replace-overlay
2045 (delete-overlay replace-overlay))
2046 (when query-replace-lazy-highlight
444697a1 2047 (lazy-highlight-cleanup lazy-highlight-cleanup)
ccec9764 2048 (setq isearch-lazy-highlight-last-string nil)))
e782e9f2 2049
6f1df6d9 2050;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
c88ab9ce 2051;;; replace.el ends here