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