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