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