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