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