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