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