*** empty log message ***
[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
e09d4033
RS
449
450(defvar occur-buffer nil
451 "Name of buffer for last occur.")
452
453
454(defvar occur-nlines nil
455 "Number of lines of context to show around matching line.")
456
a41284da
RS
457(defvar occur-command-arguments nil
458 "Arguments that were given to `occur' when it made this buffer.")
698e1804 459
de3c9b09
RS
460(put 'occur-mode 'mode-class 'special)
461
505847d4 462(defun occur-mode ()
698e1804 463 "Major mode for output from \\[occur].
0081c8a1
RS
464\\<occur-mode-map>Move point to one of the items in this buffer, then use
465\\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
466Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
467
698e1804 468\\{occur-mode-map}"
505847d4
RS
469 (kill-all-local-variables)
470 (use-local-map occur-mode-map)
471 (setq major-mode 'occur-mode)
472 (setq mode-name "Occur")
473 (make-local-variable 'revert-buffer-function)
474 (setq revert-buffer-function 'occur-revert-function)
f601efb0 475 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
698e1804
RS
476 (make-local-variable 'occur-buffer)
477 (make-local-variable 'occur-nlines)
505847d4
RS
478 (make-local-variable 'occur-command-arguments)
479 (run-hooks 'occur-mode-hook))
698e1804 480
a41284da 481(defun occur-revert-function (ignore1 ignore2)
f54701d1 482 "Handle `revert-buffer' for *Occur* buffers."
a41284da
RS
483 (let ((args occur-command-arguments ))
484 (save-excursion
485 (set-buffer occur-buffer)
486 (apply 'occur args))))
487
78bead73
RS
488(defun occur-mode-mouse-goto (event)
489 "In Occur mode, go to the occurrence whose line you click on."
490 (interactive "e")
491 (let (buffer pos)
492 (save-excursion
493 (set-buffer (window-buffer (posn-window (event-end event))))
494 (save-excursion
495 (goto-char (posn-point (event-end event)))
496 (setq pos (occur-mode-find-occurrence))
497 (setq buffer occur-buffer)))
498 (pop-to-buffer buffer)
499 (goto-char (marker-position pos))))
500
501(defun occur-mode-find-occurrence ()
698e1804
RS
502 (if (or (null occur-buffer)
503 (null (buffer-name occur-buffer)))
504 (progn
8d15583f 505 (setq occur-buffer nil)
698e1804 506 (error "Buffer in which occurrences were found is deleted")))
8d15583f
RS
507 (let ((pos (get-text-property (point) 'occur)))
508 (if (null pos)
509 (error "No occurrence on this line")
510 pos)))
78bead73
RS
511
512(defun occur-mode-goto-occurrence ()
513 "Go to the occurrence the current line describes."
514 (interactive)
515 (let ((pos (occur-mode-find-occurrence)))
698e1804 516 (pop-to-buffer occur-buffer)
121e2227 517 (goto-char (marker-position pos))))
8d15583f 518
029024e2
RS
519(defun occur-mode-goto-occurrence-other-window ()
520 "Go to the occurrence the current line describes, in another window."
521 (interactive)
522 (let ((pos (occur-mode-find-occurrence)))
523 (switch-to-buffer-other-window occur-buffer)
524 (goto-char (marker-position pos))))
525
365486d6
RS
526(defun occur-mode-display-occurrence ()
527 "Display in another window the occurrence the current line describes."
528 (interactive)
529 (let ((pos (occur-mode-find-occurrence))
530 same-window-buffer-names
531 same-window-regexps
532 window)
533 (setq window (display-buffer occur-buffer))
534 ;; This is the way to set point in the proper window.
535 (save-selected-window
536 (select-window window)
537 (goto-char (marker-position pos)))))
538
8d15583f
RS
539(defun occur-next (&optional n)
540 "Move to the Nth (default 1) next match in the *Occur* buffer."
541 (interactive "p")
542 (if (not n) (setq n 1))
543 (let ((r))
544 (while (> n 0)
545 (if (get-text-property (point) 'occur-point)
546 (forward-char 1))
547 (setq r (next-single-property-change (point) 'occur-point))
548 (if r
549 (goto-char r)
e730be7f 550 (error "No more matches"))
8d15583f
RS
551 (setq n (1- n)))))
552
553
554
555(defun occur-prev (&optional n)
556 "Move to the Nth (default 1) previous match in the *Occur* buffer."
557 (interactive "p")
558 (if (not n) (setq n 1))
559 (let ((r))
560 (while (> n 0)
561
562 (setq r (get-text-property (point) 'occur-point))
563 (if r (forward-char -1))
564
565 (setq r (previous-single-property-change (point) 'occur-point))
566 (if r
567 (goto-char (- r 1))
e730be7f 568 (error "No earlier matches"))
8d15583f
RS
569
570 (setq n (1- n)))))
4c53bd2b 571\f
9d325ebf 572(defcustom list-matching-lines-default-context-lines 0
e730be7f
DL
573 "*Default number of context lines included around `list-matching-lines' matches.
574A negative number means to include that many lines before the match.
9d325ebf
RS
575A positive number means to include that many lines both before and after."
576 :type 'integer
577 :group 'matching)
698e1804 578
31e1d920 579(defalias 'list-matching-lines 'occur)
698e1804 580
c9daced0 581(defvar list-matching-lines-face 'bold
e730be7f 582 "*Face used by \\[list-matching-lines] to show the text that matches.
c9daced0
RS
583If the value is nil, don't highlight the matching portions specially.")
584
698e1804 585(defun occur (regexp &optional nlines)
99976f85 586 "Show all lines in the current buffer containing a match for REGEXP.
da44e784
RM
587
588If a match spreads across multiple lines, all those lines are shown.
698e1804 589
da44e784
RM
590Each line is displayed with NLINES lines before and after, or -NLINES
591before if NLINES is negative.
592NLINES defaults to `list-matching-lines-default-context-lines'.
698e1804
RS
593Interactively it is the prefix arg.
594
4c53bd2b 595The lines are shown in a buffer named `*Occur*'.
698e1804 596It serves as a menu to find any of the occurrences in this buffer.
de3c9b09 597\\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
9483d601 598
de3c9b09
RS
599If REGEXP contains upper case characters (excluding those preceded by `\\'),
600the matching is case-sensitive."
a5dfed3e
RS
601 (interactive
602 (list (let* ((default (car regexp-history))
603 (input
604 (read-from-minibuffer
605 (if default
606 (format "List lines matching regexp (default `%s'): "
607 default)
608 "List lines matching regexp: ")
aeab5be0 609 nil nil nil 'regexp-history default t)))
4a8f3b3d
RS
610 (and (equal input "") default
611 (setq input default))
aeab5be0 612 input)
a5dfed3e 613 current-prefix-arg))
d79dfd47
GM
614 (let* ((nlines (if nlines
615 (prefix-numeric-value nlines)
616 list-matching-lines-default-context-lines))
617 (current-tab-width tab-width)
ae13fc3c 618 (inhibit-read-only t)
d79dfd47
GM
619 ;; Minimum width of line number plus trailing colon.
620 (min-line-number-width 6)
9043c1c3
GM
621 ;; Width of line number prefix without the colon. Choose a
622 ;; width that's a multiple of `tab-width' in the original
623 ;; buffer so that lines in *Occur* appear right.
624 (line-number-width (1- (* (/ (- (+ min-line-number-width
625 tab-width)
626 1)
627 tab-width)
628 tab-width)))
d79dfd47
GM
629 ;; Format string for line numbers.
630 (line-number-format (format "%%%dd" line-number-width))
631 (empty (make-string line-number-width ?\ ))
632 (first t)
633 ;;flag to prevent printing separator for first match
634 (occur-num-matches 0)
635 (buffer (current-buffer))
636 (dir default-directory)
637 (linenum 1)
638 (prevpos
639 ;;position of most recent match
640 (point-min))
641 (case-fold-search (and case-fold-search
642 (isearch-no-upper-case-p regexp t)))
643 (final-context-start
644 ;; Marker to the start of context immediately following
645 ;; the matched text in *Occur*.
646 (make-marker)))
99976f85
RS
647;;; (save-excursion
648;;; (beginning-of-line)
649;;; (setq linenum (1+ (count-lines (point-min) (point))))
650;;; (setq prevpos (point)))
016c214f
RS
651 (save-excursion
652 (goto-char (point-min))
653 ;; Check first whether there are any matches at all.
654 (if (not (re-search-forward regexp nil t))
655 (message "No matches for `%s'" regexp)
656 ;; Back up, so the search loop below will find the first match.
657 (goto-char (match-beginning 0))
658 (with-output-to-temp-buffer "*Occur*"
659 (save-excursion
660 (set-buffer standard-output)
661 (setq default-directory dir)
662 ;; We will insert the number of lines, and "lines", later.
663 (insert " matching ")
664 (let ((print-escape-newlines t))
665 (prin1 regexp))
666 (insert " in buffer " (buffer-name buffer) ?. ?\n)
667 (occur-mode)
668 (setq occur-buffer buffer)
669 (setq occur-nlines nlines)
a41284da
RS
670 (setq occur-command-arguments
671 (list regexp nlines)))
016c214f 672 (if (eq buffer standard-output)
91c6bdc0 673 (goto-char (point-max)))
016c214f
RS
674 (save-excursion
675 ;; Find next match, but give up if prev match was at end of buffer.
dd4e0e55 676 (while (and (not (eobp))
016c214f
RS
677 (re-search-forward regexp nil t))
678 (goto-char (match-beginning 0))
679 (beginning-of-line)
680 (save-match-data
681 (setq linenum (+ linenum (count-lines prevpos (point)))))
682 (setq prevpos (point))
683 (goto-char (match-end 0))
d79dfd47
GM
684 (let* (;;start point of text in source buffer to be put
685 ;;into *Occur*
686 (start (save-excursion
016c214f 687 (goto-char (match-beginning 0))
e09d4033
RS
688 (forward-line (if (< nlines 0)
689 nlines
690 (- nlines)))
016c214f 691 (point)))
e09d4033
RS
692 ;; end point of text in source buffer to be put
693 ;; into *Occur*
d79dfd47
GM
694 (end (save-excursion
695 (goto-char (match-end 0))
696 (if (> nlines 0)
697 (forward-line (1+ nlines))
698 (forward-line 1))
699 (point)))
e09d4033 700 ;; Amount of context before matching text
d79dfd47 701 (match-beg (- (match-beginning 0) start))
e09d4033 702 ;; Length of matching text
d79dfd47
GM
703 (match-len (- (match-end 0) (match-beginning 0)))
704 (tag (format line-number-format linenum))
e730be7f 705 tem
0f0a7f7c 706 insertion-start
e09d4033 707 ;; Number of lines of context to show for current match.
e730be7f 708 occur-marker
e09d4033
RS
709 ;; Marker pointing to end of match in source buffer.
710 (text-beg
711 ;; Marker pointing to start of text for one
712 ;; match in *Occur*.
713 (make-marker))
e730be7f 714 (text-end
e09d4033
RS
715 ;; Marker pointing to end of text for one match
716 ;; in *Occur*.
d79dfd47 717 (make-marker)))
016c214f 718 (save-excursion
8d15583f
RS
719 (setq occur-marker (make-marker))
720 (set-marker occur-marker (point))
016c214f 721 (set-buffer standard-output)
8d15583f 722 (setq occur-num-matches (1+ occur-num-matches))
016c214f
RS
723 (or first (zerop nlines)
724 (insert "--------\n"))
725 (setq first nil)
d79dfd47
GM
726 (save-excursion
727 (set-buffer "*Occur*")
728 (setq tab-width current-tab-width))
e09d4033
RS
729
730 ;; Insert matching text including context lines from
731 ;; source buffer into *Occur*
8d15583f 732 (set-marker text-beg (point))
0f0a7f7c 733 (setq insertion-start (point))
016c214f 734 (insert-buffer-substring buffer start end)
0f0a7f7c
KH
735 (or (and (/= (+ start match-beg) end)
736 (with-current-buffer buffer
737 (eq (char-before end) ?\n)))
738 (insert "\n"))
e730be7f 739 (set-marker final-context-start
0f0a7f7c
KH
740 (+ (- (point) (- end (match-end 0)))
741 (if (save-excursion
742 (set-buffer buffer)
743 (save-excursion
744 (goto-char (match-end 0))
745 (end-of-line)
746 (bolp)))
747 1 0)))
8d15583f 748 (set-marker text-end (point))
e09d4033
RS
749
750 ;; Highlight text that was matched.
8d15583f
RS
751 (if list-matching-lines-face
752 (put-text-property
753 (+ (marker-position text-beg) match-beg)
754 (+ (marker-position text-beg) match-beg match-len)
755 'face list-matching-lines-face))
756
e09d4033
RS
757 ;; `occur-point' property is used by occur-next and
758 ;; occur-prev to move between matching lines.
8d15583f
RS
759 (put-text-property
760 (+ (marker-position text-beg) match-beg match-len)
761 (+ (marker-position text-beg) match-beg match-len 1)
762 'occur-point t)
e09d4033
RS
763
764 ;; Now go back to the start of the matching text
765 ;; adding the space and colon to the start of each line.
0f0a7f7c 766 (goto-char insertion-start)
e09d4033 767 ;; Insert space and colon for lines of context before match.
8d15583f
RS
768 (setq tem (if (< linenum nlines)
769 (- nlines linenum)
770 nlines))
016c214f
RS
771 (while (> tem 0)
772 (insert empty ?:)
773 (forward-line 1)
774 (setq tem (1- tem)))
e09d4033
RS
775
776 ;; Insert line number and colon for the lines of
777 ;; matching text.
778 (let ((this-linenum linenum))
016c214f
RS
779 (while (< (point) final-context-start)
780 (if (null tag)
d79dfd47 781 (setq tag (format line-number-format this-linenum)))
016c214f 782 (insert tag ?:)
016c214f
RS
783 (forward-line 1)
784 (setq tag nil)
785 (setq this-linenum (1+ this-linenum)))
0f0a7f7c 786 (while (and (not (eobp)) (<= (point) final-context-start))
016c214f
RS
787 (insert empty ?:)
788 (forward-line 1)
789 (setq this-linenum (1+ this-linenum))))
e09d4033
RS
790
791 ;; Insert space and colon for lines of context after match.
8d15583f 792 (while (and (< (point) (point-max)) (< tem nlines))
016c214f
RS
793 (insert empty ?:)
794 (forward-line 1)
795 (setq tem (1+ tem)))
8d15583f
RS
796
797 ;; Add text properties. The `occur' prop is used to
798 ;; store the marker of the matching text in the
799 ;; source buffer.
2ddf19df
EZ
800 (add-text-properties
801 (marker-position text-beg) (- (marker-position text-end) 1)
802 '(mouse-face highlight
75f70c1c 803 help-echo "mouse-2: go to this occurrence"))
8d15583f 804 (put-text-property (marker-position text-beg)
e09d4033 805 (marker-position text-end)
8d15583f 806 'occur occur-marker)
016c214f
RS
807 (goto-char (point-max)))
808 (forward-line 1)))
809 (set-buffer standard-output)
e09d4033
RS
810 ;; Go back to top of *Occur* and finish off by printing the
811 ;; number of matching lines.
016c214f 812 (goto-char (point-min))
65b4665c 813 (let ((message-string
8d15583f 814 (if (= occur-num-matches 1)
65b4665c 815 "1 line"
8d15583f 816 (format "%d lines" occur-num-matches))))
65b4665c
RS
817 (insert message-string)
818 (if (interactive-p)
5ddf4bda
KH
819 (message "%s matched" message-string)))
820 (setq buffer-read-only t)))))))
698e1804 821\f
81bdc14d
RS
822;; It would be nice to use \\[...], but there is no reasonable way
823;; to make that display both SPC and Y.
698e1804
RS
824(defconst query-replace-help
825 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
be44f62c 826RET or `q' to exit, Period to replace one match and exit,
698e1804
RS
827Comma to replace but not move point immediately,
828C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
829C-w to delete match and recursive edit,
830C-l to clear the screen, redisplay, and offer same replacement again,
831! to replace all remaining matches with no more questions,
7ce278f3
GM
832^ to move point back to previous match,
833E to edit the replacement string"
f54701d1 834 "Help message while in `query-replace'.")
698e1804 835
81bdc14d
RS
836(defvar query-replace-map (make-sparse-keymap)
837 "Keymap that defines the responses to questions in `query-replace'.
838The \"bindings\" in this map are not commands; they are answers.
839The valid answers include `act', `skip', `act-and-show',
840`exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
d9121bc0 841`automatic', `backup', `exit-prefix', and `help'.")
81bdc14d
RS
842
843(define-key query-replace-map " " 'act)
844(define-key query-replace-map "\d" 'skip)
845(define-key query-replace-map [delete] 'skip)
9275e5e3 846(define-key query-replace-map [backspace] 'skip)
81bdc14d
RS
847(define-key query-replace-map "y" 'act)
848(define-key query-replace-map "n" 'skip)
633a305a
RS
849(define-key query-replace-map "Y" 'act)
850(define-key query-replace-map "N" 'skip)
34724fcb 851(define-key query-replace-map "e" 'edit-replacement)
7ce278f3 852(define-key query-replace-map "E" 'edit-replacement)
81bdc14d 853(define-key query-replace-map "," 'act-and-show)
81bdc14d 854(define-key query-replace-map "q" 'exit)
919592c0 855(define-key query-replace-map "\r" 'exit)
384c7da4 856(define-key query-replace-map [return] 'exit)
81bdc14d
RS
857(define-key query-replace-map "." 'act-and-exit)
858(define-key query-replace-map "\C-r" 'edit)
859(define-key query-replace-map "\C-w" 'delete-and-edit)
860(define-key query-replace-map "\C-l" 'recenter)
861(define-key query-replace-map "!" 'automatic)
862(define-key query-replace-map "^" 'backup)
863(define-key query-replace-map "\C-h" 'help)
e731045a
KH
864(define-key query-replace-map [f1] 'help)
865(define-key query-replace-map [help] 'help)
81bdc14d 866(define-key query-replace-map "?" 'help)
bc6312e1
RS
867(define-key query-replace-map "\C-g" 'quit)
868(define-key query-replace-map "\C-]" 'quit)
d9121bc0
RS
869(define-key query-replace-map "\e" 'exit-prefix)
870(define-key query-replace-map [escape] 'exit-prefix)
81bdc14d 871
84482eb3 872(defun replace-match-string-symbols (n)
e730be7f
DL
873 "Process a list (and any sub-lists), expanding certain symbols.
874Symbol Expands To
875N (match-string N) (where N is a string of digits)
876#N (string-to-number (match-string N))
877& (match-string 0)
878#& (string-to-number (match-string 0))
879
880Note that these symbols must be preceeded by a backslash in order to
881type them."
84482eb3
RS
882 (while n
883 (cond
884 ((consp (car n))
885 (replace-match-string-symbols (car n))) ;Process sub-list
886 ((symbolp (car n))
887 (let ((name (symbol-name (car n))))
888 (cond
889 ((string-match "^[0-9]+$" name)
890 (setcar n (list 'match-string (string-to-number name))))
891 ((string-match "^#[0-9]+$" name)
892 (setcar n (list 'string-to-number
893 (list 'match-string
894 (string-to-number (substring name 1))))))
895 ((string= "&" name)
896 (setcar n '(match-string 0)))
897 ((string= "#&" name)
898 (setcar n '(string-to-number (match-string 0))))))))
899 (setq n (cdr n))))
900
901(defun replace-eval-replacement (expression replace-count)
902 (let ((replacement (eval expression)))
903 (if (stringp replacement)
904 replacement
905 (prin1-to-string replacement t))))
906
907(defun replace-loop-through-replacements (data replace-count)
908 ;; DATA is a vector contaning the following values:
909 ;; 0 next-rotate-count
910 ;; 1 repeat-count
911 ;; 2 next-replacement
912 ;; 3 replacements
913 (if (= (aref data 0) replace-count)
914 (progn
915 (aset data 0 (+ replace-count (aref data 1)))
916 (let ((next (cdr (aref data 2))))
917 (aset data 2 (if (consp next) next (aref data 3))))))
918 (car (aref data 2)))
919
99a7559f 920(defun perform-replace (from-string replacements
698e1804 921 query-flag regexp-flag delimited-flag
99a7559f 922 &optional repeat-count map start end)
698e1804
RS
923 "Subroutine of `query-replace'. Its complexity handles interactive queries.
924Don't use this in your own program unless you want to query and set the mark
925just as `query-replace' does. Instead, write a simple loop like this:
698665d1
GM
926
927 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
698e1804 928 (replace-match \"foobar\" nil nil))
698665d1
GM
929
930which will run faster and probably do exactly what you want. Please
931see the documentation of `replace-match' to find out how to simulate
932`case-replace'."
81bdc14d 933 (or map (setq map query-replace-map))
1c1dadab
RS
934 (and query-flag minibuffer-auto-raise
935 (raise-frame (window-frame (minibuffer-window))))
698e1804
RS
936 (let ((nocasify (not (and case-fold-search case-replace
937 (string-equal from-string
938 (downcase from-string)))))
5a78b471
KH
939 (case-fold-search (and case-fold-search
940 (string-equal from-string
941 (downcase from-string))))
698e1804
RS
942 (literal (not regexp-flag))
943 (search-function (if regexp-flag 're-search-forward 'search-forward))
944 (search-string from-string)
e5d77022 945 (real-match-data nil) ; the match data for the current match
698e1804 946 (next-replacement nil)
698e1804
RS
947 (keep-going t)
948 (stack nil)
698e1804 949 (replace-count 0)
5632eb27
PE
950 (nonempty-match nil)
951
7ef5c431
KH
952 ;; If non-nil, it is marker saying where in the buffer to stop.
953 (limit nil)
954
5632eb27
PE
955 ;; Data for the next match. If a cons, it has the same format as
956 ;; (match-data); otherwise it is t if a match is possible at point.
ae4eb03c 957 (match-again t)
5632eb27 958
02d95a27
RS
959 (message
960 (if query-flag
961 (substitute-command-keys
962 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
7ef5c431
KH
963
964 ;; If region is active, in Transient Mark mode, operate on region.
47d72254
GM
965 (when start
966 (setq limit (copy-marker (max start end)))
967 (goto-char (min start end))
968 (deactivate-mark))
84482eb3
RS
969
970 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
971 ;; containing a function and its first argument. The function is
972 ;; called to generate each replacement like this:
973 ;; (funcall (car replacements) (cdr replacements) replace-count)
974 ;; It must return a string.
975 (cond
976 ((stringp replacements)
977 (setq next-replacement replacements
978 replacements nil))
979 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
980 (or repeat-count (setq repeat-count 1))
981 (setq replacements (cons 'replace-loop-through-replacements
982 (vector repeat-count repeat-count
983 replacements replacements)))))
984
698e1804
RS
985 (if delimited-flag
986 (setq search-function 're-search-forward
987 search-string (concat "\\b"
988 (if regexp-flag from-string
989 (regexp-quote from-string))
990 "\\b")))
991 (push-mark)
992 (undo-boundary)
e782e9f2
RS
993 (unwind-protect
994 ;; Loop finding occurrences that perhaps should be replaced.
995 (while (and keep-going
996 (not (eobp))
5632eb27
PE
997 ;; Use the next match if it is already known;
998 ;; otherwise, search for a match after moving forward
999 ;; one char if progress is required.
1000 (setq real-match-data
1001 (if (consp match-again)
1002 (progn (goto-char (nth 1 match-again))
1003 match-again)
1004 (and (or match-again
889617de
GM
1005 ;; MATCH-AGAIN non-nil means we
1006 ;; accept an adjacent match. If
1007 ;; we don't, move one char to the
1008 ;; right. This takes us a
1009 ;; character too far at the end,
1010 ;; but this is undone after the
1011 ;; while-loop.
8f3ff96b 1012 (progn (forward-char 1) (not (eobp))))
7ef5c431 1013 (funcall search-function search-string limit t)
5632eb27
PE
1014 ;; For speed, use only integers and
1015 ;; reuse the list used last time.
1016 (match-data t real-match-data)))))
1c4fe319
RS
1017 ;; Optionally ignore matches that have a read-only property.
1018 (unless (and query-replace-skip-read-only
1019 (text-property-not-all
1020 (match-beginning 0) (match-end 0)
1021 'read-only nil))
1022
1023 ;; Record whether the match is nonempty, to avoid an infinite loop
1024 ;; repeatedly matching the same empty string.
1025 (setq nonempty-match
1026 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1027
1028 ;; If the match is empty, record that the next one can't be
1029 ;; adjacent.
1030
1031 ;; Otherwise, if matching a regular expression, do the next
1032 ;; match now, since the replacement for this match may
1033 ;; affect whether the next match is adjacent to this one.
1034 ;; If that match is empty, don't use it.
1035 (setq match-again
1036 (and nonempty-match
1037 (or (not regexp-flag)
1038 (and (looking-at search-string)
1039 (let ((match (match-data)))
1040 (and (/= (nth 0 match) (nth 1 match))
1041 match))))))
1042
1043 ;; Calculate the replacement string, if necessary.
1044 (when replacements
1045 (set-match-data real-match-data)
1046 (setq next-replacement
1047 (funcall (car replacements) (cdr replacements)
1048 replace-count)))
1049 (if (not query-flag)
1050 (let ((inhibit-read-only query-replace-skip-read-only))
1051 (set-match-data real-match-data)
1052 (replace-match next-replacement nocasify literal)
1053 (setq replace-count (1+ replace-count)))
1054 (undo-boundary)
1055 (let (done replaced key def)
1056 ;; Loop reading commands until one of them sets done,
1057 ;; which means it has finished handling this occurrence.
1058 (while (not done)
1059 (set-match-data real-match-data)
1060 (replace-highlight (match-beginning 0) (match-end 0))
1061 ;; Bind message-log-max so we don't fill up the message log
1062 ;; with a bunch of identical messages.
1063 (let ((message-log-max nil))
1064 (message message from-string next-replacement))
1065 (setq key (read-event))
1066 ;; Necessary in case something happens during read-event
1067 ;; that clobbers the match data.
1068 (set-match-data real-match-data)
1069 (setq key (vector key))
1070 (setq def (lookup-key map key))
1071 ;; Restore the match data while we process the command.
1072 (cond ((eq def 'help)
1073 (with-output-to-temp-buffer "*Help*"
1074 (princ
1075 (concat "Query replacing "
1076 (if regexp-flag "regexp " "")
1077 from-string " with "
1078 next-replacement ".\n\n"
1079 (substitute-command-keys
1080 query-replace-help)))
1081 (with-current-buffer standard-output
1082 (help-mode))))
1083 ((eq def 'exit)
1084 (setq keep-going nil)
1085 (setq done t))
1086 ((eq def 'backup)
1087 (if stack
1088 (let ((elt (car stack)))
1089 (goto-char (car elt))
1090 (setq replaced (eq t (cdr elt)))
1091 (or replaced
1092 (set-match-data (cdr elt)))
1093 (setq stack (cdr stack)))
1094 (message "No previous match")
1095 (ding 'no-terminate)
1096 (sit-for 1)))
1097 ((eq def 'act)
1098 (or replaced
1099 (progn
1100 (replace-match next-replacement nocasify literal)
1101 (setq replace-count (1+ replace-count))))
1102 (setq done t replaced t))
1103 ((eq def 'act-and-exit)
1104 (or replaced
1105 (progn
1106 (replace-match next-replacement nocasify literal)
1107 (setq replace-count (1+ replace-count))))
1108 (setq keep-going nil)
1109 (setq done t replaced t))
1110 ((eq def 'act-and-show)
1111 (if (not replaced)
1112 (progn
1113 (replace-match next-replacement nocasify literal)
1114 (setq replace-count (1+ replace-count))
1115 (setq replaced t))))
1116 ((eq def 'automatic)
1117 (or replaced
1118 (progn
1119 (replace-match next-replacement nocasify literal)
1120 (setq replace-count (1+ replace-count))))
1121 (setq done t query-flag nil replaced t))
1122 ((eq def 'skip)
1123 (setq done t))
1124 ((eq def 'recenter)
1125 (recenter nil))
1126 ((eq def 'edit)
1127 (let ((opos (point-marker)))
1128 (goto-char (match-beginning 0))
1129 (save-excursion
1130 (funcall search-function search-string limit t)
1131 (setq real-match-data (match-data)))
86914dcc
RS
1132 (save-excursion
1133 (save-window-excursion
1134 (recursive-edit)))
1c4fe319
RS
1135 (goto-char opos))
1136 (set-match-data real-match-data)
1137 ;; Before we make the replacement,
1138 ;; decide whether the search string
1139 ;; can match again just after this match.
1140 (if (and regexp-flag nonempty-match)
1141 (setq match-again (and (looking-at search-string)
1142 (match-data)))))
7ce278f3 1143
1c4fe319
RS
1144 ;; Edit replacement.
1145 ((eq def 'edit-replacement)
1146 (setq next-replacement
1147 (read-input "Edit replacement string: "
1148 next-replacement))
1149 (or replaced
1150 (replace-match next-replacement nocasify literal))
1151 (setq done t))
7ce278f3 1152
1c4fe319
RS
1153 ((eq def 'delete-and-edit)
1154 (delete-region (match-beginning 0) (match-end 0))
1155 (set-match-data
1156 (prog1 (match-data)
1157 (save-excursion (recursive-edit))))
1158 (setq replaced t))
1159 ;; Note: we do not need to treat `exit-prefix'
1160 ;; specially here, since we reread
1161 ;; any unrecognized character.
1162 (t
1163 (setq this-command 'mode-exited)
1164 (setq keep-going nil)
1165 (setq unread-command-events
1166 (append (listify-key-sequence key)
1167 unread-command-events))
1168 (setq done t))))
1169 ;; Record previous position for ^ when we move on.
1170 ;; Change markers to numbers in the match data
1171 ;; since lots of markers slow down editing.
1172 (setq stack
1173 (cons (cons (point)
1174 (or replaced (match-data t)))
1175 stack))))))
889617de
GM
1176
1177 ;; The code preventing adjacent regexp matches in the condition
1178 ;; of the while-loop above will haven taken us one character
1179 ;; beyond the last replacement. Undo that.
1180 (when (and regexp-flag (not match-again) (> replace-count 0))
1181 (backward-char 1))
1182
e782e9f2 1183 (replace-dehighlight))
4d33492a
RS
1184 (or unread-command-events
1185 (message "Replaced %d occurrence%s"
1186 replace-count
1187 (if (= replace-count 1) "" "s")))
1188 (and keep-going stack)))
698e1804 1189
95807e68 1190(defcustom query-replace-highlight t
9d325ebf
RS
1191 "*Non-nil means to highlight words during query replacement."
1192 :type 'boolean
1193 :group 'matching)
e782e9f2
RS
1194
1195(defvar replace-overlay nil)
1196
1197(defun replace-dehighlight ()
1198 (and replace-overlay
1199 (progn
1200 (delete-overlay replace-overlay)
1201 (setq replace-overlay nil))))
1202
1203(defun replace-highlight (start end)
1204 (and query-replace-highlight
1205 (progn
1206 (or replace-overlay
1207 (progn
1208 (setq replace-overlay (make-overlay start end))
1209 (overlay-put replace-overlay 'face
e730be7f 1210 (if (facep 'query-replace)
e782e9f2
RS
1211 'query-replace 'region))))
1212 (move-overlay replace-overlay start end (current-buffer)))))
1213
c88ab9ce 1214;;; replace.el ends here