*** empty log message ***
[bpt/emacs.git] / lisp / replace.el
CommitLineData
60370d40 1;;; replace.el --- replace commands for Emacs
c88ab9ce 2
2f57bf85
DK
3;; Copyright (C) 1985, 86, 87, 92, 94, 96, 1997, 2000, 2001, 2002,
4;; 2003, 2004 Free Software Foundation, Inc.
3a801d0c 5
30764597
PJ
6;; Maintainer: FSF
7
698e1804
RS
8;; This file is part of GNU Emacs.
9
10;; GNU Emacs is free software; you can redistribute it and/or modify
11;; it under the terms of the GNU General Public License as published by
e5d77022 12;; the Free Software Foundation; either version 2, or (at your option)
698e1804
RS
13;; any later version.
14
15;; GNU Emacs is distributed in the hope that it will be useful,
16;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18;; GNU General Public License for more details.
19
20;; You should have received a copy of the GNU General Public License
b578f267
EN
21;; along with GNU Emacs; see the file COPYING. If not, write to the
22;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23;; Boston, MA 02111-1307, USA.
698e1804 24
d9ecc911
ER
25;;; Commentary:
26
27;; This package supplies the string and regular-expression replace functions
28;; documented in the Emacs user's manual.
29
4f4b8eff 30;;; Code:
698e1804 31
9d325ebf 32(defcustom case-replace t
f54701d1 33 "*Non-nil means `query-replace' should preserve case in replacements."
9d325ebf
RS
34 :type 'boolean
35 :group 'matching)
77176e73 36
770970cb
RS
37(defvar query-replace-history nil)
38
1f3ade4f 39(defcustom query-replace-interactive nil
151270f3 40 "Non-nil means `query-replace' uses the last search string.
0ec4febd
JL
41That becomes the \"string to replace\".
42If value is `initial', the last search string is inserted into
43the minibuffer as an initial value for \"string to replace\"."
44 :type '(choice (const :tag "Off" nil)
45 (const :tag "Initial content" initial)
46 (other :tag "Use default value" t))
1f3ade4f 47 :group 'matching)
151270f3 48
bdb1c08f 49(defcustom query-replace-from-history-variable 'query-replace-history
f54701d1 50 "History list to use for the FROM argument of `query-replace' commands.
bdb1c08f
RS
51The value of this variable should be a symbol; that symbol
52is used as a variable to hold a history list for the strings
53or patterns to be replaced."
54 :group 'matching
cd32a7ba
DN
55 :type 'symbol
56 :version "20.3")
bdb1c08f
RS
57
58(defcustom query-replace-to-history-variable 'query-replace-history
f54701d1 59 "History list to use for the TO argument of `query-replace' commands.
bdb1c08f
RS
60The value of this variable should be a symbol; that symbol
61is used as a variable to hold a history list for replacement
62strings or patterns."
63 :group 'matching
cd32a7ba
DN
64 :type 'symbol
65 :version "20.3")
bdb1c08f 66
1c4fe319
RS
67(defcustom query-replace-skip-read-only nil
68 "*Non-nil means `query-replace' and friends ignore read-only matches."
69 :type 'boolean
70 :group 'matching
89e7ad59 71 :version "21.4")
1c4fe319 72
86914dcc
RS
73(defun query-replace-read-args (string regexp-flag &optional noerror)
74 (unless noerror
75 (barf-if-buffer-read-only))
770970cb 76 (let (from to)
0ec4febd
JL
77 (if (and query-replace-interactive
78 (not (eq query-replace-interactive 'initial)))
79 (setq from (car (if regexp-flag regexp-search-ring search-ring)))
2f2f7e58
RS
80 ;; The save-excursion here is in case the user marks and copies
81 ;; a region in order to specify the minibuffer input.
82 ;; That should not clobber the region for the query-replace itself.
83 (save-excursion
0ec4febd
JL
84 (setq from (read-from-minibuffer
85 (format "%s: " string)
86 (if (eq query-replace-interactive 'initial)
87 (car (if regexp-flag regexp-search-ring search-ring)))
88 nil nil
89 query-replace-from-history-variable
90 nil t)))
d9291fa3 91 ;; Warn if user types \n or \t, but don't reject the input.
2f57bf85
DK
92 (and regexp-flag
93 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
94 (let ((match (match-string 3 from)))
95 (cond
96 ((string= match "\\n")
97 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
98 ((string= match "\\t")
99 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
100 (sit-for 2))))
d9291fa3 101
2f2f7e58 102 (save-excursion
0ec4febd
JL
103 (setq to (read-from-minibuffer
104 (format "%s %s with: " string from)
105 nil nil nil
106 query-replace-to-history-variable from t)))
7c1c02ac
DK
107 (when (and regexp-flag
108 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
109 (let (pos list char)
110 (while
111 (progn
112 (setq pos (match-end 0))
113 (push (substring to 0 (- pos 2)) list)
114 (setq char (aref to (1- pos))
115 to (substring to pos))
116 (cond ((eq char ?\#)
117 (push '(number-to-string replace-count) list))
118 ((eq char ?\,)
119 (setq pos (read-from-string to))
120 (push `(replace-quote ,(car pos)) list)
9e5d1b63
RS
121 (let ((end
122 ;; Swallow a space after a symbol
123 ;; if there is a space.
124 (if (and (or (symbolp (car pos))
125 ;; Swallow a space after 'foo
126 ;; but not after (quote foo).
127 (and (eq (car-safe (car pos)) 'quote)
128 (= ?\( (aref to 0))))
129 (string-match " " to (cdr pos)))
130 (1+ (cdr pos))
131 (cdr pos))))
132 (setq to (substring to end)))))
7c1c02ac
DK
133 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
134 (setq to (nreverse (delete "" (cons to list)))))
135 (replace-match-string-symbols to)
da6eb51c 136 (setq to (cons 'replace-eval-replacement
7c1c02ac
DK
137 (if (> (length to) 1)
138 (cons 'concat to)
139 (car to)))))
10784bac 140 (list from to current-prefix-arg)))
770970cb 141
47d72254 142(defun query-replace (from-string to-string &optional delimited start end)
da44e784
RM
143 "Replace some occurrences of FROM-STRING with TO-STRING.
144As each match is found, the user must type a character saying
145what to do with it. For directions, type \\[help-command] at that time.
146
7ef5c431
KH
147In Transient Mark mode, if the mark is active, operate on the contents
148of the region. Otherwise, operate from point to the end of the buffer.
149
151270f3
RS
150If `query-replace-interactive' is non-nil, the last incremental search
151string is used as FROM-STRING--you don't have to specify it with the
152minibuffer.
153
446d9629
RS
154Matching is independent of case if `case-fold-search' is non-nil and
155FROM-STRING has no uppercase letters. Replacement transfers the case
156pattern of the old text to the new text, if `case-replace' and
157`case-fold-search' are non-nil and FROM-STRING has no uppercase
158letters. \(Transferring the case pattern means that if the old text
159matched is all caps, or capitalized, then its replacement is upcased
160or capitalized.)
9b0bf2b6 161
118a01c9 162Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
81bdc14d 163only matches surrounded by word boundaries.
47d72254 164Fourth and fifth arg START and END specify the region to operate on.
81bdc14d
RS
165
166To customize possible responses, change the \"bindings\" in `query-replace-map'."
10784bac
RS
167 (interactive (let ((common
168 (query-replace-read-args "Query replace" nil)))
169 (list (nth 0 common) (nth 1 common) (nth 2 common)
170 ;; These are done separately here
171 ;; so that command-history will record these expressions
172 ;; rather than the values they had this time.
173 (if (and transient-mark-mode mark-active)
174 (region-beginning))
175 (if (and transient-mark-mode mark-active)
176 (region-end)))))
99a7559f 177 (perform-replace from-string to-string t nil delimited nil nil start end))
7ef5c431 178
73fa8346 179(define-key esc-map "%" 'query-replace)
da44e784 180
47d72254 181(defun query-replace-regexp (regexp to-string &optional delimited start end)
da44e784
RM
182 "Replace some things after point matching REGEXP with TO-STRING.
183As each match is found, the user must type a character saying
184what to do with it. For directions, type \\[help-command] at that time.
185
7ef5c431
KH
186In Transient Mark mode, if the mark is active, operate on the contents
187of the region. Otherwise, operate from point to the end of the buffer.
188
151270f3
RS
189If `query-replace-interactive' is non-nil, the last incremental search
190regexp is used as REGEXP--you don't have to specify it with the
191minibuffer.
192
446d9629
RS
193Matching is independent of case if `case-fold-search' is non-nil and
194REGEXP has no uppercase letters. Replacement transfers the case
195pattern of the old text to the new text, if `case-replace' and
196`case-fold-search' are non-nil and REGEXP has no uppercase letters.
197\(Transferring the case pattern means that if the old text matched is
198all caps, or capitalized, then its replacement is upcased or
199capitalized.)
47d72254 200
118a01c9 201Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
da44e784 202only matches surrounded by word boundaries.
47d72254
GM
203Fourth and fifth arg START and END specify the region to operate on.
204
118a01c9
RS
205In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
206and `\\=\\N' (where N is a digit) stands for
2f57bf85 207whatever what matched the Nth `\\(...\\)' in REGEXP.
7c1c02ac
DK
208`\\?' lets you edit the replacement text in the minibuffer
209at the given position for each replacement.
210
ba8d15f9
RS
211In interactive calls, the replacement text can contain `\\,'
212followed by a Lisp expression. Each
213replacement evaluates that expression to compute the replacement
214string. Inside of that expression, `\\&' is a string denoting the
215whole match as a sting, `\\N' for a partial match, `\\#&' and `\\#N'
216for the whole or a partial match converted to a number with
217`string-to-number', and `\\#' itself for the number of replacements
218done so far (starting with zero).
7c1c02ac 219
ba8d15f9
RS
220If the replacement expression is a symbol, write a space after it
221to terminate it. One space there, if any, will be discarded.
7c1c02ac
DK
222
223When using those Lisp features interactively in the replacement
224text, TO-STRING is actually made a list instead of a string.
225Use \\[repeat-complex-command] after this command for details."
10784bac
RS
226 (interactive
227 (let ((common
228 (query-replace-read-args "Query replace regexp" t)))
7c1c02ac
DK
229 (list (nth 0 common) (nth 1 common) (nth 2 common)
230 ;; These are done separately here
231 ;; so that command-history will record these expressions
232 ;; rather than the values they had this time.
233 (if (and transient-mark-mode mark-active)
234 (region-beginning))
235 (if (and transient-mark-mode mark-active)
236 (region-end)))))
99a7559f 237 (perform-replace regexp to-string t t delimited nil nil start end))
2f57bf85 238
cbc127de 239(define-key esc-map [?\C-%] 'query-replace-regexp)
da44e784 240
47d72254 241(defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
84482eb3
RS
242 "Replace some things after point matching REGEXP with the result of TO-EXPR.
243As each match is found, the user must type a character saying
244what to do with it. For directions, type \\[help-command] at that time.
245
246TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
247reference `replace-count' to get the number of replacements already made.
248If the result of TO-EXPR is not a string, it is converted to one using
249`prin1-to-string' with the NOESCAPE argument (which see).
250
251For convenience, when entering TO-EXPR interactively, you can use `\\&' or
653479ad
AS
252`\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
253N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
84482eb3 254Use `\\#&' or `\\#N' if you want a number instead of a string.
2f57bf85 255In interactive use, `\\#' in itself stands for `replace-count'.
84482eb3
RS
256
257In Transient Mark mode, if the mark is active, operate on the contents
258of the region. Otherwise, operate from point to the end of the buffer.
259
260If `query-replace-interactive' is non-nil, the last incremental search
261regexp is used as REGEXP--you don't have to specify it with the
262minibuffer.
263
264Preserves case in each replacement if `case-replace' and `case-fold-search'
265are non-nil and REGEXP has no uppercase letters.
47d72254 266
84482eb3 267Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
470bbe9b 268only matches that are surrounded by word boundaries.
47d72254 269Fourth and fifth arg START and END specify the region to operate on."
84482eb3 270 (interactive
10784bac 271 (let (from to)
84482eb3
RS
272 (if query-replace-interactive
273 (setq from (car regexp-search-ring))
274 (setq from (read-from-minibuffer "Query replace regexp: "
275 nil nil nil
276 query-replace-from-history-variable
277 nil t)))
278 (setq to (list (read-from-minibuffer
279 (format "Query replace regexp %s with eval: " from)
280 nil nil t query-replace-to-history-variable from t)))
281 ;; We make TO a list because replace-match-string-symbols requires one,
282 ;; and the user might enter a single token.
283 (replace-match-string-symbols to)
10784bac
RS
284 (list from (car to) current-prefix-arg
285 (if (and transient-mark-mode mark-active)
286 (region-beginning))
287 (if (and transient-mark-mode mark-active)
288 (region-end)))))
d2ce3151 289 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
d83a97ab 290 t 'literal delimited nil nil start end))
84482eb3 291
47d72254 292(defun map-query-replace-regexp (regexp to-strings &optional n start end)
da44e784 293 "Replace some matches for REGEXP with various strings, in rotation.
e730be7f
DL
294The second argument TO-STRINGS contains the replacement strings,
295separated by spaces. Third arg DELIMITED (prefix arg if interactive),
296if non-nil, means replace only matches surrounded by word boundaries.
297This command works like `query-replace-regexp' except that each
298successive replacement uses the next successive replacement string,
da44e784
RM
299wrapping around from the last such string to the first.
300
7ef5c431
KH
301In Transient Mark mode, if the mark is active, operate on the contents
302of the region. Otherwise, operate from point to the end of the buffer.
303
da44e784
RM
304Non-interactively, TO-STRINGS may be a list of replacement strings.
305
151270f3
RS
306If `query-replace-interactive' is non-nil, the last incremental search
307regexp is used as REGEXP--you don't have to specify it with the minibuffer.
308
da44e784 309A prefix argument N says to use each replacement string N times
47d72254
GM
310before rotating to the next.
311Fourth and fifth arg START and END specify the region to operate on."
770970cb 312 (interactive
10784bac 313 (let (from to)
151270f3
RS
314 (setq from (if query-replace-interactive
315 (car regexp-search-ring)
316 (read-from-minibuffer "Map query replace (regexp): "
317 nil nil nil
fce31d51 318 'query-replace-history nil t)))
770970cb
RS
319 (setq to (read-from-minibuffer
320 (format "Query replace %s with (space-separated strings): "
321 from)
322 nil nil nil
4a8f3b3d 323 'query-replace-history from t))
2f2f7e58
RS
324 (list from to
325 (and current-prefix-arg
326 (prefix-numeric-value current-prefix-arg))
10784bac
RS
327 (if (and transient-mark-mode mark-active)
328 (region-beginning))
329 (if (and transient-mark-mode mark-active)
330 (region-end)))))
da44e784
RM
331 (let (replacements)
332 (if (listp to-strings)
333 (setq replacements to-strings)
334 (while (/= (length to-strings) 0)
335 (if (string-match " " to-strings)
336 (setq replacements
337 (append replacements
338 (list (substring to-strings 0
339 (string-match " " to-strings))))
340 to-strings (substring to-strings
341 (1+ (string-match " " to-strings))))
342 (setq replacements (append replacements (list to-strings))
343 to-strings ""))))
99a7559f 344 (perform-replace regexp replacements t t nil n nil start end)))
da44e784 345
47d72254 346(defun replace-string (from-string to-string &optional delimited start end)
da44e784
RM
347 "Replace occurrences of FROM-STRING with TO-STRING.
348Preserve case in each match if `case-replace' and `case-fold-search'
349are non-nil and FROM-STRING has no uppercase letters.
9b0bf2b6
RS
350\(Preserving case means that if the string matched is all caps, or capitalized,
351then its replacement is upcased or capitalized.)
352
7ef5c431
KH
353In Transient Mark mode, if the mark is active, operate on the contents
354of the region. Otherwise, operate from point to the end of the buffer.
355
118a01c9 356Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
da44e784 357only matches surrounded by word boundaries.
47d72254 358Fourth and fifth arg START and END specify the region to operate on.
da44e784 359
151270f3
RS
360If `query-replace-interactive' is non-nil, the last incremental search
361string is used as FROM-STRING--you don't have to specify it with the
362minibuffer.
363
da44e784
RM
364This function is usually the wrong thing to use in a Lisp program.
365What you probably want is a loop like this:
118a01c9
RS
366 (while (search-forward FROM-STRING nil t)
367 (replace-match TO-STRING nil t))
87532fbe
RS
368which will run faster and will not set the mark or print anything.
369\(You may need a more complex loop if FROM-STRING can match the null string
370and TO-STRING is also null.)"
10784bac
RS
371 (interactive
372 (let ((common
373 (query-replace-read-args "Replace string" nil)))
374 (list (nth 0 common) (nth 1 common) (nth 2 common)
375 (if (and transient-mark-mode mark-active)
376 (region-beginning))
377 (if (and transient-mark-mode mark-active)
378 (region-end)))))
99a7559f 379 (perform-replace from-string to-string nil nil delimited nil nil start end))
da44e784 380
47d72254 381(defun replace-regexp (regexp to-string &optional delimited start end)
da44e784 382 "Replace things after point matching REGEXP with TO-STRING.
118a01c9 383Preserve case in each match if `case-replace' and `case-fold-search'
da44e784 384are non-nil and REGEXP has no uppercase letters.
47d72254
GM
385
386In Transient Mark mode, if the mark is active, operate on the contents
387of the region. Otherwise, operate from point to the end of the buffer.
388
118a01c9 389Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
da44e784 390only matches surrounded by word boundaries.
47d72254
GM
391Fourth and fifth arg START and END specify the region to operate on.
392
118a01c9
RS
393In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
394and `\\=\\N' (where N is a digit) stands for
7c1c02ac
DK
395whatever what matched the Nth `\\(...\\)' in REGEXP.
396`\\?' lets you edit the replacement text in the minibuffer
397at the given position for each replacement.
398
399In interactive calls, the replacement text may contain `\\,'
400followed by a Lisp expression used as part of the replacement
401text. Inside of that expression, `\\&' is a string denoting the
402whole match, `\\N' a partial matches, `\\#&' and `\\#N' the
403respective numeric values from `string-to-number', and `\\#'
404itself for `replace-count', the number of replacements occured so
405far.
406
407If your Lisp expression is an identifier and the next letter in
408the replacement string would be interpreted as part of it, you
409can wrap it with an expression like `\\,(or \\#)'. Incidentally,
410for this particular case you may also enter `\\#' in the
411replacement text directly.
412
413When using those Lisp features interactively in the replacement
414text, TO-STRING is actually made a list instead of a string.
415Use \\[repeat-complex-command] after this command for details.
da44e784 416
151270f3
RS
417If `query-replace-interactive' is non-nil, the last incremental search
418regexp is used as REGEXP--you don't have to specify it with the minibuffer.
419
da44e784
RM
420This function is usually the wrong thing to use in a Lisp program.
421What you probably want is a loop like this:
422 (while (re-search-forward REGEXP nil t)
118a01c9 423 (replace-match TO-STRING nil nil))
da44e784 424which will run faster and will not set the mark or print anything."
10784bac
RS
425 (interactive
426 (let ((common
427 (query-replace-read-args "Replace regexp" t)))
428 (list (nth 0 common) (nth 1 common) (nth 2 common)
429 (if (and transient-mark-mode mark-active)
430 (region-beginning))
431 (if (and transient-mark-mode mark-active)
432 (region-end)))))
99a7559f 433 (perform-replace regexp to-string nil t delimited nil nil start end))
e32eb3e6 434
4c53bd2b
RS
435\f
436(defvar regexp-history nil
437 "History list for some commands that read regular expressions.")
da44e784 438
e32eb3e6 439
31e1d920 440(defalias 'delete-non-matching-lines 'keep-lines)
e32eb3e6
GM
441(defalias 'delete-matching-lines 'flush-lines)
442(defalias 'count-matches 'how-many)
443
444
445(defun keep-lines-read-args (prompt)
446 "Read arguments for `keep-lines' and friends.
447Prompt for a regexp with PROMPT.
2ced751f
RS
448Value is a list, (REGEXP)."
449 (list (read-from-minibuffer prompt nil nil nil
450 'regexp-history nil t)))
e32eb3e6
GM
451
452(defun keep-lines (regexp &optional rstart rend)
698e1804
RS
453 "Delete all lines except those containing matches for REGEXP.
454A match split across lines preserves all the lines it lies in.
d2a0ee8b
RS
455Applies to all lines after point.
456
457If REGEXP contains upper case characters (excluding those preceded by `\\'),
e32eb3e6
GM
458the matching is case-sensitive.
459
460Second and third arg RSTART and REND specify the region to operate on.
461
2ced751f
RS
462Interactively, in Transient Mark mode when the mark is active, operate
463on the contents of the region. Otherwise, operate from point to the
464end of the buffer."
465
e32eb3e6 466 (interactive
98faf1bb
RS
467 (progn
468 (barf-if-buffer-read-only)
469 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
e32eb3e6 470 (if rstart
119831da
RS
471 (progn
472 (goto-char (min rstart rend))
473 (setq rend (copy-marker (max rstart rend))))
2ced751f
RS
474 (if (and transient-mark-mode mark-active)
475 (setq rstart (region-beginning)
476 rend (copy-marker (region-end)))
477 (setq rstart (point)
478 rend (point-max-marker)))
479 (goto-char rstart))
698e1804
RS
480 (save-excursion
481 (or (bolp) (forward-line 1))
d2a0ee8b
RS
482 (let ((start (point))
483 (case-fold-search (and case-fold-search
484 (isearch-no-upper-case-p regexp t))))
e32eb3e6 485 (while (< (point) rend)
698e1804 486 ;; Start is first char not preserved by previous match.
e32eb3e6
GM
487 (if (not (re-search-forward regexp rend 'move))
488 (delete-region start rend)
698e1804
RS
489 (let ((end (save-excursion (goto-char (match-beginning 0))
490 (beginning-of-line)
491 (point))))
492 ;; Now end is first char preserved by the new match.
493 (if (< start end)
494 (delete-region start end))))
d99118b0 495
e32eb3e6 496 (setq start (save-excursion (forward-line 1) (point)))
698e1804 497 ;; If the match was empty, avoid matching again at same place.
e32eb3e6
GM
498 (and (< (point) rend)
499 (= (match-beginning 0) (match-end 0))
698e1804
RS
500 (forward-char 1))))))
501
e32eb3e6
GM
502
503(defun flush-lines (regexp &optional rstart rend)
698e1804
RS
504 "Delete lines containing matches for REGEXP.
505If a match is split across lines, all the lines it lies in are deleted.
d2a0ee8b
RS
506Applies to lines after point.
507
508If REGEXP contains upper case characters (excluding those preceded by `\\'),
e32eb3e6
GM
509the matching is case-sensitive.
510
511Second and third arg RSTART and REND specify the region to operate on.
512
2ced751f
RS
513Interactively, in Transient Mark mode when the mark is active, operate
514on the contents of the region. Otherwise, operate from point to the
515end of the buffer."
516
e32eb3e6 517 (interactive
98faf1bb
RS
518 (progn
519 (barf-if-buffer-read-only)
520 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
e32eb3e6 521 (if rstart
119831da
RS
522 (progn
523 (goto-char (min rstart rend))
524 (setq rend (copy-marker (max rstart rend))))
2ced751f
RS
525 (if (and transient-mark-mode mark-active)
526 (setq rstart (region-beginning)
527 rend (copy-marker (region-end)))
528 (setq rstart (point)
529 rend (point-max-marker)))
530 (goto-char rstart))
d2a0ee8b
RS
531 (let ((case-fold-search (and case-fold-search
532 (isearch-no-upper-case-p regexp t))))
533 (save-excursion
e32eb3e6
GM
534 (while (and (< (point) rend)
535 (re-search-forward regexp rend t))
d2a0ee8b
RS
536 (delete-region (save-excursion (goto-char (match-beginning 0))
537 (beginning-of-line)
538 (point))
539 (progn (forward-line 1) (point)))))))
698e1804 540
e32eb3e6
GM
541
542(defun how-many (regexp &optional rstart rend)
d2a0ee8b
RS
543 "Print number of matches for REGEXP following point.
544
545If REGEXP contains upper case characters (excluding those preceded by `\\'),
e32eb3e6
GM
546the matching is case-sensitive.
547
548Second and third arg RSTART and REND specify the region to operate on.
549
2ced751f
RS
550Interactively, in Transient Mark mode when the mark is active, operate
551on the contents of the region. Otherwise, operate from point to the
552end of the buffer."
553
e32eb3e6
GM
554 (interactive
555 (keep-lines-read-args "How many matches for (regexp): "))
f601efb0
SM
556 (save-excursion
557 (if rstart
558 (goto-char (min rstart rend))
2ced751f
RS
559 (if (and transient-mark-mode mark-active)
560 (setq rstart (region-beginning)
561 rend (copy-marker (region-end)))
562 (setq rstart (point)
563 rend (point-max-marker)))
564 (goto-char rstart))
f601efb0
SM
565 (let ((count 0)
566 opoint
567 (case-fold-search (and case-fold-search
568 (isearch-no-upper-case-p regexp t))))
569 (while (and (< (point) rend)
570 (progn (setq opoint (point))
571 (re-search-forward regexp rend t)))
572 (if (= opoint (point))
573 (forward-char 1)
574 (setq count (1+ count))))
575 (message "%d occurrences" count))))
e32eb3e6 576
4c53bd2b 577\f
f601efb0
SM
578(defvar occur-mode-map
579 (let ((map (make-sparse-keymap)))
580 (define-key map [mouse-2] 'occur-mode-mouse-goto)
581 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
582 (define-key map "\C-m" 'occur-mode-goto-occurrence)
daae70bf 583 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
365486d6 584 (define-key map "\C-o" 'occur-mode-display-occurrence)
f601efb0
SM
585 (define-key map "\M-n" 'occur-next)
586 (define-key map "\M-p" 'occur-prev)
d99118b0
SS
587 (define-key map "r" 'occur-rename-buffer)
588 (define-key map "c" 'clone-buffer)
f601efb0 589 (define-key map "g" 'revert-buffer)
d99118b0
SS
590 (define-key map "q" 'quit-window)
591 (define-key map "z" 'kill-this-buffer)
f601efb0
SM
592 map)
593 "Keymap for `occur-mode'.")
698e1804 594
46b3d18e
RS
595(defvar occur-revert-arguments nil
596 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
597See `occur-revert-function'.")
698e1804 598
c9ae8cbb
JB
599(defcustom occur-mode-hook '(turn-on-font-lock)
600 "Hook run when entering Occur mode."
601 :type 'hook
602 :group 'matching)
603
604(defcustom occur-hook nil
605 "Hook run when `occur' is called."
daae70bf
CW
606 :type 'hook
607 :group 'matching)
608
de3c9b09 609(put 'occur-mode 'mode-class 'special)
505847d4 610(defun occur-mode ()
698e1804 611 "Major mode for output from \\[occur].
0081c8a1
RS
612\\<occur-mode-map>Move point to one of the items in this buffer, then use
613\\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
614Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
615
698e1804 616\\{occur-mode-map}"
ce8b7b9f 617 (interactive)
505847d4
RS
618 (kill-all-local-variables)
619 (use-local-map occur-mode-map)
620 (setq major-mode 'occur-mode)
621 (setq mode-name "Occur")
f601efb0 622 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
c9ae8cbb 623 (make-local-variable 'occur-revert-arguments)
fbefbe33 624 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
423e4de7 625 (setq next-error-function 'occur-next-error)
c9ae8cbb 626 (run-hooks 'occur-mode-hook))
698e1804 627
a41284da 628(defun occur-revert-function (ignore1 ignore2)
46b3d18e 629 "Handle `revert-buffer' for Occur mode buffers."
e1690783 630 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
a41284da 631
78bead73
RS
632(defun occur-mode-mouse-goto (event)
633 "In Occur mode, go to the occurrence whose line you click on."
634 (interactive "e")
46b3d18e 635 (let (pos)
78bead73
RS
636 (save-excursion
637 (set-buffer (window-buffer (posn-window (event-end event))))
638 (save-excursion
639 (goto-char (posn-point (event-end event)))
46b3d18e
RS
640 (setq pos (occur-mode-find-occurrence))))
641 (pop-to-buffer (marker-buffer pos))
642 (goto-char pos)))
78bead73
RS
643
644(defun occur-mode-find-occurrence ()
46b3d18e
RS
645 (let ((pos (get-text-property (point) 'occur-target)))
646 (unless pos
68608d9c 647 (error "No occurrence on this line"))
46b3d18e
RS
648 (unless (buffer-live-p (marker-buffer pos))
649 (error "Buffer for this occurrence was killed"))
650 pos))
78bead73
RS
651
652(defun occur-mode-goto-occurrence ()
653 "Go to the occurrence the current line describes."
654 (interactive)
46b3d18e
RS
655 (let ((pos (occur-mode-find-occurrence)))
656 (pop-to-buffer (marker-buffer pos))
657 (goto-char pos)))
8d15583f 658
029024e2
RS
659(defun occur-mode-goto-occurrence-other-window ()
660 "Go to the occurrence the current line describes, in another window."
661 (interactive)
46b3d18e
RS
662 (let ((pos (occur-mode-find-occurrence)))
663 (switch-to-buffer-other-window (marker-buffer pos))
664 (goto-char pos)))
029024e2 665
365486d6
RS
666(defun occur-mode-display-occurrence ()
667 "Display in another window the occurrence the current line describes."
668 (interactive)
46b3d18e
RS
669 (let ((pos (occur-mode-find-occurrence))
670 window
671 ;; Bind these to ensure `display-buffer' puts it in another window.
365486d6 672 same-window-buffer-names
46b3d18e
RS
673 same-window-regexps)
674 (setq window (display-buffer (marker-buffer pos)))
365486d6
RS
675 ;; This is the way to set point in the proper window.
676 (save-selected-window
677 (select-window window)
46b3d18e 678 (goto-char pos))))
365486d6 679
123d5548 680(defun occur-find-match (n search message)
8d15583f
RS
681 (if (not n) (setq n 1))
682 (let ((r))
683 (while (> n 0)
123d5548
JB
684 (setq r (funcall search (point) 'occur-match))
685 (and r
686 (get-text-property r 'occur-match)
687 (setq r (funcall search r 'occur-match)))
8d15583f 688 (if r
123d5548
JB
689 (goto-char r)
690 (error message))
8d15583f
RS
691 (setq n (1- n)))))
692
123d5548
JB
693(defun occur-next (&optional n)
694 "Move to the Nth (default 1) next match in an Occur mode buffer."
695 (interactive "p")
696 (occur-find-match n #'next-single-property-change "No more matches"))
697
8d15583f 698(defun occur-prev (&optional n)
46b3d18e 699 "Move to the Nth (default 1) previous match in an Occur mode buffer."
8d15583f 700 (interactive "p")
123d5548 701 (occur-find-match n #'previous-single-property-change "No earlier matches"))
423e4de7
KS
702
703(defun occur-next-error (&optional argp reset)
704 "Move to the Nth (default 1) next match in an Occur mode buffer.
705Compatibility function for \\[next-error] invocations."
706 (interactive "p")
707 (when reset
708 (occur-find-match 0 #'next-single-property-change "No first match"))
709 (occur-find-match
710 (prefix-numeric-value argp)
711 (if (> 0 (prefix-numeric-value argp))
712 #'previous-single-property-change
713 #'next-single-property-change)
714 "No more matches")
715 (occur-mode-goto-occurrence))
716
4c53bd2b 717\f
9d325ebf 718(defcustom list-matching-lines-default-context-lines 0
e730be7f
DL
719 "*Default number of context lines included around `list-matching-lines' matches.
720A negative number means to include that many lines before the match.
9d325ebf
RS
721A positive number means to include that many lines both before and after."
722 :type 'integer
723 :group 'matching)
698e1804 724
31e1d920 725(defalias 'list-matching-lines 'occur)
698e1804 726
68608d9c 727(defcustom list-matching-lines-face 'bold
e730be7f 728 "*Face used by \\[list-matching-lines] to show the text that matches.
68608d9c
CW
729If the value is nil, don't highlight the matching portions specially."
730 :type 'face
731 :group 'matching)
732
733(defcustom list-matching-lines-buffer-name-face 'underline
734 "*Face used by \\[list-matching-lines] to show the names of buffers.
735If the value is nil, don't highlight the buffer names specially."
736 :type 'face
737 :group 'matching)
738
9e2b2e30 739(defun occur-accumulate-lines (count &optional no-props)
68608d9c
CW
740 (save-excursion
741 (let ((forwardp (> count 0))
742 (result nil))
743 (while (not (or (zerop count)
744 (if forwardp
745 (eobp)
746 (bobp))))
b0523087 747 (setq count (+ count (if forwardp -1 1)))
68608d9c 748 (push
9e2b2e30
CW
749 (funcall (if no-props
750 #'buffer-substring-no-properties
751 #'buffer-substring)
68608d9c
CW
752 (line-beginning-position)
753 (line-end-position))
754 result)
755 (forward-line (if forwardp 1 -1)))
756 (nreverse result))))
757
758(defun occur-read-primary-args ()
759 (list (let* ((default (car regexp-history))
760 (input
761 (read-from-minibuffer
762 (if default
763 (format "List lines matching regexp (default `%s'): "
764 default)
765 "List lines matching regexp: ")
766 nil
767 nil
768 nil
769 'regexp-history)))
770 (if (equal input "")
771 default
772 input))
bda1925e
CW
773 (when current-prefix-arg
774 (prefix-numeric-value current-prefix-arg))))
c9daced0 775
d99118b0
SS
776(defun occur-rename-buffer (&optional unique-p)
777 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
778Here `original-buffer-name' is the buffer name were occur was originally run.
779When given the prefix argument, the renaming will not clobber the existing
780buffer(s) of that name, but use `generate-new-buffer-name' instead.
2fb79329 781You can add this to `occur-hook' if you always want a separate *Occur*
d99118b0
SS
782buffer for each buffer where you invoke `occur'."
783 (interactive "P")
784 (with-current-buffer
785 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
786 (rename-buffer (concat "*Occur: "
787 (mapconcat #'buffer-name
788 (car (cddr occur-revert-arguments)) "/")
789 "*")
790 unique-p)))
791
698e1804 792(defun occur (regexp &optional nlines)
99976f85 793 "Show all lines in the current buffer containing a match for REGEXP.
da44e784
RM
794
795If a match spreads across multiple lines, all those lines are shown.
698e1804 796
da44e784
RM
797Each line is displayed with NLINES lines before and after, or -NLINES
798before if NLINES is negative.
799NLINES defaults to `list-matching-lines-default-context-lines'.
698e1804
RS
800Interactively it is the prefix arg.
801
4c53bd2b 802The lines are shown in a buffer named `*Occur*'.
698e1804 803It serves as a menu to find any of the occurrences in this buffer.
de3c9b09 804\\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
9483d601 805
de3c9b09
RS
806If REGEXP contains upper case characters (excluding those preceded by `\\'),
807the matching is case-sensitive."
68608d9c
CW
808 (interactive (occur-read-primary-args))
809 (occur-1 regexp nlines (list (current-buffer))))
810
811(defun multi-occur (bufs regexp &optional nlines)
812 "Show all lines in buffers BUFS containing a match for REGEXP.
813This function acts on multiple buffers; otherwise, it is exactly like
814`occur'."
a5dfed3e 815 (interactive
68608d9c 816 (cons
52698d45
KS
817 (let* ((bufs (list (read-buffer "First buffer to search: "
818 (current-buffer) t)))
819 (buf nil)
820 (ido-ignore-item-temp-list bufs))
68608d9c 821 (while (not (string-equal
f1180544 822 (setq buf (read-buffer
52698d45
KS
823 (if (eq read-buffer-function 'ido-read-buffer)
824 "Next buffer to search (C-j to end): "
825 "Next buffer to search (RET to end): ")
826 nil t))
68608d9c 827 ""))
52698d45
KS
828 (add-to-list 'bufs buf)
829 (setq ido-ignore-item-temp-list bufs))
68608d9c
CW
830 (nreverse (mapcar #'get-buffer bufs)))
831 (occur-read-primary-args)))
832 (occur-1 regexp nlines bufs))
833
834(defun multi-occur-by-filename-regexp (bufregexp regexp &optional nlines)
04fe158a 835 "Show all lines matching REGEXP in buffers named by BUFREGEXP.
68608d9c
CW
836See also `multi-occur'."
837 (interactive
838 (cons
839 (let* ((default (car regexp-history))
840 (input
841 (read-from-minibuffer
842 "List lines in buffers whose filename matches regexp: "
843 nil
844 nil
845 nil
846 'regexp-history)))
847 (if (equal input "")
848 default
849 input))
850 (occur-read-primary-args)))
851 (when bufregexp
852 (occur-1 regexp nlines
853 (delq nil
854 (mapcar (lambda (buf)
855 (when (and (buffer-file-name buf)
856 (string-match bufregexp
857 (buffer-file-name buf)))
858 buf))
859 (buffer-list))))))
860
e1690783
CW
861(defun occur-1 (regexp nlines bufs &optional buf-name)
862 (unless buf-name
863 (setq buf-name "*Occur*"))
864 (let ((occur-buf (get-buffer-create buf-name))
70ed2a76
CW
865 (made-temp-buf nil)
866 (active-bufs (delq nil (mapcar #'(lambda (buf)
867 (when (buffer-live-p buf) buf))
868 bufs))))
869 ;; Handle the case where one of the buffers we're searching is the
870 ;; *Occur* buffer itself.
871 (when (memq occur-buf bufs)
872 (setq occur-buf (with-current-buffer occur-buf
873 (clone-buffer "*Occur-temp*"))
874 made-temp-buf t))
68608d9c
CW
875 (with-current-buffer occur-buf
876 (setq buffer-read-only nil)
877 (occur-mode)
878 (erase-buffer)
879 (let ((count (occur-engine
70ed2a76 880 regexp active-bufs occur-buf
68608d9c
CW
881 (or nlines list-matching-lines-default-context-lines)
882 (and case-fold-search
883 (isearch-no-upper-case-p regexp t))
506a6d7e
CW
884 list-matching-lines-buffer-name-face
885 nil list-matching-lines-face nil)))
b2043e7b
AS
886 (let* ((bufcount (length active-bufs))
887 (diff (- (length bufs) bufcount)))
888 (message "Searched %d buffer%s%s; %s match%s for `%s'"
889 bufcount (if (= bufcount 1) "" "s")
890 (if (zerop diff) "" (format " (%d killed)" diff))
891 (if (zerop count) "no" (format "%d" count))
892 (if (= count 1) "" "es")
893 regexp))
70ed2a76
CW
894 ;; If we had to make a temporary buffer, make it the *Occur*
895 ;; buffer now.
896 (when made-temp-buf
e1690783
CW
897 (with-current-buffer (get-buffer buf-name)
898 (kill-buffer (current-buffer)))
899 (rename-buffer buf-name))
70ed2a76
CW
900 (setq occur-revert-arguments (list regexp nlines bufs)
901 buffer-read-only t)
68608d9c 902 (if (> count 0)
423e4de7
KS
903 (progn
904 (display-buffer occur-buf)
905 (setq next-error-last-buffer occur-buf))
2fb79329
JB
906 (kill-buffer occur-buf)))
907 (run-hooks 'occur-hook))))
68608d9c 908
46b3d18e
RS
909(defun occur-engine-add-prefix (lines)
910 (mapcar
911 #'(lambda (line)
261cca88 912 (concat " :" line "\n"))
46b3d18e
RS
913 lines))
914
915(defun occur-engine (regexp buffers out-buf nlines case-fold-search
916 title-face prefix-face match-face keep-props)
917 (with-current-buffer out-buf
918 (setq buffer-read-only nil)
5cb4031d
KH
919 (let ((globalcount 0)
920 (coding nil))
46b3d18e
RS
921 ;; Map over all the buffers
922 (dolist (buf buffers)
923 (when (buffer-live-p buf)
924 (let ((matches 0) ;; count of matched lines
925 (lines 1) ;; line count
926 (matchbeg 0)
927 (matchend 0)
928 (origpt nil)
929 (begpt nil)
930 (endpt nil)
931 (marker nil)
932 (curstring "")
933 (headerpt (with-current-buffer out-buf (point))))
934 (save-excursion
935 (set-buffer buf)
5cb4031d
KH
936 (or coding
937 ;; Set CODING only if the current buffer locally
938 ;; binds buffer-file-coding-system.
939 (not (local-variable-p 'buffer-file-coding-system))
940 (setq coding buffer-file-coding-system))
68608d9c 941 (save-excursion
46b3d18e
RS
942 (goto-char (point-min)) ;; begin searching in the buffer
943 (while (not (eobp))
944 (setq origpt (point))
945 (when (setq endpt (re-search-forward regexp nil t))
946 (setq matches (1+ matches)) ;; increment match count
46b3d18e
RS
947 (setq matchbeg (match-beginning 0)
948 matchend (match-end 0))
949 (setq begpt (save-excursion
950 (goto-char matchbeg)
951 (line-beginning-position)))
952 (setq lines (+ lines (1- (count-lines origpt endpt))))
953 (setq marker (make-marker))
954 (set-marker marker matchbeg)
955 (setq curstring (buffer-substring begpt
956 (line-end-position)))
957 ;; Depropertize the string, and maybe
958 ;; highlight the matches
959 (let ((len (length curstring))
960 (start 0))
961 (unless keep-props
962 (set-text-properties 0 len nil curstring))
963 (while (and (< start len)
964 (string-match regexp curstring start))
965 (add-text-properties (match-beginning 0)
966 (match-end 0)
967 (append
506a6d7e 968 `(occur-match t)
46b3d18e 969 (when match-face
506a6d7e 970 `(font-lock-face ,match-face)))
46b3d18e
RS
971 curstring)
972 (setq start (match-end 0))))
973 ;; Generate the string to insert for this match
974 (let* ((out-line
975 (concat
261cca88
RS
976 ;; Using 7 digits aligns tabs properly.
977 (apply #'propertize (format "%7d:" lines)
46b3d18e
RS
978 (append
979 (when prefix-face
506a6d7e 980 `(font-lock-face prefix-face))
46b3d18e
RS
981 '(occur-prefix t)))
982 curstring
983 "\n"))
984 (data
985 (if (= nlines 0)
986 ;; The simple display style
987 out-line
988 ;; The complex multi-line display
989 ;; style. Generate a list of lines,
990 ;; concatenate them all together.
991 (apply #'concat
992 (nconc
b0523087 993 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ nlines)) keep-props))))
46b3d18e 994 (list out-line)
b0523087 995 (occur-engine-add-prefix (cdr (occur-accumulate-lines (1+ nlines) keep-props))))))))
46b3d18e
RS
996 ;; Actually insert the match display data
997 (with-current-buffer out-buf
998 (let ((beg (point))
999 (end (progn (insert data) (point))))
1000 (unless (= nlines 0)
1001 (insert "-------\n"))
1002 (add-text-properties
e8e2a88c
CW
1003 beg end
1004 `(occur-target ,marker help-echo "mouse-2: go to this occurrence"))
1005 ;; We don't put `mouse-face' on the newline,
1006 ;; because that loses.
1007 (add-text-properties beg (1- end) '(mouse-face highlight)))))
46b3d18e 1008 (goto-char endpt))
e1690783
CW
1009 (if endpt
1010 (progn
1011 (setq lines (1+ lines))
1012 ;; On to the next match...
1013 (forward-line 1))
1014 (goto-char (point-max))))))
46b3d18e 1015 (when (not (zerop matches)) ;; is the count zero?
daae70bf 1016 (setq globalcount (+ globalcount matches))
46b3d18e
RS
1017 (with-current-buffer out-buf
1018 (goto-char headerpt)
1019 (let ((beg (point))
1020 end)
dbed3cd3
JPW
1021 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1022 matches (if (= matches 1) "" "es")
1023 regexp (buffer-name buf)))
46b3d18e
RS
1024 (setq end (point))
1025 (add-text-properties beg end
1026 (append
1027 (when title-face
506a6d7e
CW
1028 `(font-lock-face ,title-face))
1029 `(occur-title ,buf))))
46b3d18e 1030 (goto-char (point-min)))))))
5cb4031d
KH
1031 (if coding
1032 ;; CODING is buffer-file-coding-system of the first buffer
1033 ;; that locally binds it. Let's use it also for the output
1034 ;; buffer.
1035 (set-buffer-file-coding-system coding))
46b3d18e
RS
1036 ;; Return the number of matches
1037 globalcount)))
68608d9c 1038
698e1804 1039\f
81bdc14d
RS
1040;; It would be nice to use \\[...], but there is no reasonable way
1041;; to make that display both SPC and Y.
698e1804
RS
1042(defconst query-replace-help
1043 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
be44f62c 1044RET or `q' to exit, Period to replace one match and exit,
698e1804
RS
1045Comma to replace but not move point immediately,
1046C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1047C-w to delete match and recursive edit,
1048C-l to clear the screen, redisplay, and offer same replacement again,
1049! to replace all remaining matches with no more questions,
7ce278f3
GM
1050^ to move point back to previous match,
1051E to edit the replacement string"
f54701d1 1052 "Help message while in `query-replace'.")
698e1804 1053
81bdc14d
RS
1054(defvar query-replace-map (make-sparse-keymap)
1055 "Keymap that defines the responses to questions in `query-replace'.
1056The \"bindings\" in this map are not commands; they are answers.
1057The valid answers include `act', `skip', `act-and-show',
1058`exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
d9121bc0 1059`automatic', `backup', `exit-prefix', and `help'.")
81bdc14d
RS
1060
1061(define-key query-replace-map " " 'act)
1062(define-key query-replace-map "\d" 'skip)
1063(define-key query-replace-map [delete] 'skip)
9275e5e3 1064(define-key query-replace-map [backspace] 'skip)
81bdc14d
RS
1065(define-key query-replace-map "y" 'act)
1066(define-key query-replace-map "n" 'skip)
633a305a
RS
1067(define-key query-replace-map "Y" 'act)
1068(define-key query-replace-map "N" 'skip)
34724fcb 1069(define-key query-replace-map "e" 'edit-replacement)
7ce278f3 1070(define-key query-replace-map "E" 'edit-replacement)
81bdc14d 1071(define-key query-replace-map "," 'act-and-show)
81bdc14d 1072(define-key query-replace-map "q" 'exit)
919592c0 1073(define-key query-replace-map "\r" 'exit)
384c7da4 1074(define-key query-replace-map [return] 'exit)
81bdc14d
RS
1075(define-key query-replace-map "." 'act-and-exit)
1076(define-key query-replace-map "\C-r" 'edit)
1077(define-key query-replace-map "\C-w" 'delete-and-edit)
1078(define-key query-replace-map "\C-l" 'recenter)
1079(define-key query-replace-map "!" 'automatic)
1080(define-key query-replace-map "^" 'backup)
1081(define-key query-replace-map "\C-h" 'help)
e731045a
KH
1082(define-key query-replace-map [f1] 'help)
1083(define-key query-replace-map [help] 'help)
81bdc14d 1084(define-key query-replace-map "?" 'help)
bc6312e1
RS
1085(define-key query-replace-map "\C-g" 'quit)
1086(define-key query-replace-map "\C-]" 'quit)
d9121bc0
RS
1087(define-key query-replace-map "\e" 'exit-prefix)
1088(define-key query-replace-map [escape] 'exit-prefix)
81bdc14d 1089
84482eb3 1090(defun replace-match-string-symbols (n)
e730be7f
DL
1091 "Process a list (and any sub-lists), expanding certain symbols.
1092Symbol Expands To
1093N (match-string N) (where N is a string of digits)
1094#N (string-to-number (match-string N))
1095& (match-string 0)
1096#& (string-to-number (match-string 0))
2f57bf85 1097# replace-count
e730be7f
DL
1098
1099Note that these symbols must be preceeded by a backslash in order to
1100type them."
84482eb3
RS
1101 (while n
1102 (cond
1103 ((consp (car n))
1104 (replace-match-string-symbols (car n))) ;Process sub-list
1105 ((symbolp (car n))
1106 (let ((name (symbol-name (car n))))
1107 (cond
1108 ((string-match "^[0-9]+$" name)
1109 (setcar n (list 'match-string (string-to-number name))))
1110 ((string-match "^#[0-9]+$" name)
1111 (setcar n (list 'string-to-number
1112 (list 'match-string
1113 (string-to-number (substring name 1))))))
1114 ((string= "&" name)
1115 (setcar n '(match-string 0)))
1116 ((string= "#&" name)
2f57bf85
DK
1117 (setcar n '(string-to-number (match-string 0))))
1118 ((string= "#" name)
1119 (setcar n 'replace-count))))))
84482eb3
RS
1120 (setq n (cdr n))))
1121
1122(defun replace-eval-replacement (expression replace-count)
1123 (let ((replacement (eval expression)))
1124 (if (stringp replacement)
1125 replacement
1126 (prin1-to-string replacement t))))
1127
2f57bf85
DK
1128(defun replace-quote (replacement)
1129 "Quote a replacement string.
1130This just doubles all backslashes in REPLACEMENT and
1131returns the resulting string. If REPLACEMENT is not
1132a string, it is first passed through `prin1-to-string'
1133with the `noescape' argument set.
1134
1135`match-data' is preserved across the call."
1136 (save-match-data
1137 (replace-regexp-in-string "\\\\" "\\\\"
1138 (if (stringp replacement)
1139 replacement
1140 (prin1-to-string replacement t))
1141 t t)))
1142
84482eb3
RS
1143(defun replace-loop-through-replacements (data replace-count)
1144 ;; DATA is a vector contaning the following values:
1145 ;; 0 next-rotate-count
1146 ;; 1 repeat-count
1147 ;; 2 next-replacement
1148 ;; 3 replacements
1149 (if (= (aref data 0) replace-count)
1150 (progn
1151 (aset data 0 (+ replace-count (aref data 1)))
1152 (let ((next (cdr (aref data 2))))
1153 (aset data 2 (if (consp next) next (aref data 3))))))
1154 (car (aref data 2)))
1155
7c1c02ac
DK
1156(defun replace-match-data (integers reuse &optional new)
1157 "Like `match-data', but markers in REUSE get invalidated.
1158If NEW is non-NIL, it is set and returned instead of fresh data,
1159but coerced to the correct value of INTEGERS."
1160 (or (and new
1161 (progn
1162 (set-match-data new)
1163 (and (eq new reuse)
1164 (eq (null integers) (markerp (car reuse)))
1165 new)))
1166 (match-data integers
1167 (prog1 reuse
1168 (while reuse
1169 (if (markerp (car reuse))
1170 (set-marker (car reuse) nil))
1171 (setq reuse (cdr reuse)))))))
1172
1173(defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1174 "Make a replacement with `replace-match', editing `\\?'.
1175NEXTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1176check for `\\?' is made to save time. MATCH-DATA is used for the
1177replacement. In case editing is done, it is changed to use markers.
1178
1179The return value is non-NIL if there has been no `\\?' or NOEDIT was
1180passed in. If LITERAL is set, no checking is done, anyway."
1181 (unless (or literal noedit)
1182 (setq noedit t)
1183 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1184 newtext)
1185 (setq newtext
1186 (read-input "Edit replacement string: "
1187 (prog1
1188 (cons
1189 (replace-match "" t t newtext 3)
1190 (1+ (match-beginning 3)))
1191 (setq match-data
1192 (replace-match-data
1193 nil match-data match-data))))
1194 noedit nil)))
1195 (set-match-data match-data)
1196 (replace-match newtext fixedcase literal)
1197 noedit)
1198
d99118b0 1199(defun perform-replace (from-string replacements
698e1804 1200 query-flag regexp-flag delimited-flag
99a7559f 1201 &optional repeat-count map start end)
698e1804
RS
1202 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1203Don't use this in your own program unless you want to query and set the mark
1204just as `query-replace' does. Instead, write a simple loop like this:
698665d1
GM
1205
1206 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
698e1804 1207 (replace-match \"foobar\" nil nil))
698665d1
GM
1208
1209which will run faster and probably do exactly what you want. Please
1210see the documentation of `replace-match' to find out how to simulate
588c915a
CW
1211`case-replace'.
1212
1213This function returns nil if and only if there were no matches to
1214make, or the user didn't cancel the call."
81bdc14d 1215 (or map (setq map query-replace-map))
1c1dadab
RS
1216 (and query-flag minibuffer-auto-raise
1217 (raise-frame (window-frame (minibuffer-window))))
698e1804
RS
1218 (let ((nocasify (not (and case-fold-search case-replace
1219 (string-equal from-string
1220 (downcase from-string)))))
5a78b471
KH
1221 (case-fold-search (and case-fold-search
1222 (string-equal from-string
1223 (downcase from-string))))
d83a97ab 1224 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
698e1804
RS
1225 (search-function (if regexp-flag 're-search-forward 'search-forward))
1226 (search-string from-string)
e5d77022 1227 (real-match-data nil) ; the match data for the current match
698e1804 1228 (next-replacement nil)
7c1c02ac 1229 (noedit nil)
698e1804
RS
1230 (keep-going t)
1231 (stack nil)
698e1804 1232 (replace-count 0)
5632eb27
PE
1233 (nonempty-match nil)
1234
7ef5c431
KH
1235 ;; If non-nil, it is marker saying where in the buffer to stop.
1236 (limit nil)
1237
5632eb27
PE
1238 ;; Data for the next match. If a cons, it has the same format as
1239 ;; (match-data); otherwise it is t if a match is possible at point.
ae4eb03c 1240 (match-again t)
5632eb27 1241
02d95a27
RS
1242 (message
1243 (if query-flag
1244 (substitute-command-keys
1245 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
7ef5c431
KH
1246
1247 ;; If region is active, in Transient Mark mode, operate on region.
47d72254
GM
1248 (when start
1249 (setq limit (copy-marker (max start end)))
1250 (goto-char (min start end))
1251 (deactivate-mark))
84482eb3
RS
1252
1253 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1254 ;; containing a function and its first argument. The function is
1255 ;; called to generate each replacement like this:
1256 ;; (funcall (car replacements) (cdr replacements) replace-count)
1257 ;; It must return a string.
1258 (cond
1259 ((stringp replacements)
1260 (setq next-replacement replacements
1261 replacements nil))
1262 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1263 (or repeat-count (setq repeat-count 1))
1264 (setq replacements (cons 'replace-loop-through-replacements
1265 (vector repeat-count repeat-count
1266 replacements replacements)))))
1267
698e1804
RS
1268 (if delimited-flag
1269 (setq search-function 're-search-forward
1270 search-string (concat "\\b"
1271 (if regexp-flag from-string
1272 (regexp-quote from-string))
1273 "\\b")))
1274 (push-mark)
1275 (undo-boundary)
e782e9f2
RS
1276 (unwind-protect
1277 ;; Loop finding occurrences that perhaps should be replaced.
1278 (while (and keep-going
22a76778 1279 (not (or (eobp) (and limit (>= (point) limit))))
5632eb27
PE
1280 ;; Use the next match if it is already known;
1281 ;; otherwise, search for a match after moving forward
1282 ;; one char if progress is required.
1283 (setq real-match-data
1284 (if (consp match-again)
1285 (progn (goto-char (nth 1 match-again))
7c1c02ac
DK
1286 (replace-match-data t
1287 real-match-data
1288 match-again))
5632eb27 1289 (and (or match-again
889617de
GM
1290 ;; MATCH-AGAIN non-nil means we
1291 ;; accept an adjacent match. If
1292 ;; we don't, move one char to the
1293 ;; right. This takes us a
1294 ;; character too far at the end,
1295 ;; but this is undone after the
1296 ;; while-loop.
22a76778
JL
1297 (progn
1298 (forward-char 1)
1299 (not (or (eobp)
1300 (and limit (>= (point) limit))))))
7ef5c431 1301 (funcall search-function search-string limit t)
5632eb27
PE
1302 ;; For speed, use only integers and
1303 ;; reuse the list used last time.
7c1c02ac 1304 (replace-match-data t real-match-data)))))
1c4fe319
RS
1305 ;; Optionally ignore matches that have a read-only property.
1306 (unless (and query-replace-skip-read-only
1307 (text-property-not-all
1308 (match-beginning 0) (match-end 0)
1309 'read-only nil))
1310
1311 ;; Record whether the match is nonempty, to avoid an infinite loop
1312 ;; repeatedly matching the same empty string.
1313 (setq nonempty-match
1314 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1315
1316 ;; If the match is empty, record that the next one can't be
1317 ;; adjacent.
1318
1319 ;; Otherwise, if matching a regular expression, do the next
1320 ;; match now, since the replacement for this match may
1321 ;; affect whether the next match is adjacent to this one.
1322 ;; If that match is empty, don't use it.
1323 (setq match-again
1324 (and nonempty-match
1325 (or (not regexp-flag)
1326 (and (looking-at search-string)
1327 (let ((match (match-data)))
1328 (and (/= (nth 0 match) (nth 1 match))
1329 match))))))
1330
1331 ;; Calculate the replacement string, if necessary.
1332 (when replacements
1333 (set-match-data real-match-data)
1334 (setq next-replacement
1335 (funcall (car replacements) (cdr replacements)
7c1c02ac
DK
1336 replace-count)
1337 noedit nil))
1c4fe319 1338 (if (not query-flag)
cb05ca25
DK
1339 (let ((inhibit-read-only
1340 query-replace-skip-read-only))
1341 (unless noedit
1342 (replace-highlight (nth 0 real-match-data)
1343 (nth 1 real-match-data)))
7c1c02ac
DK
1344 (setq noedit
1345 (replace-match-maybe-edit
1346 next-replacement nocasify literal
1347 noedit real-match-data)
1348 replace-count (1+ replace-count)))
1c4fe319
RS
1349 (undo-boundary)
1350 (let (done replaced key def)
1351 ;; Loop reading commands until one of them sets done,
7c1c02ac
DK
1352 ;; which means it has finished handling this
1353 ;; occurrence. Any command that sets `done' should
1354 ;; leave behind proper match data for the stack.
1355 ;; Commands not setting `done' need to adjust
1356 ;; `real-match-data'.
1c4fe319
RS
1357 (while (not done)
1358 (set-match-data real-match-data)
1359 (replace-highlight (match-beginning 0) (match-end 0))
1360 ;; Bind message-log-max so we don't fill up the message log
1361 ;; with a bunch of identical messages.
1362 (let ((message-log-max nil))
1363 (message message from-string next-replacement))
1364 (setq key (read-event))
1365 ;; Necessary in case something happens during read-event
1366 ;; that clobbers the match data.
1367 (set-match-data real-match-data)
1368 (setq key (vector key))
1369 (setq def (lookup-key map key))
1370 ;; Restore the match data while we process the command.
1371 (cond ((eq def 'help)
1372 (with-output-to-temp-buffer "*Help*"
1373 (princ
1374 (concat "Query replacing "
1375 (if regexp-flag "regexp " "")
1376 from-string " with "
1377 next-replacement ".\n\n"
1378 (substitute-command-keys
1379 query-replace-help)))
1380 (with-current-buffer standard-output
1381 (help-mode))))
1382 ((eq def 'exit)
1383 (setq keep-going nil)
1384 (setq done t))
1385 ((eq def 'backup)
1386 (if stack
588c915a 1387 (let ((elt (pop stack)))
7c1c02ac
DK
1388 (goto-char (nth 0 elt))
1389 (setq replaced (nth 1 elt)
1390 real-match-data
1391 (replace-match-data
1392 t real-match-data
1393 (nth 2 elt))))
1c4fe319
RS
1394 (message "No previous match")
1395 (ding 'no-terminate)
1396 (sit-for 1)))
1397 ((eq def 'act)
1398 (or replaced
7c1c02ac
DK
1399 (setq noedit
1400 (replace-match-maybe-edit
1401 next-replacement nocasify literal
1402 noedit real-match-data)
1403 replace-count (1+ replace-count)))
1c4fe319
RS
1404 (setq done t replaced t))
1405 ((eq def 'act-and-exit)
1406 (or replaced
7c1c02ac 1407 (setq noedit
da6eb51c 1408 (replace-match-maybe-edit
7c1c02ac
DK
1409 next-replacement nocasify literal
1410 noedit real-match-data)
1411 replace-count (1+ replace-count)))
1c4fe319
RS
1412 (setq keep-going nil)
1413 (setq done t replaced t))
1414 ((eq def 'act-and-show)
1415 (if (not replaced)
7c1c02ac
DK
1416 (setq noedit
1417 (replace-match-maybe-edit
1418 next-replacement nocasify literal
1419 noedit real-match-data)
1420 replace-count (1+ replace-count)
1421 real-match-data (replace-match-data
1422 t real-match-data)
1423 replaced t)))
1c4fe319
RS
1424 ((eq def 'automatic)
1425 (or replaced
7c1c02ac
DK
1426 (setq noedit
1427 (replace-match-maybe-edit
1428 next-replacement nocasify literal
1429 noedit real-match-data)
1430 replace-count (1+ replace-count)))
1c4fe319
RS
1431 (setq done t query-flag nil replaced t))
1432 ((eq def 'skip)
1433 (setq done t))
1434 ((eq def 'recenter)
1435 (recenter nil))
1436 ((eq def 'edit)
1437 (let ((opos (point-marker)))
7c1c02ac
DK
1438 (setq real-match-data (replace-match-data
1439 nil real-match-data
1440 real-match-data))
1c4fe319 1441 (goto-char (match-beginning 0))
86914dcc
RS
1442 (save-excursion
1443 (save-window-excursion
1444 (recursive-edit)))
7c1c02ac
DK
1445 (goto-char opos)
1446 (set-marker opos nil))
1c4fe319
RS
1447 ;; Before we make the replacement,
1448 ;; decide whether the search string
1449 ;; can match again just after this match.
1450 (if (and regexp-flag nonempty-match)
1451 (setq match-again (and (looking-at search-string)
1452 (match-data)))))
1c4fe319
RS
1453 ;; Edit replacement.
1454 ((eq def 'edit-replacement)
7c1c02ac
DK
1455 (setq real-match-data (replace-match-data
1456 nil real-match-data
1457 real-match-data)
1458 next-replacement
1c4fe319 1459 (read-input "Edit replacement string: "
7c1c02ac
DK
1460 next-replacement)
1461 noedit nil)
1462 (if replaced
1463 (set-match-data real-match-data)
1464 (setq noedit
1465 (replace-match-maybe-edit
1466 next-replacement nocasify literal noedit
1467 real-match-data)
1468 replaced t))
1c4fe319 1469 (setq done t))
d99118b0 1470
1c4fe319 1471 ((eq def 'delete-and-edit)
7c1c02ac
DK
1472 (replace-match "" t t)
1473 (setq real-match-data (replace-match-data
1474 nil real-match-data))
1475 (replace-dehighlight)
1476 (save-excursion (recursive-edit))
1c4fe319
RS
1477 (setq replaced t))
1478 ;; Note: we do not need to treat `exit-prefix'
1479 ;; specially here, since we reread
1480 ;; any unrecognized character.
1481 (t
1482 (setq this-command 'mode-exited)
1483 (setq keep-going nil)
1484 (setq unread-command-events
1485 (append (listify-key-sequence key)
1486 unread-command-events))
1487 (setq done t))))
1488 ;; Record previous position for ^ when we move on.
1489 ;; Change markers to numbers in the match data
1490 ;; since lots of markers slow down editing.
7c1c02ac
DK
1491 (push (list (point) replaced
1492;;; If the replacement has already happened, all we need is the
1493;;; current match start and end. We could get this with a trivial
1494;;; match like
1495;;; (save-excursion (goto-char (match-beginning 0))
1496;;; (search-forward (match-string 0))
1497;;; (match-data t))
1498;;; if we really wanted to avoid manually constructing match data.
1499;;; Adding current-buffer is necessary so that match-data calls can
1500;;; return markers which are appropriate for editing.
1501 (if replaced
1502 (list
1503 (match-beginning 0)
1504 (match-end 0)
1505 (current-buffer))
1506 (match-data t)))
1507 stack)))))
889617de
GM
1508
1509 ;; The code preventing adjacent regexp matches in the condition
1510 ;; of the while-loop above will haven taken us one character
1511 ;; beyond the last replacement. Undo that.
1512 (when (and regexp-flag (not match-again) (> replace-count 0))
1513 (backward-char 1))
d99118b0 1514
e782e9f2 1515 (replace-dehighlight))
4d33492a
RS
1516 (or unread-command-events
1517 (message "Replaced %d occurrence%s"
1518 replace-count
1519 (if (= replace-count 1) "" "s")))
1520 (and keep-going stack)))
698e1804 1521
95807e68 1522(defcustom query-replace-highlight t
9d325ebf
RS
1523 "*Non-nil means to highlight words during query replacement."
1524 :type 'boolean
1525 :group 'matching)
e782e9f2
RS
1526
1527(defvar replace-overlay nil)
1528
1529(defun replace-dehighlight ()
1530 (and replace-overlay
1531 (progn
1532 (delete-overlay replace-overlay)
1533 (setq replace-overlay nil))))
1534
1535(defun replace-highlight (start end)
1536 (and query-replace-highlight
7c1c02ac
DK
1537 (if replace-overlay
1538 (move-overlay replace-overlay start end (current-buffer))
1539 (setq replace-overlay (make-overlay start end))
1540 (overlay-put replace-overlay 'face
1541 (if (facep 'query-replace)
1542 'query-replace 'region)))))
e782e9f2 1543
ab5796a9 1544;;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
c88ab9ce 1545;;; replace.el ends here