(concat): Take modulus of thisindex before shifting.
[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)
cffe0c02 244 (define-key occur-mode-map "\C-m" 'occur-mode-goto-occurrence))
698e1804
RS
245
246(defvar occur-buffer nil)
247(defvar occur-nlines nil)
248(defvar occur-pos-list nil)
249
250(defun occur-mode ()
251 "Major mode for output from \\[occur].
0081c8a1
RS
252\\<occur-mode-map>Move point to one of the items in this buffer, then use
253\\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
254Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
255
698e1804
RS
256\\{occur-mode-map}"
257 (kill-all-local-variables)
258 (use-local-map occur-mode-map)
259 (setq major-mode 'occur-mode)
260 (setq mode-name "Occur")
261 (make-local-variable 'occur-buffer)
262 (make-local-variable 'occur-nlines)
4baf5620
RS
263 (make-local-variable 'occur-pos-list)
264 (run-hooks 'occur-mode-hook))
698e1804 265
78bead73
RS
266(defun occur-mode-mouse-goto (event)
267 "In Occur mode, go to the occurrence whose line you click on."
268 (interactive "e")
269 (let (buffer pos)
270 (save-excursion
271 (set-buffer (window-buffer (posn-window (event-end event))))
272 (save-excursion
273 (goto-char (posn-point (event-end event)))
274 (setq pos (occur-mode-find-occurrence))
275 (setq buffer occur-buffer)))
276 (pop-to-buffer buffer)
277 (goto-char (marker-position pos))))
278
279(defun occur-mode-find-occurrence ()
698e1804
RS
280 (if (or (null occur-buffer)
281 (null (buffer-name occur-buffer)))
282 (progn
283 (setq occur-buffer nil
284 occur-pos-list nil)
285 (error "Buffer in which occurrences were found is deleted")))
78bead73
RS
286 (let* ((line-count
287 (count-lines (point-min)
288 (save-excursion
289 (beginning-of-line)
290 (point))))
291 (occur-number (save-excursion
698e1804 292 (beginning-of-line)
78bead73 293 (/ (1- line-count)
698e1804
RS
294 (cond ((< occur-nlines 0)
295 (- 2 occur-nlines))
296 ((> occur-nlines 0)
297 (+ 2 (* 2 occur-nlines)))
298 (t 1)))))
299 (pos (nth occur-number occur-pos-list)))
78bead73
RS
300 (if (< line-count 1)
301 (error "No occurrence on this line"))
43549f18
RS
302 (or pos
303 (error "No occurrence on this line"))
78bead73
RS
304 pos))
305
306(defun occur-mode-goto-occurrence ()
307 "Go to the occurrence the current line describes."
308 (interactive)
309 (let ((pos (occur-mode-find-occurrence)))
698e1804 310 (pop-to-buffer occur-buffer)
121e2227 311 (goto-char (marker-position pos))))
4c53bd2b 312\f
698e1804 313(defvar list-matching-lines-default-context-lines 0
da44e784 314 "*Default number of context lines to include around a `list-matching-lines'
698e1804
RS
315match. A negative number means to include that many lines before the match.
316A positive number means to include that many lines both before and after.")
317
31e1d920 318(defalias 'list-matching-lines 'occur)
698e1804 319
c9daced0
RS
320(defvar list-matching-lines-face 'bold
321 "*Face used by M-x list-matching-lines to show the text that matches.
322If the value is nil, don't highlight the matching portions specially.")
323
698e1804 324(defun occur (regexp &optional nlines)
99976f85 325 "Show all lines in the current buffer containing a match for REGEXP.
da44e784
RM
326
327If a match spreads across multiple lines, all those lines are shown.
698e1804 328
da44e784
RM
329Each line is displayed with NLINES lines before and after, or -NLINES
330before if NLINES is negative.
331NLINES defaults to `list-matching-lines-default-context-lines'.
698e1804
RS
332Interactively it is the prefix arg.
333
4c53bd2b 334The lines are shown in a buffer named `*Occur*'.
698e1804
RS
335It serves as a menu to find any of the occurrences in this buffer.
336\\[describe-mode] in that buffer will explain how."
a5dfed3e
RS
337 (interactive
338 (list (let* ((default (car regexp-history))
339 (input
340 (read-from-minibuffer
341 (if default
342 (format "List lines matching regexp (default `%s'): "
343 default)
344 "List lines matching regexp: ")
345 nil nil nil 'regexp-history)))
346 (if (string-equal input "")
347 default
348 (set-text-properties 0 (length input) nil input)
349 input))
350 current-prefix-arg))
351 (let ((nlines (if nlines
352 (prefix-numeric-value nlines)
353 list-matching-lines-default-context-lines))
354 (first t)
698e1804 355 (buffer (current-buffer))
bdd610b2 356 (dir default-directory)
698e1804 357 (linenum 1)
79c2e52b
JB
358 (prevpos (point-min))
359 (final-context-start (make-marker)))
99976f85
RS
360;;; (save-excursion
361;;; (beginning-of-line)
362;;; (setq linenum (1+ (count-lines (point-min) (point))))
363;;; (setq prevpos (point)))
016c214f
RS
364 (save-excursion
365 (goto-char (point-min))
366 ;; Check first whether there are any matches at all.
367 (if (not (re-search-forward regexp nil t))
368 (message "No matches for `%s'" regexp)
369 ;; Back up, so the search loop below will find the first match.
370 (goto-char (match-beginning 0))
371 (with-output-to-temp-buffer "*Occur*"
372 (save-excursion
373 (set-buffer standard-output)
374 (setq default-directory dir)
375 ;; We will insert the number of lines, and "lines", later.
376 (insert " matching ")
377 (let ((print-escape-newlines t))
378 (prin1 regexp))
379 (insert " in buffer " (buffer-name buffer) ?. ?\n)
380 (occur-mode)
381 (setq occur-buffer buffer)
382 (setq occur-nlines nlines)
383 (setq occur-pos-list ()))
384 (if (eq buffer standard-output)
91c6bdc0 385 (goto-char (point-max)))
016c214f
RS
386 (save-excursion
387 ;; Find next match, but give up if prev match was at end of buffer.
388 (while (and (not (= prevpos (point-max)))
389 (re-search-forward regexp nil t))
390 (goto-char (match-beginning 0))
391 (beginning-of-line)
392 (save-match-data
393 (setq linenum (+ linenum (count-lines prevpos (point)))))
394 (setq prevpos (point))
395 (goto-char (match-end 0))
396 (let* ((start (save-excursion
397 (goto-char (match-beginning 0))
398 (forward-line (if (< nlines 0) nlines (- nlines)))
399 (point)))
400 (end (save-excursion
401 (goto-char (match-end 0))
402 (if (> nlines 0)
403 (forward-line (1+ nlines))
404 (forward-line 1))
405 (point)))
c9daced0
RS
406 ;; Record where the actual match
407 (match-offset
408 (save-excursion
409 (goto-char (match-beginning 0))
410 (beginning-of-line)
411 ;; +6 to skip over line number
412 (+ 6 (- (match-beginning 0) (point)))))
413 (match-len (- (match-end 0) (match-beginning 0)))
016c214f
RS
414 (tag (format "%5d" linenum))
415 (empty (make-string (length tag) ?\ ))
416 tem)
417 (save-excursion
418 (setq tem (make-marker))
419 (set-marker tem (point))
420 (set-buffer standard-output)
421 (setq occur-pos-list (cons tem occur-pos-list))
422 (or first (zerop nlines)
423 (insert "--------\n"))
424 (setq first nil)
425 (insert-buffer-substring buffer start end)
426 (set-marker final-context-start
427 (- (point) (- end (match-end 0))))
428 (backward-char (- end start))
429 (setq tem nlines)
430 (while (> tem 0)
431 (insert empty ?:)
432 (forward-line 1)
433 (setq tem (1- tem)))
81fa866c
EN
434 (let ((this-linenum linenum)
435 line-start)
016c214f
RS
436 (while (< (point) final-context-start)
437 (if (null tag)
438 (setq tag (format "%5d" this-linenum)))
439 (insert tag ?:)
c9daced0
RS
440 (setq line-start
441 (save-excursion
442 (beginning-of-line)
443 (point)))
444 (put-text-property line-start
016c214f
RS
445 (save-excursion
446 (end-of-line)
447 (point))
448 'mouse-face 'highlight)
c9daced0
RS
449 (if list-matching-lines-face
450 (put-text-property
451 (+ line-start match-offset)
452 (+ line-start match-offset match-len)
453 'face list-matching-lines-face))
016c214f
RS
454 (forward-line 1)
455 (setq tag nil)
456 (setq this-linenum (1+ this-linenum)))
457 (while (<= (point) final-context-start)
458 (insert empty ?:)
459 (forward-line 1)
460 (setq this-linenum (1+ this-linenum))))
461 (while (< tem nlines)
462 (insert empty ?:)
463 (forward-line 1)
464 (setq tem (1+ tem)))
465 (goto-char (point-max)))
466 (forward-line 1)))
467 (set-buffer standard-output)
468 ;; Put positions in increasing order to go with buffer.
469 (setq occur-pos-list (nreverse occur-pos-list))
470 (goto-char (point-min))
65b4665c
RS
471 (let ((message-string
472 (if (= (length occur-pos-list) 1)
473 "1 line"
474 (format "%d lines" (length occur-pos-list)))))
475 (insert message-string)
476 (if (interactive-p)
477 (message "%s matched" message-string)))))))))
698e1804 478\f
81bdc14d
RS
479;; It would be nice to use \\[...], but there is no reasonable way
480;; to make that display both SPC and Y.
698e1804
RS
481(defconst query-replace-help
482 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
be44f62c 483RET or `q' to exit, Period to replace one match and exit,
698e1804
RS
484Comma to replace but not move point immediately,
485C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
486C-w to delete match and recursive edit,
487C-l to clear the screen, redisplay, and offer same replacement again,
488! to replace all remaining matches with no more questions,
489^ to move point back to previous match."
490 "Help message while in query-replace")
491
81bdc14d
RS
492(defvar query-replace-map (make-sparse-keymap)
493 "Keymap that defines the responses to questions in `query-replace'.
494The \"bindings\" in this map are not commands; they are answers.
495The valid answers include `act', `skip', `act-and-show',
496`exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
d9121bc0 497`automatic', `backup', `exit-prefix', and `help'.")
81bdc14d
RS
498
499(define-key query-replace-map " " 'act)
500(define-key query-replace-map "\d" 'skip)
501(define-key query-replace-map [delete] 'skip)
9275e5e3 502(define-key query-replace-map [backspace] 'skip)
81bdc14d
RS
503(define-key query-replace-map "y" 'act)
504(define-key query-replace-map "n" 'skip)
633a305a
RS
505(define-key query-replace-map "Y" 'act)
506(define-key query-replace-map "N" 'skip)
81bdc14d 507(define-key query-replace-map "," 'act-and-show)
81bdc14d 508(define-key query-replace-map "q" 'exit)
919592c0 509(define-key query-replace-map "\r" 'exit)
384c7da4 510(define-key query-replace-map [return] 'exit)
81bdc14d
RS
511(define-key query-replace-map "." 'act-and-exit)
512(define-key query-replace-map "\C-r" 'edit)
513(define-key query-replace-map "\C-w" 'delete-and-edit)
514(define-key query-replace-map "\C-l" 'recenter)
515(define-key query-replace-map "!" 'automatic)
516(define-key query-replace-map "^" 'backup)
517(define-key query-replace-map "\C-h" 'help)
e731045a
KH
518(define-key query-replace-map [f1] 'help)
519(define-key query-replace-map [help] 'help)
81bdc14d 520(define-key query-replace-map "?" 'help)
bc6312e1
RS
521(define-key query-replace-map "\C-g" 'quit)
522(define-key query-replace-map "\C-]" 'quit)
d9121bc0
RS
523(define-key query-replace-map "\e" 'exit-prefix)
524(define-key query-replace-map [escape] 'exit-prefix)
81bdc14d 525
698e1804
RS
526(defun perform-replace (from-string replacements
527 query-flag regexp-flag delimited-flag
81bdc14d 528 &optional repeat-count map)
698e1804
RS
529 "Subroutine of `query-replace'. Its complexity handles interactive queries.
530Don't use this in your own program unless you want to query and set the mark
531just as `query-replace' does. Instead, write a simple loop like this:
532 (while (re-search-forward \"foo[ \t]+bar\" nil t)
533 (replace-match \"foobar\" nil nil))
e782e9f2 534which will run faster and probably do exactly what you want."
81bdc14d 535 (or map (setq map query-replace-map))
1c1dadab
RS
536 (and query-flag minibuffer-auto-raise
537 (raise-frame (window-frame (minibuffer-window))))
698e1804
RS
538 (let ((nocasify (not (and case-fold-search case-replace
539 (string-equal from-string
540 (downcase from-string)))))
541 (literal (not regexp-flag))
542 (search-function (if regexp-flag 're-search-forward 'search-forward))
543 (search-string from-string)
e5d77022 544 (real-match-data nil) ; the match data for the current match
698e1804
RS
545 (next-replacement nil)
546 (replacement-index 0)
547 (keep-going t)
548 (stack nil)
549 (next-rotate-count 0)
550 (replace-count 0)
da44e784 551 (lastrepl nil) ;Position after last match considered.
ae4eb03c 552 (match-again t)
02d95a27
RS
553 (message
554 (if query-flag
555 (substitute-command-keys
556 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
698e1804
RS
557 (if (stringp replacements)
558 (setq next-replacement replacements)
559 (or repeat-count (setq repeat-count 1)))
560 (if delimited-flag
561 (setq search-function 're-search-forward
562 search-string (concat "\\b"
563 (if regexp-flag from-string
564 (regexp-quote from-string))
565 "\\b")))
566 (push-mark)
567 (undo-boundary)
e782e9f2
RS
568 (unwind-protect
569 ;; Loop finding occurrences that perhaps should be replaced.
570 (while (and keep-going
571 (not (eobp))
572 (funcall search-function search-string nil t)
573 ;; If the search string matches immediately after
574 ;; the previous match, but it did not match there
575 ;; before the replacement was done, ignore the match.
576 (if (or (eq lastrepl (point))
577 (and regexp-flag
578 (eq lastrepl (match-beginning 0))
ae4eb03c 579 (not match-again)))
e782e9f2
RS
580 (if (eobp)
581 nil
582 ;; Don't replace the null string
583 ;; right after end of previous replacement.
584 (forward-char 1)
585 (funcall search-function search-string nil t))
586 t))
587
ae4eb03c
RS
588 ;; Save the data associated with the real match.
589 ;; For speed, use only integers and reuse the list used last time.
590 (setq real-match-data (match-data t real-match-data))
591
592 ;; Before we make the replacement, decide whether the search string
593 ;; can match again just after this match.
594 (if regexp-flag
595 (setq match-again (looking-at search-string)))
e782e9f2
RS
596 ;; If time for a change, advance to next replacement string.
597 (if (and (listp replacements)
598 (= next-rotate-count replace-count))
599 (progn
600 (setq next-rotate-count
601 (+ next-rotate-count repeat-count))
602 (setq next-replacement (nth replacement-index replacements))
603 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
604 (if (not query-flag)
605 (progn
ae4eb03c 606 (store-match-data real-match-data)
e782e9f2
RS
607 (replace-match next-replacement nocasify literal)
608 (setq replace-count (1+ replace-count)))
609 (undo-boundary)
610 (let (done replaced key def)
611 ;; Loop reading commands until one of them sets done,
612 ;; which means it has finished handling this occurrence.
613 (while (not done)
301a9d17 614 (store-match-data real-match-data)
e782e9f2 615 (replace-highlight (match-beginning 0) (match-end 0))
c006b215
KH
616 ;; Bind message-log-max so we don't fill up the message log
617 ;; with a bunch of identical messages.
618 (let ((message-log-max nil))
619 (message message from-string next-replacement))
e782e9f2
RS
620 (setq key (read-event))
621 (setq key (vector key))
622 (setq def (lookup-key map key))
623 ;; Restore the match data while we process the command.
e782e9f2
RS
624 (cond ((eq def 'help)
625 (with-output-to-temp-buffer "*Help*"
626 (princ
627 (concat "Query replacing "
628 (if regexp-flag "regexp " "")
629 from-string " with "
630 next-replacement ".\n\n"
631 (substitute-command-keys
b905ac33
KH
632 query-replace-help)))
633 (save-excursion
634 (set-buffer standard-output)
635 (help-mode))))
e782e9f2
RS
636 ((eq def 'exit)
637 (setq keep-going nil)
638 (setq done t))
639 ((eq def 'backup)
237e6ab0
KH
640 (if stack
641 (let ((elt (car stack)))
642 (goto-char (car elt))
643 (setq replaced (eq t (cdr elt)))
644 (or replaced
645 (store-match-data (cdr elt)))
646 (setq stack (cdr stack)))
647 (message "No previous match")
648 (ding 'no-terminate)
649 (sit-for 1)))
e782e9f2
RS
650 ((eq def 'act)
651 (or replaced
3043b0b4
RS
652 (progn
653 (replace-match next-replacement nocasify literal)
654 (setq replace-count (1+ replace-count))))
e782e9f2
RS
655 (setq done t replaced t))
656 ((eq def 'act-and-exit)
657 (or replaced
3043b0b4
RS
658 (progn
659 (replace-match next-replacement nocasify literal)
660 (setq replace-count (1+ replace-count))))
e782e9f2
RS
661 (setq keep-going nil)
662 (setq done t replaced t))
663 ((eq def 'act-and-show)
664 (if (not replaced)
665 (progn
666 (replace-match next-replacement nocasify literal)
3043b0b4 667 (setq replace-count (1+ replace-count))
e782e9f2
RS
668 (setq replaced t))))
669 ((eq def 'automatic)
670 (or replaced
3043b0b4
RS
671 (progn
672 (replace-match next-replacement nocasify literal)
673 (setq replace-count (1+ replace-count))))
e782e9f2
RS
674 (setq done t query-flag nil replaced t))
675 ((eq def 'skip)
676 (setq done t))
677 ((eq def 'recenter)
678 (recenter nil))
679 ((eq def 'edit)
680 (store-match-data
681 (prog1 (match-data)
ae4eb03c
RS
682 (save-excursion (recursive-edit))))
683 ;; Before we make the replacement,
684 ;; decide whether the search string
685 ;; can match again just after this match.
686 (if regexp-flag
687 (setq match-again (looking-at search-string))))
e782e9f2
RS
688 ((eq def 'delete-and-edit)
689 (delete-region (match-beginning 0) (match-end 0))
690 (store-match-data
691 (prog1 (match-data)
692 (save-excursion (recursive-edit))))
693 (setq replaced t))
d9121bc0
RS
694 ;; Note: we do not need to treat `exit-prefix'
695 ;; specially here, since we reread
696 ;; any unrecognized character.
e782e9f2 697 (t
d9121bc0 698 (setq this-command 'mode-exited)
e782e9f2
RS
699 (setq keep-going nil)
700 (setq unread-command-events
701 (append (listify-key-sequence key)
702 unread-command-events))
703 (setq done t))))
704 ;; Record previous position for ^ when we move on.
705 ;; Change markers to numbers in the match data
706 ;; since lots of markers slow down editing.
707 (setq stack
708 (cons (cons (point)
141aa68c 709 (or replaced (match-data t)))
3043b0b4 710 stack))))
e782e9f2
RS
711 (setq lastrepl (point)))
712 (replace-dehighlight))
4d33492a
RS
713 (or unread-command-events
714 (message "Replaced %d occurrence%s"
715 replace-count
716 (if (= replace-count 1) "" "s")))
717 (and keep-going stack)))
698e1804 718
e782e9f2
RS
719(defvar query-replace-highlight nil
720 "*Non-nil means to highlight words during query replacement.")
721
722(defvar replace-overlay nil)
723
724(defun replace-dehighlight ()
725 (and replace-overlay
726 (progn
727 (delete-overlay replace-overlay)
728 (setq replace-overlay nil))))
729
730(defun replace-highlight (start end)
731 (and query-replace-highlight
732 (progn
733 (or replace-overlay
734 (progn
735 (setq replace-overlay (make-overlay start end))
736 (overlay-put replace-overlay 'face
737 (if (internal-find-face 'query-replace)
738 'query-replace 'region))))
739 (move-overlay replace-overlay start end (current-buffer)))))
740
c88ab9ce 741;;; replace.el ends here