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