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