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