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