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