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