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