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