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