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