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