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