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