(mail-passwd-command): New variable.
[bpt/emacs.git] / lisp / replace.el
CommitLineData
c88ab9ce
ER
1;;; replace.el --- replace commands for Emacs.
2
016c214f 3;; Copyright (C) 1985, 1986, 1987, 1992, 1994, 1996 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
1781e021 29(defvar case-replace t "\
73fa8346 30*Non-nil means query-replace should preserve case in replacements.")
77176e73 31
770970cb
RS
32(defvar query-replace-history nil)
33
151270f3
RS
34(defvar query-replace-interactive nil
35 "Non-nil means `query-replace' uses the last search string.
36That becomes the \"string to replace\".")
37
38(defun query-replace-read-args (string regexp-flag)
770970cb 39 (let (from to)
151270f3
RS
40 (if query-replace-interactive
41 (setq from (car (if regexp-flag regexp-search-ring search-ring)))
42 (setq from (read-from-minibuffer (format "%s: " string)
43 nil nil nil
44 'query-replace-history)))
770970cb
RS
45 (setq to (read-from-minibuffer (format "%s %s with: " string from)
46 nil nil nil
47 'query-replace-history))
48 (list from to current-prefix-arg)))
49
da44e784
RM
50(defun query-replace (from-string to-string &optional arg)
51 "Replace some occurrences of FROM-STRING with TO-STRING.
52As each match is found, the user must type a character saying
53what to do with it. For directions, type \\[help-command] at that time.
54
151270f3
RS
55If `query-replace-interactive' is non-nil, the last incremental search
56string is used as FROM-STRING--you don't have to specify it with the
57minibuffer.
58
118a01c9 59Preserves case in each replacement if `case-replace' and `case-fold-search'
da44e784 60are non-nil and FROM-STRING has no uppercase letters.
9b0bf2b6
RS
61\(Preserving case means that if the string matched is all caps, or capitalized,
62then its replacement is upcased or capitalized.)
63
118a01c9 64Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
81bdc14d
RS
65only matches surrounded by word boundaries.
66
67To customize possible responses, change the \"bindings\" in `query-replace-map'."
151270f3 68 (interactive (query-replace-read-args "Query replace" nil))
4d33492a 69 (perform-replace from-string to-string t nil arg))
73fa8346 70(define-key esc-map "%" 'query-replace)
da44e784 71
da44e784
RM
72(defun query-replace-regexp (regexp to-string &optional arg)
73 "Replace some things after point matching REGEXP with TO-STRING.
74As each match is found, the user must type a character saying
75what to do with it. For directions, type \\[help-command] at that time.
76
151270f3
RS
77If `query-replace-interactive' is non-nil, the last incremental search
78regexp is used as REGEXP--you don't have to specify it with the
79minibuffer.
80
118a01c9 81Preserves case in each replacement if `case-replace' and `case-fold-search'
da44e784 82are non-nil and REGEXP has no uppercase letters.
118a01c9 83Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
da44e784 84only matches surrounded by word boundaries.
118a01c9
RS
85In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
86and `\\=\\N' (where N is a digit) stands for
87 whatever what matched the Nth `\\(...\\)' in REGEXP."
151270f3 88 (interactive (query-replace-read-args "Query replace regexp" t))
4d33492a 89 (perform-replace regexp to-string t t arg))
da44e784 90
da44e784
RM
91(defun map-query-replace-regexp (regexp to-strings &optional arg)
92 "Replace some matches for REGEXP with various strings, in rotation.
93The second argument TO-STRINGS contains the replacement strings, separated
94by spaces. This command works like `query-replace-regexp' except
95that each successive replacement uses the next successive replacement string,
96wrapping around from the last such string to the first.
97
98Non-interactively, TO-STRINGS may be a list of replacement strings.
99
151270f3
RS
100If `query-replace-interactive' is non-nil, the last incremental search
101regexp is used as REGEXP--you don't have to specify it with the minibuffer.
102
da44e784
RM
103A prefix argument N says to use each replacement string N times
104before rotating to the next."
770970cb
RS
105 (interactive
106 (let (from to)
151270f3
RS
107 (setq from (if query-replace-interactive
108 (car regexp-search-ring)
109 (read-from-minibuffer "Map query replace (regexp): "
110 nil nil nil
111 'query-replace-history)))
770970cb
RS
112 (setq to (read-from-minibuffer
113 (format "Query replace %s with (space-separated strings): "
114 from)
115 nil nil nil
116 'query-replace-history))
117 (list from to current-prefix-arg)))
da44e784
RM
118 (let (replacements)
119 (if (listp to-strings)
120 (setq replacements to-strings)
121 (while (/= (length to-strings) 0)
122 (if (string-match " " to-strings)
123 (setq replacements
124 (append replacements
125 (list (substring to-strings 0
126 (string-match " " to-strings))))
127 to-strings (substring to-strings
128 (1+ (string-match " " to-strings))))
129 (setq replacements (append replacements (list to-strings))
130 to-strings ""))))
4d33492a 131 (perform-replace regexp replacements t t nil arg)))
da44e784 132
da44e784
RM
133(defun replace-string (from-string to-string &optional delimited)
134 "Replace occurrences of FROM-STRING with TO-STRING.
135Preserve case in each match if `case-replace' and `case-fold-search'
136are non-nil and FROM-STRING has no uppercase letters.
9b0bf2b6
RS
137\(Preserving case means that if the string matched is all caps, or capitalized,
138then its replacement is upcased or capitalized.)
139
118a01c9 140Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
da44e784
RM
141only matches surrounded by word boundaries.
142
151270f3
RS
143If `query-replace-interactive' is non-nil, the last incremental search
144string is used as FROM-STRING--you don't have to specify it with the
145minibuffer.
146
da44e784
RM
147This function is usually the wrong thing to use in a Lisp program.
148What you probably want is a loop like this:
118a01c9
RS
149 (while (search-forward FROM-STRING nil t)
150 (replace-match TO-STRING nil t))
da44e784 151which will run faster and will not set the mark or print anything."
151270f3 152 (interactive (query-replace-read-args "Replace string" nil))
4d33492a 153 (perform-replace from-string to-string nil nil delimited))
da44e784 154
da44e784
RM
155(defun replace-regexp (regexp to-string &optional delimited)
156 "Replace things after point matching REGEXP with TO-STRING.
118a01c9 157Preserve case in each match if `case-replace' and `case-fold-search'
da44e784 158are non-nil and REGEXP has no uppercase letters.
118a01c9 159Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
da44e784 160only matches surrounded by word boundaries.
118a01c9
RS
161In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
162and `\\=\\N' (where N is a digit) stands for
880f22a1 163 whatever what matched the Nth `\\(...\\)' in REGEXP.
da44e784 164
151270f3
RS
165If `query-replace-interactive' is non-nil, the last incremental search
166regexp is used as REGEXP--you don't have to specify it with the minibuffer.
167
da44e784
RM
168This function is usually the wrong thing to use in a Lisp program.
169What you probably want is a loop like this:
170 (while (re-search-forward REGEXP nil t)
118a01c9 171 (replace-match TO-STRING nil nil))
da44e784 172which will run faster and will not set the mark or print anything."
151270f3 173 (interactive (query-replace-read-args "Replace regexp" t))
4d33492a 174 (perform-replace regexp to-string nil t delimited))
4c53bd2b
RS
175\f
176(defvar regexp-history nil
177 "History list for some commands that read regular expressions.")
da44e784 178
31e1d920 179(defalias 'delete-non-matching-lines 'keep-lines)
698e1804
RS
180(defun keep-lines (regexp)
181 "Delete all lines except those containing matches for REGEXP.
182A match split across lines preserves all the lines it lies in.
183Applies to all lines after point."
4c53bd2b 184 (interactive (list (read-from-minibuffer
72f21cdf 185 "Keep lines (containing match for regexp): "
4c53bd2b 186 nil nil nil 'regexp-history)))
698e1804
RS
187 (save-excursion
188 (or (bolp) (forward-line 1))
189 (let ((start (point)))
190 (while (not (eobp))
191 ;; Start is first char not preserved by previous match.
192 (if (not (re-search-forward regexp nil 'move))
193 (delete-region start (point-max))
194 (let ((end (save-excursion (goto-char (match-beginning 0))
195 (beginning-of-line)
196 (point))))
197 ;; Now end is first char preserved by the new match.
198 (if (< start end)
199 (delete-region start end))))
200 (setq start (save-excursion (forward-line 1)
201 (point)))
202 ;; If the match was empty, avoid matching again at same place.
203 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
204 (forward-char 1))))))
205
31e1d920 206(defalias 'delete-matching-lines 'flush-lines)
698e1804
RS
207(defun flush-lines (regexp)
208 "Delete lines containing matches for REGEXP.
209If a match is split across lines, all the lines it lies in are deleted.
210Applies to lines after point."
4c53bd2b 211 (interactive (list (read-from-minibuffer
72f21cdf 212 "Flush lines (containing match for regexp): "
4c53bd2b 213 nil nil nil 'regexp-history)))
698e1804
RS
214 (save-excursion
215 (while (and (not (eobp))
216 (re-search-forward regexp nil t))
217 (delete-region (save-excursion (goto-char (match-beginning 0))
218 (beginning-of-line)
219 (point))
220 (progn (forward-line 1) (point))))))
221
31e1d920 222(defalias 'count-matches 'how-many)
698e1804
RS
223(defun how-many (regexp)
224 "Print number of matches for REGEXP following point."
4c53bd2b 225 (interactive (list (read-from-minibuffer
72f21cdf 226 "How many matches for (regexp): "
4c53bd2b 227 nil nil nil 'regexp-history)))
698e1804
RS
228 (let ((count 0) opoint)
229 (save-excursion
230 (while (and (not (eobp))
231 (progn (setq opoint (point))
232 (re-search-forward regexp nil t)))
233 (if (= opoint (point))
234 (forward-char 1)
235 (setq count (1+ count))))
236 (message "%d occurrences" count))))
4c53bd2b 237\f
698e1804
RS
238(defvar occur-mode-map ())
239(if occur-mode-map
240 ()
241 (setq occur-mode-map (make-sparse-keymap))
78bead73 242 (define-key occur-mode-map [mouse-2] 'occur-mode-mouse-goto)
0081c8a1 243 (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence)
a41284da
RS
244 (define-key occur-mode-map "\C-m" 'occur-mode-goto-occurrence)
245 (define-key occur-mode-map "g" 'revert-buffer))
698e1804
RS
246
247(defvar occur-buffer nil)
248(defvar occur-nlines nil)
249(defvar occur-pos-list nil)
a41284da
RS
250(defvar occur-command-arguments nil
251 "Arguments that were given to `occur' when it made this buffer.")
698e1804
RS
252
253(defun occur-mode ()
254 "Major mode for output from \\[occur].
0081c8a1
RS
255\\<occur-mode-map>Move point to one of the items in this buffer, then use
256\\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
257Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
258
698e1804
RS
259\\{occur-mode-map}"
260 (kill-all-local-variables)
261 (use-local-map occur-mode-map)
262 (setq major-mode 'occur-mode)
263 (setq mode-name "Occur")
a41284da
RS
264 (make-local-variable 'revert-buffer-function)
265 (setq revert-buffer-function 'occur-revert-function)
698e1804
RS
266 (make-local-variable 'occur-buffer)
267 (make-local-variable 'occur-nlines)
4baf5620 268 (make-local-variable 'occur-pos-list)
a41284da 269 (make-local-variable 'occur-command-arguments)
4baf5620 270 (run-hooks 'occur-mode-hook))
698e1804 271
a41284da
RS
272;; Handle revert-buffer for *Occur* buffers.
273(defun occur-revert-function (ignore1 ignore2)
274 (let ((args occur-command-arguments ))
275 (save-excursion
276 (set-buffer occur-buffer)
277 (apply 'occur args))))
278
78bead73
RS
279(defun occur-mode-mouse-goto (event)
280 "In Occur mode, go to the occurrence whose line you click on."
281 (interactive "e")
282 (let (buffer pos)
283 (save-excursion
284 (set-buffer (window-buffer (posn-window (event-end event))))
285 (save-excursion
286 (goto-char (posn-point (event-end event)))
287 (setq pos (occur-mode-find-occurrence))
288 (setq buffer occur-buffer)))
289 (pop-to-buffer buffer)
290 (goto-char (marker-position pos))))
291
292(defun occur-mode-find-occurrence ()
698e1804
RS
293 (if (or (null occur-buffer)
294 (null (buffer-name occur-buffer)))
295 (progn
296 (setq occur-buffer nil
297 occur-pos-list nil)
298 (error "Buffer in which occurrences were found is deleted")))
78bead73
RS
299 (let* ((line-count
300 (count-lines (point-min)
301 (save-excursion
302 (beginning-of-line)
303 (point))))
304 (occur-number (save-excursion
698e1804 305 (beginning-of-line)
78bead73 306 (/ (1- line-count)
698e1804
RS
307 (cond ((< occur-nlines 0)
308 (- 2 occur-nlines))
309 ((> occur-nlines 0)
310 (+ 2 (* 2 occur-nlines)))
311 (t 1)))))
312 (pos (nth occur-number occur-pos-list)))
78bead73
RS
313 (if (< line-count 1)
314 (error "No occurrence on this line"))
43549f18
RS
315 (or pos
316 (error "No occurrence on this line"))
78bead73
RS
317 pos))
318
319(defun occur-mode-goto-occurrence ()
320 "Go to the occurrence the current line describes."
321 (interactive)
322 (let ((pos (occur-mode-find-occurrence)))
698e1804 323 (pop-to-buffer occur-buffer)
121e2227 324 (goto-char (marker-position pos))))
4c53bd2b 325\f
698e1804 326(defvar list-matching-lines-default-context-lines 0
da44e784 327 "*Default number of context lines to include around a `list-matching-lines'
698e1804
RS
328match. A negative number means to include that many lines before the match.
329A positive number means to include that many lines both before and after.")
330
31e1d920 331(defalias 'list-matching-lines 'occur)
698e1804 332
c9daced0
RS
333(defvar list-matching-lines-face 'bold
334 "*Face used by M-x list-matching-lines to show the text that matches.
335If the value is nil, don't highlight the matching portions specially.")
336
698e1804 337(defun occur (regexp &optional nlines)
99976f85 338 "Show all lines in the current buffer containing a match for REGEXP.
da44e784
RM
339
340If a match spreads across multiple lines, all those lines are shown.
698e1804 341
da44e784
RM
342Each line is displayed with NLINES lines before and after, or -NLINES
343before if NLINES is negative.
344NLINES defaults to `list-matching-lines-default-context-lines'.
698e1804
RS
345Interactively it is the prefix arg.
346
4c53bd2b 347The lines are shown in a buffer named `*Occur*'.
698e1804
RS
348It serves as a menu to find any of the occurrences in this buffer.
349\\[describe-mode] in that buffer will explain how."
a5dfed3e
RS
350 (interactive
351 (list (let* ((default (car regexp-history))
352 (input
353 (read-from-minibuffer
354 (if default
355 (format "List lines matching regexp (default `%s'): "
356 default)
357 "List lines matching regexp: ")
358 nil nil nil 'regexp-history)))
359 (if (string-equal input "")
360 default
361 (set-text-properties 0 (length input) nil input)
362 input))
363 current-prefix-arg))
364 (let ((nlines (if nlines
365 (prefix-numeric-value nlines)
366 list-matching-lines-default-context-lines))
367 (first t)
698e1804 368 (buffer (current-buffer))
bdd610b2 369 (dir default-directory)
698e1804 370 (linenum 1)
79c2e52b
JB
371 (prevpos (point-min))
372 (final-context-start (make-marker)))
99976f85
RS
373;;; (save-excursion
374;;; (beginning-of-line)
375;;; (setq linenum (1+ (count-lines (point-min) (point))))
376;;; (setq prevpos (point)))
016c214f
RS
377 (save-excursion
378 (goto-char (point-min))
379 ;; Check first whether there are any matches at all.
380 (if (not (re-search-forward regexp nil t))
381 (message "No matches for `%s'" regexp)
382 ;; Back up, so the search loop below will find the first match.
383 (goto-char (match-beginning 0))
384 (with-output-to-temp-buffer "*Occur*"
385 (save-excursion
386 (set-buffer standard-output)
387 (setq default-directory dir)
388 ;; We will insert the number of lines, and "lines", later.
389 (insert " matching ")
390 (let ((print-escape-newlines t))
391 (prin1 regexp))
392 (insert " in buffer " (buffer-name buffer) ?. ?\n)
393 (occur-mode)
394 (setq occur-buffer buffer)
395 (setq occur-nlines nlines)
a41284da
RS
396 (setq occur-pos-list ())
397 (setq occur-command-arguments
398 (list regexp nlines)))
016c214f 399 (if (eq buffer standard-output)
91c6bdc0 400 (goto-char (point-max)))
016c214f
RS
401 (save-excursion
402 ;; Find next match, but give up if prev match was at end of buffer.
403 (while (and (not (= prevpos (point-max)))
404 (re-search-forward regexp nil t))
405 (goto-char (match-beginning 0))
406 (beginning-of-line)
407 (save-match-data
408 (setq linenum (+ linenum (count-lines prevpos (point)))))
409 (setq prevpos (point))
410 (goto-char (match-end 0))
411 (let* ((start (save-excursion
412 (goto-char (match-beginning 0))
413 (forward-line (if (< nlines 0) nlines (- nlines)))
414 (point)))
415 (end (save-excursion
416 (goto-char (match-end 0))
417 (if (> nlines 0)
418 (forward-line (1+ nlines))
419 (forward-line 1))
420 (point)))
c9daced0
RS
421 ;; Record where the actual match
422 (match-offset
423 (save-excursion
424 (goto-char (match-beginning 0))
425 (beginning-of-line)
426 ;; +6 to skip over line number
427 (+ 6 (- (match-beginning 0) (point)))))
428 (match-len (- (match-end 0) (match-beginning 0)))
016c214f
RS
429 (tag (format "%5d" linenum))
430 (empty (make-string (length tag) ?\ ))
431 tem)
432 (save-excursion
433 (setq tem (make-marker))
434 (set-marker tem (point))
435 (set-buffer standard-output)
436 (setq occur-pos-list (cons tem occur-pos-list))
437 (or first (zerop nlines)
438 (insert "--------\n"))
439 (setq first nil)
440 (insert-buffer-substring buffer start end)
441 (set-marker final-context-start
442 (- (point) (- end (match-end 0))))
742d416f 443 (goto-char (- (point) (- end start)))
016c214f
RS
444 (setq tem nlines)
445 (while (> tem 0)
446 (insert empty ?:)
447 (forward-line 1)
448 (setq tem (1- tem)))
81fa866c
EN
449 (let ((this-linenum linenum)
450 line-start)
016c214f
RS
451 (while (< (point) final-context-start)
452 (if (null tag)
453 (setq tag (format "%5d" this-linenum)))
454 (insert tag ?:)
c9daced0
RS
455 (setq line-start
456 (save-excursion
457 (beginning-of-line)
458 (point)))
459 (put-text-property line-start
016c214f
RS
460 (save-excursion
461 (end-of-line)
462 (point))
463 'mouse-face 'highlight)
c9daced0
RS
464 (if list-matching-lines-face
465 (put-text-property
466 (+ line-start match-offset)
467 (+ line-start match-offset match-len)
468 'face list-matching-lines-face))
016c214f
RS
469 (forward-line 1)
470 (setq tag nil)
471 (setq this-linenum (1+ this-linenum)))
472 (while (<= (point) final-context-start)
473 (insert empty ?:)
474 (forward-line 1)
475 (setq this-linenum (1+ this-linenum))))
476 (while (< tem nlines)
477 (insert empty ?:)
478 (forward-line 1)
479 (setq tem (1+ tem)))
480 (goto-char (point-max)))
481 (forward-line 1)))
482 (set-buffer standard-output)
483 ;; Put positions in increasing order to go with buffer.
484 (setq occur-pos-list (nreverse occur-pos-list))
485 (goto-char (point-min))
65b4665c
RS
486 (let ((message-string
487 (if (= (length occur-pos-list) 1)
488 "1 line"
489 (format "%d lines" (length occur-pos-list)))))
490 (insert message-string)
491 (if (interactive-p)
492 (message "%s matched" message-string)))))))))
698e1804 493\f
81bdc14d
RS
494;; It would be nice to use \\[...], but there is no reasonable way
495;; to make that display both SPC and Y.
698e1804
RS
496(defconst query-replace-help
497 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
be44f62c 498RET or `q' to exit, Period to replace one match and exit,
698e1804
RS
499Comma to replace but not move point immediately,
500C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
501C-w to delete match and recursive edit,
502C-l to clear the screen, redisplay, and offer same replacement again,
503! to replace all remaining matches with no more questions,
504^ to move point back to previous match."
505 "Help message while in query-replace")
506
81bdc14d
RS
507(defvar query-replace-map (make-sparse-keymap)
508 "Keymap that defines the responses to questions in `query-replace'.
509The \"bindings\" in this map are not commands; they are answers.
510The valid answers include `act', `skip', `act-and-show',
511`exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
d9121bc0 512`automatic', `backup', `exit-prefix', and `help'.")
81bdc14d
RS
513
514(define-key query-replace-map " " 'act)
515(define-key query-replace-map "\d" 'skip)
516(define-key query-replace-map [delete] 'skip)
9275e5e3 517(define-key query-replace-map [backspace] 'skip)
81bdc14d
RS
518(define-key query-replace-map "y" 'act)
519(define-key query-replace-map "n" 'skip)
633a305a
RS
520(define-key query-replace-map "Y" 'act)
521(define-key query-replace-map "N" 'skip)
81bdc14d 522(define-key query-replace-map "," 'act-and-show)
81bdc14d 523(define-key query-replace-map "q" 'exit)
919592c0 524(define-key query-replace-map "\r" 'exit)
384c7da4 525(define-key query-replace-map [return] 'exit)
81bdc14d
RS
526(define-key query-replace-map "." 'act-and-exit)
527(define-key query-replace-map "\C-r" 'edit)
528(define-key query-replace-map "\C-w" 'delete-and-edit)
529(define-key query-replace-map "\C-l" 'recenter)
530(define-key query-replace-map "!" 'automatic)
531(define-key query-replace-map "^" 'backup)
532(define-key query-replace-map "\C-h" 'help)
e731045a
KH
533(define-key query-replace-map [f1] 'help)
534(define-key query-replace-map [help] 'help)
81bdc14d 535(define-key query-replace-map "?" 'help)
bc6312e1
RS
536(define-key query-replace-map "\C-g" 'quit)
537(define-key query-replace-map "\C-]" 'quit)
d9121bc0
RS
538(define-key query-replace-map "\e" 'exit-prefix)
539(define-key query-replace-map [escape] 'exit-prefix)
81bdc14d 540
698e1804
RS
541(defun perform-replace (from-string replacements
542 query-flag regexp-flag delimited-flag
81bdc14d 543 &optional repeat-count map)
698e1804
RS
544 "Subroutine of `query-replace'. Its complexity handles interactive queries.
545Don't use this in your own program unless you want to query and set the mark
546just as `query-replace' does. Instead, write a simple loop like this:
547 (while (re-search-forward \"foo[ \t]+bar\" nil t)
548 (replace-match \"foobar\" nil nil))
e782e9f2 549which will run faster and probably do exactly what you want."
81bdc14d 550 (or map (setq map query-replace-map))
1c1dadab
RS
551 (and query-flag minibuffer-auto-raise
552 (raise-frame (window-frame (minibuffer-window))))
698e1804
RS
553 (let ((nocasify (not (and case-fold-search case-replace
554 (string-equal from-string
555 (downcase from-string)))))
556 (literal (not regexp-flag))
557 (search-function (if regexp-flag 're-search-forward 'search-forward))
558 (search-string from-string)
e5d77022 559 (real-match-data nil) ; the match data for the current match
698e1804
RS
560 (next-replacement nil)
561 (replacement-index 0)
562 (keep-going t)
563 (stack nil)
564 (next-rotate-count 0)
565 (replace-count 0)
da44e784 566 (lastrepl nil) ;Position after last match considered.
ae4eb03c 567 (match-again t)
02d95a27
RS
568 (message
569 (if query-flag
570 (substitute-command-keys
571 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
698e1804
RS
572 (if (stringp replacements)
573 (setq next-replacement replacements)
574 (or repeat-count (setq repeat-count 1)))
575 (if delimited-flag
576 (setq search-function 're-search-forward
577 search-string (concat "\\b"
578 (if regexp-flag from-string
579 (regexp-quote from-string))
580 "\\b")))
581 (push-mark)
582 (undo-boundary)
e782e9f2
RS
583 (unwind-protect
584 ;; Loop finding occurrences that perhaps should be replaced.
585 (while (and keep-going
586 (not (eobp))
587 (funcall search-function search-string nil t)
588 ;; If the search string matches immediately after
589 ;; the previous match, but it did not match there
590 ;; before the replacement was done, ignore the match.
591 (if (or (eq lastrepl (point))
592 (and regexp-flag
593 (eq lastrepl (match-beginning 0))
ae4eb03c 594 (not match-again)))
e782e9f2
RS
595 (if (eobp)
596 nil
597 ;; Don't replace the null string
598 ;; right after end of previous replacement.
599 (forward-char 1)
600 (funcall search-function search-string nil t))
601 t))
602
ae4eb03c
RS
603 ;; Save the data associated with the real match.
604 ;; For speed, use only integers and reuse the list used last time.
605 (setq real-match-data (match-data t real-match-data))
606
607 ;; Before we make the replacement, decide whether the search string
608 ;; can match again just after this match.
609 (if regexp-flag
610 (setq match-again (looking-at search-string)))
e782e9f2
RS
611 ;; If time for a change, advance to next replacement string.
612 (if (and (listp replacements)
613 (= next-rotate-count replace-count))
614 (progn
615 (setq next-rotate-count
616 (+ next-rotate-count repeat-count))
617 (setq next-replacement (nth replacement-index replacements))
618 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
619 (if (not query-flag)
620 (progn
ae4eb03c 621 (store-match-data real-match-data)
e782e9f2
RS
622 (replace-match next-replacement nocasify literal)
623 (setq replace-count (1+ replace-count)))
624 (undo-boundary)
625 (let (done replaced key def)
626 ;; Loop reading commands until one of them sets done,
627 ;; which means it has finished handling this occurrence.
628 (while (not done)
301a9d17 629 (store-match-data real-match-data)
e782e9f2 630 (replace-highlight (match-beginning 0) (match-end 0))
c006b215
KH
631 ;; Bind message-log-max so we don't fill up the message log
632 ;; with a bunch of identical messages.
633 (let ((message-log-max nil))
634 (message message from-string next-replacement))
e782e9f2
RS
635 (setq key (read-event))
636 (setq key (vector key))
637 (setq def (lookup-key map key))
638 ;; Restore the match data while we process the command.
e782e9f2
RS
639 (cond ((eq def 'help)
640 (with-output-to-temp-buffer "*Help*"
641 (princ
642 (concat "Query replacing "
643 (if regexp-flag "regexp " "")
644 from-string " with "
645 next-replacement ".\n\n"
646 (substitute-command-keys
b905ac33
KH
647 query-replace-help)))
648 (save-excursion
649 (set-buffer standard-output)
650 (help-mode))))
e782e9f2
RS
651 ((eq def 'exit)
652 (setq keep-going nil)
653 (setq done t))
654 ((eq def 'backup)
237e6ab0
KH
655 (if stack
656 (let ((elt (car stack)))
657 (goto-char (car elt))
658 (setq replaced (eq t (cdr elt)))
659 (or replaced
660 (store-match-data (cdr elt)))
661 (setq stack (cdr stack)))
662 (message "No previous match")
663 (ding 'no-terminate)
664 (sit-for 1)))
e782e9f2
RS
665 ((eq def 'act)
666 (or replaced
3043b0b4
RS
667 (progn
668 (replace-match next-replacement nocasify literal)
669 (setq replace-count (1+ replace-count))))
e782e9f2
RS
670 (setq done t replaced t))
671 ((eq def 'act-and-exit)
672 (or replaced
3043b0b4
RS
673 (progn
674 (replace-match next-replacement nocasify literal)
675 (setq replace-count (1+ replace-count))))
e782e9f2
RS
676 (setq keep-going nil)
677 (setq done t replaced t))
678 ((eq def 'act-and-show)
679 (if (not replaced)
680 (progn
681 (replace-match next-replacement nocasify literal)
3043b0b4 682 (setq replace-count (1+ replace-count))
e782e9f2
RS
683 (setq replaced t))))
684 ((eq def 'automatic)
685 (or replaced
3043b0b4
RS
686 (progn
687 (replace-match next-replacement nocasify literal)
688 (setq replace-count (1+ replace-count))))
e782e9f2
RS
689 (setq done t query-flag nil replaced t))
690 ((eq def 'skip)
691 (setq done t))
692 ((eq def 'recenter)
693 (recenter nil))
694 ((eq def 'edit)
695 (store-match-data
696 (prog1 (match-data)
ae4eb03c
RS
697 (save-excursion (recursive-edit))))
698 ;; Before we make the replacement,
699 ;; decide whether the search string
700 ;; can match again just after this match.
701 (if regexp-flag
702 (setq match-again (looking-at search-string))))
e782e9f2
RS
703 ((eq def 'delete-and-edit)
704 (delete-region (match-beginning 0) (match-end 0))
705 (store-match-data
706 (prog1 (match-data)
707 (save-excursion (recursive-edit))))
708 (setq replaced t))
d9121bc0
RS
709 ;; Note: we do not need to treat `exit-prefix'
710 ;; specially here, since we reread
711 ;; any unrecognized character.
e782e9f2 712 (t
d9121bc0 713 (setq this-command 'mode-exited)
e782e9f2
RS
714 (setq keep-going nil)
715 (setq unread-command-events
716 (append (listify-key-sequence key)
717 unread-command-events))
718 (setq done t))))
719 ;; Record previous position for ^ when we move on.
720 ;; Change markers to numbers in the match data
721 ;; since lots of markers slow down editing.
722 (setq stack
723 (cons (cons (point)
141aa68c 724 (or replaced (match-data t)))
3043b0b4 725 stack))))
e782e9f2
RS
726 (setq lastrepl (point)))
727 (replace-dehighlight))
4d33492a
RS
728 (or unread-command-events
729 (message "Replaced %d occurrence%s"
730 replace-count
731 (if (= replace-count 1) "" "s")))
732 (and keep-going stack)))
698e1804 733
e782e9f2
RS
734(defvar query-replace-highlight nil
735 "*Non-nil means to highlight words during query replacement.")
736
737(defvar replace-overlay nil)
738
739(defun replace-dehighlight ()
740 (and replace-overlay
741 (progn
742 (delete-overlay replace-overlay)
743 (setq replace-overlay nil))))
744
745(defun replace-highlight (start end)
746 (and query-replace-highlight
747 (progn
748 (or replace-overlay
749 (progn
750 (setq replace-overlay (make-overlay start end))
751 (overlay-put replace-overlay 'face
752 (if (internal-find-face 'query-replace)
753 'query-replace 'region))))
754 (move-overlay replace-overlay start end (current-buffer)))))
755
c88ab9ce 756;;; replace.el ends here