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