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