(smtpmail-via-smtp): Speciy process coding system.
[bpt/emacs.git] / lisp / replace.el
CommitLineData
c88ab9ce
ER
1;;; replace.el --- replace commands for Emacs.
2
aeab5be0 3;; Copyright (C) 1985, 86, 87, 92, 94, 96, 1997 Free Software Foundation, Inc.
3a801d0c 4
698e1804
RS
5;; This file is part of GNU Emacs.
6
7;; GNU Emacs is free software; you can redistribute it and/or modify
8;; it under the terms of the GNU General Public License as published by
e5d77022 9;; the Free Software Foundation; either version 2, or (at your option)
698e1804
RS
10;; any later version.
11
12;; GNU Emacs is distributed in the hope that it will be useful,
13;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15;; GNU General Public License for more details.
16
17;; You should have received a copy of the GNU General Public License
b578f267
EN
18;; along with GNU Emacs; see the file COPYING. If not, write to the
19;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
20;; Boston, MA 02111-1307, USA.
698e1804 21
d9ecc911
ER
22;;; Commentary:
23
24;; This package supplies the string and regular-expression replace functions
25;; documented in the Emacs user's manual.
26
4f4b8eff 27;;; Code:
698e1804 28
9d325ebf
RS
29(defcustom case-replace t
30 "*Non-nil means query-replace should preserve case in replacements."
31 :type 'boolean
32 :group 'matching)
77176e73 33
770970cb
RS
34(defvar query-replace-history nil)
35
151270f3
RS
36(defvar query-replace-interactive nil
37 "Non-nil means `query-replace' uses the last search string.
38That becomes the \"string to replace\".")
39
bdb1c08f
RS
40(defcustom query-replace-from-history-variable 'query-replace-history
41 "History list to use for the FROM argument of query-replace commands.
42The value of this variable should be a symbol; that symbol
43is used as a variable to hold a history list for the strings
44or patterns to be replaced."
45 :group 'matching
cd32a7ba
DN
46 :type 'symbol
47 :version "20.3")
bdb1c08f
RS
48
49(defcustom query-replace-to-history-variable 'query-replace-history
50 "History list to use for the TO argument of query-replace commands.
51The value of this variable should be a symbol; that symbol
52is used as a variable to hold a history list for replacement
53strings or patterns."
54 :group 'matching
cd32a7ba
DN
55 :type 'symbol
56 :version "20.3")
bdb1c08f 57
151270f3 58(defun query-replace-read-args (string regexp-flag)
770970cb 59 (let (from to)
151270f3
RS
60 (if query-replace-interactive
61 (setq from (car (if regexp-flag regexp-search-ring search-ring)))
62 (setq from (read-from-minibuffer (format "%s: " string)
63 nil nil nil
bdb1c08f
RS
64 query-replace-from-history-variable
65 nil t)))
770970cb
RS
66 (setq to (read-from-minibuffer (format "%s %s with: " string from)
67 nil nil nil
4a8f3b3d 68 query-replace-to-history-variable from t))
770970cb
RS
69 (list from to current-prefix-arg)))
70
da44e784
RM
71(defun query-replace (from-string to-string &optional arg)
72 "Replace some occurrences of FROM-STRING with TO-STRING.
73As each match is found, the user must type a character saying
74what to do with it. For directions, type \\[help-command] at that time.
75
7ef5c431
KH
76In Transient Mark mode, if the mark is active, operate on the contents
77of the region. Otherwise, operate from point to the end of the buffer.
78
151270f3
RS
79If `query-replace-interactive' is non-nil, the last incremental search
80string is used as FROM-STRING--you don't have to specify it with the
81minibuffer.
82
118a01c9 83Preserves case in each replacement if `case-replace' and `case-fold-search'
da44e784 84are non-nil and FROM-STRING has no uppercase letters.
9b0bf2b6
RS
85\(Preserving case means that if the string matched is all caps, or capitalized,
86then its replacement is upcased or capitalized.)
87
118a01c9 88Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
81bdc14d
RS
89only matches surrounded by word boundaries.
90
91To customize possible responses, change the \"bindings\" in `query-replace-map'."
151270f3 92 (interactive (query-replace-read-args "Query replace" nil))
4d33492a 93 (perform-replace from-string to-string t nil arg))
7ef5c431 94
73fa8346 95(define-key esc-map "%" 'query-replace)
da44e784 96
da44e784
RM
97(defun query-replace-regexp (regexp to-string &optional arg)
98 "Replace some things after point matching REGEXP with TO-STRING.
99As each match is found, the user must type a character saying
100what to do with it. For directions, type \\[help-command] at that time.
101
7ef5c431
KH
102In Transient Mark mode, if the mark is active, operate on the contents
103of the region. Otherwise, operate from point to the end of the buffer.
104
151270f3
RS
105If `query-replace-interactive' is non-nil, the last incremental search
106regexp is used as REGEXP--you don't have to specify it with the
107minibuffer.
108
118a01c9 109Preserves case in each replacement if `case-replace' and `case-fold-search'
da44e784 110are non-nil and REGEXP has no uppercase letters.
118a01c9 111Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
da44e784 112only matches surrounded by word boundaries.
118a01c9
RS
113In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
114and `\\=\\N' (where N is a digit) stands for
115 whatever what matched the Nth `\\(...\\)' in REGEXP."
151270f3 116 (interactive (query-replace-read-args "Query replace regexp" t))
4d33492a 117 (perform-replace regexp to-string t t arg))
da44e784 118
da44e784
RM
119(defun map-query-replace-regexp (regexp to-strings &optional arg)
120 "Replace some matches for REGEXP with various strings, in rotation.
121The second argument TO-STRINGS contains the replacement strings, separated
122by spaces. This command works like `query-replace-regexp' except
123that each successive replacement uses the next successive replacement string,
124wrapping around from the last such string to the first.
125
7ef5c431
KH
126In Transient Mark mode, if the mark is active, operate on the contents
127of the region. Otherwise, operate from point to the end of the buffer.
128
da44e784
RM
129Non-interactively, TO-STRINGS may be a list of replacement strings.
130
151270f3
RS
131If `query-replace-interactive' is non-nil, the last incremental search
132regexp is used as REGEXP--you don't have to specify it with the minibuffer.
133
da44e784
RM
134A prefix argument N says to use each replacement string N times
135before rotating to the next."
770970cb
RS
136 (interactive
137 (let (from to)
151270f3
RS
138 (setq from (if query-replace-interactive
139 (car regexp-search-ring)
140 (read-from-minibuffer "Map query replace (regexp): "
141 nil nil nil
fce31d51 142 'query-replace-history nil t)))
770970cb
RS
143 (setq to (read-from-minibuffer
144 (format "Query replace %s with (space-separated strings): "
145 from)
146 nil nil nil
4a8f3b3d 147 'query-replace-history from t))
770970cb 148 (list from to current-prefix-arg)))
da44e784
RM
149 (let (replacements)
150 (if (listp to-strings)
151 (setq replacements to-strings)
152 (while (/= (length to-strings) 0)
153 (if (string-match " " to-strings)
154 (setq replacements
155 (append replacements
156 (list (substring to-strings 0
157 (string-match " " to-strings))))
158 to-strings (substring to-strings
159 (1+ (string-match " " to-strings))))
160 (setq replacements (append replacements (list to-strings))
161 to-strings ""))))
4d33492a 162 (perform-replace regexp replacements t t nil arg)))
da44e784 163
da44e784
RM
164(defun replace-string (from-string to-string &optional delimited)
165 "Replace occurrences of FROM-STRING with TO-STRING.
166Preserve case in each match if `case-replace' and `case-fold-search'
167are non-nil and FROM-STRING has no uppercase letters.
9b0bf2b6
RS
168\(Preserving case means that if the string matched is all caps, or capitalized,
169then its replacement is upcased or capitalized.)
170
7ef5c431
KH
171In Transient Mark mode, if the mark is active, operate on the contents
172of the region. Otherwise, operate from point to the end of the buffer.
173
118a01c9 174Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
da44e784
RM
175only matches surrounded by word boundaries.
176
151270f3
RS
177If `query-replace-interactive' is non-nil, the last incremental search
178string is used as FROM-STRING--you don't have to specify it with the
179minibuffer.
180
da44e784
RM
181This function is usually the wrong thing to use in a Lisp program.
182What you probably want is a loop like this:
118a01c9
RS
183 (while (search-forward FROM-STRING nil t)
184 (replace-match TO-STRING nil t))
87532fbe
RS
185which will run faster and will not set the mark or print anything.
186\(You may need a more complex loop if FROM-STRING can match the null string
187and TO-STRING is also null.)"
151270f3 188 (interactive (query-replace-read-args "Replace string" nil))
4d33492a 189 (perform-replace from-string to-string nil nil delimited))
da44e784 190
da44e784
RM
191(defun replace-regexp (regexp to-string &optional delimited)
192 "Replace things after point matching REGEXP with TO-STRING.
118a01c9 193Preserve case in each match if `case-replace' and `case-fold-search'
da44e784 194are non-nil and REGEXP has no uppercase letters.
118a01c9 195Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
da44e784 196only matches surrounded by word boundaries.
118a01c9
RS
197In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
198and `\\=\\N' (where N is a digit) stands for
880f22a1 199 whatever what matched the Nth `\\(...\\)' in REGEXP.
da44e784 200
7ef5c431
KH
201In Transient Mark mode, if the mark is active, operate on the contents
202of the region. Otherwise, operate from point to the end of the buffer.
203
151270f3
RS
204If `query-replace-interactive' is non-nil, the last incremental search
205regexp is used as REGEXP--you don't have to specify it with the minibuffer.
206
da44e784
RM
207This function is usually the wrong thing to use in a Lisp program.
208What you probably want is a loop like this:
209 (while (re-search-forward REGEXP nil t)
118a01c9 210 (replace-match TO-STRING nil nil))
da44e784 211which will run faster and will not set the mark or print anything."
151270f3 212 (interactive (query-replace-read-args "Replace regexp" t))
4d33492a 213 (perform-replace regexp to-string nil t delimited))
4c53bd2b
RS
214\f
215(defvar regexp-history nil
216 "History list for some commands that read regular expressions.")
da44e784 217
31e1d920 218(defalias 'delete-non-matching-lines 'keep-lines)
698e1804
RS
219(defun keep-lines (regexp)
220 "Delete all lines except those containing matches for REGEXP.
221A match split across lines preserves all the lines it lies in.
222Applies to all lines after point."
4c53bd2b 223 (interactive (list (read-from-minibuffer
72f21cdf 224 "Keep lines (containing match for regexp): "
fce31d51 225 nil nil nil 'regexp-history nil t)))
698e1804
RS
226 (save-excursion
227 (or (bolp) (forward-line 1))
228 (let ((start (point)))
229 (while (not (eobp))
230 ;; Start is first char not preserved by previous match.
231 (if (not (re-search-forward regexp nil 'move))
232 (delete-region start (point-max))
233 (let ((end (save-excursion (goto-char (match-beginning 0))
234 (beginning-of-line)
235 (point))))
236 ;; Now end is first char preserved by the new match.
237 (if (< start end)
238 (delete-region start end))))
239 (setq start (save-excursion (forward-line 1)
240 (point)))
241 ;; If the match was empty, avoid matching again at same place.
242 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
243 (forward-char 1))))))
244
31e1d920 245(defalias 'delete-matching-lines 'flush-lines)
698e1804
RS
246(defun flush-lines (regexp)
247 "Delete lines containing matches for REGEXP.
248If a match is split across lines, all the lines it lies in are deleted.
249Applies to lines after point."
4c53bd2b 250 (interactive (list (read-from-minibuffer
72f21cdf 251 "Flush lines (containing match for regexp): "
fce31d51 252 nil nil nil 'regexp-history nil t)))
698e1804
RS
253 (save-excursion
254 (while (and (not (eobp))
255 (re-search-forward regexp nil t))
256 (delete-region (save-excursion (goto-char (match-beginning 0))
257 (beginning-of-line)
258 (point))
259 (progn (forward-line 1) (point))))))
260
31e1d920 261(defalias 'count-matches 'how-many)
698e1804
RS
262(defun how-many (regexp)
263 "Print number of matches for REGEXP following point."
fce31d51
KH
264 (interactive (list(read-from-minibuffer
265 "How many matches for (regexp): "
266 nil nil nil 'regexp-history nil t)))
698e1804
RS
267 (let ((count 0) opoint)
268 (save-excursion
269 (while (and (not (eobp))
270 (progn (setq opoint (point))
271 (re-search-forward regexp nil t)))
272 (if (= opoint (point))
273 (forward-char 1)
274 (setq count (1+ count))))
275 (message "%d occurrences" count))))
4c53bd2b 276\f
698e1804
RS
277(defvar occur-mode-map ())
278(if occur-mode-map
279 ()
280 (setq occur-mode-map (make-sparse-keymap))
78bead73 281 (define-key occur-mode-map [mouse-2] 'occur-mode-mouse-goto)
0081c8a1 282 (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence)
a41284da 283 (define-key occur-mode-map "\C-m" 'occur-mode-goto-occurrence)
8d15583f
RS
284 (define-key occur-mode-map "\M-n" 'occur-next)
285 (define-key occur-mode-map "\M-p" 'occur-prev)
a41284da 286 (define-key occur-mode-map "g" 'revert-buffer))
698e1804 287
e09d4033
RS
288
289(defvar occur-buffer nil
290 "Name of buffer for last occur.")
291
292
293(defvar occur-nlines nil
294 "Number of lines of context to show around matching line.")
295
a41284da
RS
296(defvar occur-command-arguments nil
297 "Arguments that were given to `occur' when it made this buffer.")
698e1804 298
de3c9b09
RS
299(put 'occur-mode 'mode-class 'special)
300
698e1804
RS
301(defun occur-mode ()
302 "Major mode for output from \\[occur].
0081c8a1
RS
303\\<occur-mode-map>Move point to one of the items in this buffer, then use
304\\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
305Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
306
698e1804
RS
307\\{occur-mode-map}"
308 (kill-all-local-variables)
309 (use-local-map occur-mode-map)
310 (setq major-mode 'occur-mode)
311 (setq mode-name "Occur")
a41284da
RS
312 (make-local-variable 'revert-buffer-function)
313 (setq revert-buffer-function 'occur-revert-function)
698e1804
RS
314 (make-local-variable 'occur-buffer)
315 (make-local-variable 'occur-nlines)
a41284da 316 (make-local-variable 'occur-command-arguments)
4baf5620 317 (run-hooks 'occur-mode-hook))
698e1804 318
a41284da
RS
319;; Handle revert-buffer for *Occur* buffers.
320(defun occur-revert-function (ignore1 ignore2)
321 (let ((args occur-command-arguments ))
322 (save-excursion
323 (set-buffer occur-buffer)
324 (apply 'occur args))))
325
78bead73
RS
326(defun occur-mode-mouse-goto (event)
327 "In Occur mode, go to the occurrence whose line you click on."
328 (interactive "e")
329 (let (buffer pos)
330 (save-excursion
331 (set-buffer (window-buffer (posn-window (event-end event))))
332 (save-excursion
333 (goto-char (posn-point (event-end event)))
334 (setq pos (occur-mode-find-occurrence))
335 (setq buffer occur-buffer)))
336 (pop-to-buffer buffer)
337 (goto-char (marker-position pos))))
338
339(defun occur-mode-find-occurrence ()
698e1804
RS
340 (if (or (null occur-buffer)
341 (null (buffer-name occur-buffer)))
342 (progn
8d15583f 343 (setq occur-buffer nil)
698e1804 344 (error "Buffer in which occurrences were found is deleted")))
8d15583f
RS
345 (let ((pos (get-text-property (point) 'occur)))
346 (if (null pos)
347 (error "No occurrence on this line")
348 pos)))
78bead73
RS
349
350(defun occur-mode-goto-occurrence ()
351 "Go to the occurrence the current line describes."
352 (interactive)
353 (let ((pos (occur-mode-find-occurrence)))
698e1804 354 (pop-to-buffer occur-buffer)
121e2227 355 (goto-char (marker-position pos))))
8d15583f
RS
356
357(defun occur-next (&optional n)
358 "Move to the Nth (default 1) next match in the *Occur* buffer."
359 (interactive "p")
360 (if (not n) (setq n 1))
361 (let ((r))
362 (while (> n 0)
363 (if (get-text-property (point) 'occur-point)
364 (forward-char 1))
365 (setq r (next-single-property-change (point) 'occur-point))
366 (if r
367 (goto-char r)
368 (error "no more matches"))
369 (setq n (1- n)))))
370
371
372
373(defun occur-prev (&optional n)
374 "Move to the Nth (default 1) previous match in the *Occur* buffer."
375 (interactive "p")
376 (if (not n) (setq n 1))
377 (let ((r))
378 (while (> n 0)
379
380 (setq r (get-text-property (point) 'occur-point))
381 (if r (forward-char -1))
382
383 (setq r (previous-single-property-change (point) 'occur-point))
384 (if r
385 (goto-char (- r 1))
386 (error "no earlier matches"))
387
388 (setq n (1- n)))))
4c53bd2b 389\f
9d325ebf 390(defcustom list-matching-lines-default-context-lines 0
da44e784 391 "*Default number of context lines to include around a `list-matching-lines'
698e1804 392match. A negative number means to include that many lines before the match.
9d325ebf
RS
393A positive number means to include that many lines both before and after."
394 :type 'integer
395 :group 'matching)
698e1804 396
31e1d920 397(defalias 'list-matching-lines 'occur)
698e1804 398
c9daced0
RS
399(defvar list-matching-lines-face 'bold
400 "*Face used by M-x list-matching-lines to show the text that matches.
401If the value is nil, don't highlight the matching portions specially.")
402
698e1804 403(defun occur (regexp &optional nlines)
99976f85 404 "Show all lines in the current buffer containing a match for REGEXP.
da44e784
RM
405
406If a match spreads across multiple lines, all those lines are shown.
698e1804 407
da44e784
RM
408Each line is displayed with NLINES lines before and after, or -NLINES
409before if NLINES is negative.
410NLINES defaults to `list-matching-lines-default-context-lines'.
698e1804
RS
411Interactively it is the prefix arg.
412
4c53bd2b 413The lines are shown in a buffer named `*Occur*'.
698e1804 414It serves as a menu to find any of the occurrences in this buffer.
de3c9b09 415\\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
9483d601 416
de3c9b09
RS
417If REGEXP contains upper case characters (excluding those preceded by `\\'),
418the matching is case-sensitive."
a5dfed3e
RS
419 (interactive
420 (list (let* ((default (car regexp-history))
421 (input
422 (read-from-minibuffer
423 (if default
424 (format "List lines matching regexp (default `%s'): "
425 default)
426 "List lines matching regexp: ")
aeab5be0 427 nil nil nil 'regexp-history default t)))
4a8f3b3d
RS
428 (and (equal input "") default
429 (setq input default))
aeab5be0 430 input)
a5dfed3e
RS
431 current-prefix-arg))
432 (let ((nlines (if nlines
433 (prefix-numeric-value nlines)
434 list-matching-lines-default-context-lines))
435 (first t)
e09d4033 436 ;;flag to prevent printing separator for first match
8d15583f 437 (occur-num-matches 0)
698e1804 438 (buffer (current-buffer))
bdd610b2 439 (dir default-directory)
698e1804 440 (linenum 1)
e09d4033
RS
441 (prevpos
442 ;;position of most recent match
443 (point-min))
9483d601
RS
444 (case-fold-search (and case-fold-search
445 (isearch-no-upper-case-p regexp t)))
e09d4033
RS
446 (final-context-start
447 ;; Marker to the start of context immediately following
448 ;; the matched text in *Occur*.
449 (make-marker)))
99976f85
RS
450;;; (save-excursion
451;;; (beginning-of-line)
452;;; (setq linenum (1+ (count-lines (point-min) (point))))
453;;; (setq prevpos (point)))
016c214f
RS
454 (save-excursion
455 (goto-char (point-min))
456 ;; Check first whether there are any matches at all.
457 (if (not (re-search-forward regexp nil t))
458 (message "No matches for `%s'" regexp)
459 ;; Back up, so the search loop below will find the first match.
460 (goto-char (match-beginning 0))
461 (with-output-to-temp-buffer "*Occur*"
462 (save-excursion
463 (set-buffer standard-output)
464 (setq default-directory dir)
465 ;; We will insert the number of lines, and "lines", later.
466 (insert " matching ")
467 (let ((print-escape-newlines t))
468 (prin1 regexp))
469 (insert " in buffer " (buffer-name buffer) ?. ?\n)
470 (occur-mode)
471 (setq occur-buffer buffer)
472 (setq occur-nlines nlines)
a41284da
RS
473 (setq occur-command-arguments
474 (list regexp nlines)))
016c214f 475 (if (eq buffer standard-output)
91c6bdc0 476 (goto-char (point-max)))
016c214f
RS
477 (save-excursion
478 ;; Find next match, but give up if prev match was at end of buffer.
479 (while (and (not (= prevpos (point-max)))
480 (re-search-forward regexp nil t))
481 (goto-char (match-beginning 0))
482 (beginning-of-line)
483 (save-match-data
484 (setq linenum (+ linenum (count-lines prevpos (point)))))
485 (setq prevpos (point))
486 (goto-char (match-end 0))
e09d4033
RS
487 (let* ((start
488 ;;start point of text in source buffer to be put
489 ;;into *Occur*
490 (save-excursion
016c214f 491 (goto-char (match-beginning 0))
e09d4033
RS
492 (forward-line (if (< nlines 0)
493 nlines
494 (- nlines)))
016c214f 495 (point)))
e09d4033
RS
496 (end
497 ;; end point of text in source buffer to be put
498 ;; into *Occur*
499 (save-excursion
500 (goto-char (match-end 0))
501 (if (> nlines 0)
502 (forward-line (1+ nlines))
503 (forward-line 1))
504 (point)))
505 (match-beg
506 ;; Amount of context before matching text
507 (- (match-beginning 0) start))
508 (match-len
509 ;; Length of matching text
510 (- (match-end 0) (match-beginning 0)))
016c214f
RS
511 (tag (format "%5d" linenum))
512 (empty (make-string (length tag) ?\ ))
e09d4033 513 tem
0f0a7f7c 514 insertion-start
e09d4033
RS
515 ;; Number of lines of context to show for current match.
516 occur-marker
517 ;; Marker pointing to end of match in source buffer.
518 (text-beg
519 ;; Marker pointing to start of text for one
520 ;; match in *Occur*.
521 (make-marker))
522 (text-end
523 ;; Marker pointing to end of text for one match
524 ;; in *Occur*.
525 (make-marker))
8d15583f 526 )
016c214f 527 (save-excursion
8d15583f
RS
528 (setq occur-marker (make-marker))
529 (set-marker occur-marker (point))
016c214f 530 (set-buffer standard-output)
8d15583f 531 (setq occur-num-matches (1+ occur-num-matches))
016c214f
RS
532 (or first (zerop nlines)
533 (insert "--------\n"))
534 (setq first nil)
e09d4033
RS
535
536 ;; Insert matching text including context lines from
537 ;; source buffer into *Occur*
8d15583f 538 (set-marker text-beg (point))
0f0a7f7c 539 (setq insertion-start (point))
016c214f 540 (insert-buffer-substring buffer start end)
0f0a7f7c
KH
541 (or (and (/= (+ start match-beg) end)
542 (with-current-buffer buffer
543 (eq (char-before end) ?\n)))
544 (insert "\n"))
545 (set-marker final-context-start
546 (+ (- (point) (- end (match-end 0)))
547 (if (save-excursion
548 (set-buffer buffer)
549 (save-excursion
550 (goto-char (match-end 0))
551 (end-of-line)
552 (bolp)))
553 1 0)))
8d15583f 554 (set-marker text-end (point))
e09d4033
RS
555
556 ;; Highlight text that was matched.
8d15583f
RS
557 (if list-matching-lines-face
558 (put-text-property
559 (+ (marker-position text-beg) match-beg)
560 (+ (marker-position text-beg) match-beg match-len)
561 'face list-matching-lines-face))
562
e09d4033
RS
563 ;; `occur-point' property is used by occur-next and
564 ;; occur-prev to move between matching lines.
8d15583f
RS
565 (put-text-property
566 (+ (marker-position text-beg) match-beg match-len)
567 (+ (marker-position text-beg) match-beg match-len 1)
568 'occur-point t)
e09d4033
RS
569
570 ;; Now go back to the start of the matching text
571 ;; adding the space and colon to the start of each line.
0f0a7f7c 572 (goto-char insertion-start)
e09d4033 573 ;; Insert space and colon for lines of context before match.
8d15583f
RS
574 (setq tem (if (< linenum nlines)
575 (- nlines linenum)
576 nlines))
016c214f
RS
577 (while (> tem 0)
578 (insert empty ?:)
579 (forward-line 1)
580 (setq tem (1- tem)))
e09d4033
RS
581
582 ;; Insert line number and colon for the lines of
583 ;; matching text.
584 (let ((this-linenum linenum))
016c214f
RS
585 (while (< (point) final-context-start)
586 (if (null tag)
587 (setq tag (format "%5d" this-linenum)))
588 (insert tag ?:)
016c214f
RS
589 (forward-line 1)
590 (setq tag nil)
591 (setq this-linenum (1+ this-linenum)))
0f0a7f7c 592 (while (and (not (eobp)) (<= (point) final-context-start))
016c214f
RS
593 (insert empty ?:)
594 (forward-line 1)
595 (setq this-linenum (1+ this-linenum))))
e09d4033
RS
596
597 ;; Insert space and colon for lines of context after match.
8d15583f 598 (while (and (< (point) (point-max)) (< tem nlines))
016c214f
RS
599 (insert empty ?:)
600 (forward-line 1)
601 (setq tem (1+ tem)))
8d15583f
RS
602
603 ;; Add text properties. The `occur' prop is used to
604 ;; store the marker of the matching text in the
605 ;; source buffer.
606 (put-text-property (marker-position text-beg)
607 (- (marker-position text-end) 1)
608 'mouse-face 'highlight)
609 (put-text-property (marker-position text-beg)
e09d4033 610 (marker-position text-end)
8d15583f 611 'occur occur-marker)
016c214f
RS
612 (goto-char (point-max)))
613 (forward-line 1)))
614 (set-buffer standard-output)
e09d4033
RS
615 ;; Go back to top of *Occur* and finish off by printing the
616 ;; number of matching lines.
016c214f 617 (goto-char (point-min))
65b4665c 618 (let ((message-string
8d15583f 619 (if (= occur-num-matches 1)
65b4665c 620 "1 line"
8d15583f 621 (format "%d lines" occur-num-matches))))
65b4665c
RS
622 (insert message-string)
623 (if (interactive-p)
624 (message "%s matched" message-string)))))))))
698e1804 625\f
81bdc14d
RS
626;; It would be nice to use \\[...], but there is no reasonable way
627;; to make that display both SPC and Y.
698e1804
RS
628(defconst query-replace-help
629 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
be44f62c 630RET or `q' to exit, Period to replace one match and exit,
698e1804
RS
631Comma to replace but not move point immediately,
632C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
633C-w to delete match and recursive edit,
634C-l to clear the screen, redisplay, and offer same replacement again,
635! to replace all remaining matches with no more questions,
636^ to move point back to previous match."
637 "Help message while in query-replace")
638
81bdc14d
RS
639(defvar query-replace-map (make-sparse-keymap)
640 "Keymap that defines the responses to questions in `query-replace'.
641The \"bindings\" in this map are not commands; they are answers.
642The valid answers include `act', `skip', `act-and-show',
643`exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
d9121bc0 644`automatic', `backup', `exit-prefix', and `help'.")
81bdc14d
RS
645
646(define-key query-replace-map " " 'act)
647(define-key query-replace-map "\d" 'skip)
648(define-key query-replace-map [delete] 'skip)
9275e5e3 649(define-key query-replace-map [backspace] 'skip)
81bdc14d
RS
650(define-key query-replace-map "y" 'act)
651(define-key query-replace-map "n" 'skip)
633a305a
RS
652(define-key query-replace-map "Y" 'act)
653(define-key query-replace-map "N" 'skip)
81bdc14d 654(define-key query-replace-map "," 'act-and-show)
81bdc14d 655(define-key query-replace-map "q" 'exit)
919592c0 656(define-key query-replace-map "\r" 'exit)
384c7da4 657(define-key query-replace-map [return] 'exit)
81bdc14d
RS
658(define-key query-replace-map "." 'act-and-exit)
659(define-key query-replace-map "\C-r" 'edit)
660(define-key query-replace-map "\C-w" 'delete-and-edit)
661(define-key query-replace-map "\C-l" 'recenter)
662(define-key query-replace-map "!" 'automatic)
663(define-key query-replace-map "^" 'backup)
664(define-key query-replace-map "\C-h" 'help)
e731045a
KH
665(define-key query-replace-map [f1] 'help)
666(define-key query-replace-map [help] 'help)
81bdc14d 667(define-key query-replace-map "?" 'help)
bc6312e1
RS
668(define-key query-replace-map "\C-g" 'quit)
669(define-key query-replace-map "\C-]" 'quit)
d9121bc0
RS
670(define-key query-replace-map "\e" 'exit-prefix)
671(define-key query-replace-map [escape] 'exit-prefix)
81bdc14d 672
698e1804
RS
673(defun perform-replace (from-string replacements
674 query-flag regexp-flag delimited-flag
81bdc14d 675 &optional repeat-count map)
698e1804
RS
676 "Subroutine of `query-replace'. Its complexity handles interactive queries.
677Don't use this in your own program unless you want to query and set the mark
678just as `query-replace' does. Instead, write a simple loop like this:
679 (while (re-search-forward \"foo[ \t]+bar\" nil t)
680 (replace-match \"foobar\" nil nil))
e782e9f2 681which will run faster and probably do exactly what you want."
81bdc14d 682 (or map (setq map query-replace-map))
1c1dadab
RS
683 (and query-flag minibuffer-auto-raise
684 (raise-frame (window-frame (minibuffer-window))))
698e1804
RS
685 (let ((nocasify (not (and case-fold-search case-replace
686 (string-equal from-string
687 (downcase from-string)))))
688 (literal (not regexp-flag))
689 (search-function (if regexp-flag 're-search-forward 'search-forward))
690 (search-string from-string)
e5d77022 691 (real-match-data nil) ; the match data for the current match
698e1804
RS
692 (next-replacement nil)
693 (replacement-index 0)
694 (keep-going t)
695 (stack nil)
696 (next-rotate-count 0)
697 (replace-count 0)
5632eb27
PE
698 (nonempty-match nil)
699
7ef5c431
KH
700 ;; If non-nil, it is marker saying where in the buffer to stop.
701 (limit nil)
702
5632eb27
PE
703 ;; Data for the next match. If a cons, it has the same format as
704 ;; (match-data); otherwise it is t if a match is possible at point.
ae4eb03c 705 (match-again t)
5632eb27 706
02d95a27
RS
707 (message
708 (if query-flag
709 (substitute-command-keys
710 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
7ef5c431
KH
711
712 ;; If region is active, in Transient Mark mode, operate on region.
713 (if (and transient-mark-mode mark-active)
714 (progn
715 (setq limit (copy-marker (region-end)))
716 (goto-char (region-beginning))
717 (deactivate-mark)))
698e1804
RS
718 (if (stringp replacements)
719 (setq next-replacement replacements)
720 (or repeat-count (setq repeat-count 1)))
721 (if delimited-flag
722 (setq search-function 're-search-forward
723 search-string (concat "\\b"
724 (if regexp-flag from-string
725 (regexp-quote from-string))
726 "\\b")))
727 (push-mark)
728 (undo-boundary)
e782e9f2
RS
729 (unwind-protect
730 ;; Loop finding occurrences that perhaps should be replaced.
731 (while (and keep-going
732 (not (eobp))
5632eb27
PE
733 ;; Use the next match if it is already known;
734 ;; otherwise, search for a match after moving forward
735 ;; one char if progress is required.
736 (setq real-match-data
737 (if (consp match-again)
738 (progn (goto-char (nth 1 match-again))
739 match-again)
740 (and (or match-again
741 (progn
742 (forward-char 1)
743 (not (eobp))))
7ef5c431 744 (funcall search-function search-string limit t)
5632eb27
PE
745 ;; For speed, use only integers and
746 ;; reuse the list used last time.
747 (match-data t real-match-data)))))
748
749 ;; Record whether the match is nonempty, to avoid an infinite loop
750 ;; repeatedly matching the same empty string.
751 (setq nonempty-match
752 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
753
754 ;; If the match is empty, record that the next one can't be adjacent.
755 ;; Otherwise, if matching a regular expression, do the next
756 ;; match now, since the replacement for this match may
757 ;; affect whether the next match is adjacent to this one.
758 (setq match-again
759 (and nonempty-match
760 (or (not regexp-flag)
761 (and (looking-at search-string)
937ab68f 762 (match-data)))))
5632eb27 763
e782e9f2
RS
764 ;; If time for a change, advance to next replacement string.
765 (if (and (listp replacements)
766 (= next-rotate-count replace-count))
767 (progn
768 (setq next-rotate-count
769 (+ next-rotate-count repeat-count))
770 (setq next-replacement (nth replacement-index replacements))
771 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
772 (if (not query-flag)
773 (progn
ef4aaf5f 774 (set-match-data real-match-data)
e782e9f2
RS
775 (replace-match next-replacement nocasify literal)
776 (setq replace-count (1+ replace-count)))
777 (undo-boundary)
778 (let (done replaced key def)
779 ;; Loop reading commands until one of them sets done,
780 ;; which means it has finished handling this occurrence.
781 (while (not done)
ef4aaf5f 782 (set-match-data real-match-data)
e782e9f2 783 (replace-highlight (match-beginning 0) (match-end 0))
c006b215
KH
784 ;; Bind message-log-max so we don't fill up the message log
785 ;; with a bunch of identical messages.
786 (let ((message-log-max nil))
787 (message message from-string next-replacement))
e782e9f2 788 (setq key (read-event))
f5e52cd3
RS
789 ;; Necessary in case something happens during read-event
790 ;; that clobbers the match data.
ef4aaf5f 791 (set-match-data real-match-data)
e782e9f2
RS
792 (setq key (vector key))
793 (setq def (lookup-key map key))
794 ;; Restore the match data while we process the command.
e782e9f2
RS
795 (cond ((eq def 'help)
796 (with-output-to-temp-buffer "*Help*"
797 (princ
798 (concat "Query replacing "
799 (if regexp-flag "regexp " "")
800 from-string " with "
801 next-replacement ".\n\n"
802 (substitute-command-keys
b905ac33
KH
803 query-replace-help)))
804 (save-excursion
805 (set-buffer standard-output)
806 (help-mode))))
e782e9f2
RS
807 ((eq def 'exit)
808 (setq keep-going nil)
809 (setq done t))
810 ((eq def 'backup)
237e6ab0
KH
811 (if stack
812 (let ((elt (car stack)))
813 (goto-char (car elt))
814 (setq replaced (eq t (cdr elt)))
815 (or replaced
ef4aaf5f 816 (set-match-data (cdr elt)))
237e6ab0
KH
817 (setq stack (cdr stack)))
818 (message "No previous match")
819 (ding 'no-terminate)
820 (sit-for 1)))
e782e9f2
RS
821 ((eq def 'act)
822 (or replaced
3043b0b4
RS
823 (progn
824 (replace-match next-replacement nocasify literal)
825 (setq replace-count (1+ replace-count))))
e782e9f2
RS
826 (setq done t replaced t))
827 ((eq def 'act-and-exit)
828 (or replaced
3043b0b4
RS
829 (progn
830 (replace-match next-replacement nocasify literal)
831 (setq replace-count (1+ replace-count))))
e782e9f2
RS
832 (setq keep-going nil)
833 (setq done t replaced t))
834 ((eq def 'act-and-show)
835 (if (not replaced)
836 (progn
837 (replace-match next-replacement nocasify literal)
3043b0b4 838 (setq replace-count (1+ replace-count))
e782e9f2
RS
839 (setq replaced t))))
840 ((eq def 'automatic)
841 (or replaced
3043b0b4
RS
842 (progn
843 (replace-match next-replacement nocasify literal)
844 (setq replace-count (1+ replace-count))))
e782e9f2
RS
845 (setq done t query-flag nil replaced t))
846 ((eq def 'skip)
847 (setq done t))
848 ((eq def 'recenter)
849 (recenter nil))
850 ((eq def 'edit)
a9c4c78a
RS
851 (goto-char (match-beginning 0))
852 (funcall search-function search-string limit t)
853 (setq real-match-data (match-data))
854 (save-excursion (recursive-edit))
855 (set-match-data real-match-data)
ae4eb03c
RS
856 ;; Before we make the replacement,
857 ;; decide whether the search string
858 ;; can match again just after this match.
5632eb27
PE
859 (if (and regexp-flag nonempty-match)
860 (setq match-again (and (looking-at search-string)
937ab68f 861 (match-data)))))
e782e9f2
RS
862 ((eq def 'delete-and-edit)
863 (delete-region (match-beginning 0) (match-end 0))
ef4aaf5f 864 (set-match-data
e782e9f2
RS
865 (prog1 (match-data)
866 (save-excursion (recursive-edit))))
867 (setq replaced t))
d9121bc0
RS
868 ;; Note: we do not need to treat `exit-prefix'
869 ;; specially here, since we reread
870 ;; any unrecognized character.
e782e9f2 871 (t
d9121bc0 872 (setq this-command 'mode-exited)
e782e9f2
RS
873 (setq keep-going nil)
874 (setq unread-command-events
875 (append (listify-key-sequence key)
876 unread-command-events))
877 (setq done t))))
878 ;; Record previous position for ^ when we move on.
879 ;; Change markers to numbers in the match data
880 ;; since lots of markers slow down editing.
881 (setq stack
882 (cons (cons (point)
141aa68c 883 (or replaced (match-data t)))
5632eb27 884 stack)))))
e782e9f2 885 (replace-dehighlight))
4d33492a
RS
886 (or unread-command-events
887 (message "Replaced %d occurrence%s"
888 replace-count
889 (if (= replace-count 1) "" "s")))
890 (and keep-going stack)))
698e1804 891
95807e68 892(defcustom query-replace-highlight t
9d325ebf
RS
893 "*Non-nil means to highlight words during query replacement."
894 :type 'boolean
895 :group 'matching)
e782e9f2
RS
896
897(defvar replace-overlay nil)
898
899(defun replace-dehighlight ()
900 (and replace-overlay
901 (progn
902 (delete-overlay replace-overlay)
903 (setq replace-overlay nil))))
904
905(defun replace-highlight (start end)
906 (and query-replace-highlight
907 (progn
908 (or replace-overlay
909 (progn
910 (setq replace-overlay (make-overlay start end))
911 (overlay-put replace-overlay 'face
912 (if (internal-find-face 'query-replace)
913 'query-replace 'region))))
914 (move-overlay replace-overlay start end (current-buffer)))))
915
c88ab9ce 916;;; replace.el ends here