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