(perform-replace): Don't move forward one char
[bpt/emacs.git] / lisp / replace.el
1 ;;; replace.el --- replace commands for Emacs.
2
3 ;; Copyright (C) 1985, 86, 87, 92, 94, 96, 1997, 2000
4 ;; Free Software Foundation, Inc.
5
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
10 ;; the Free Software Foundation; either version 2, or (at your option)
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
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.
22
23 ;;; Commentary:
24
25 ;; This package supplies the string and regular-expression replace functions
26 ;; documented in the Emacs user's manual.
27
28 ;;; Code:
29
30 (defcustom case-replace t
31 "*Non-nil means query-replace should preserve case in replacements."
32 :type 'boolean
33 :group 'matching)
34
35 (defvar query-replace-history nil)
36
37 (defvar query-replace-interactive nil
38 "Non-nil means `query-replace' uses the last search string.
39 That becomes the \"string to replace\".")
40
41 (defcustom query-replace-from-history-variable 'query-replace-history
42 "History list to use for the FROM argument of query-replace commands.
43 The value of this variable should be a symbol; that symbol
44 is used as a variable to hold a history list for the strings
45 or patterns to be replaced."
46 :group 'matching
47 :type 'symbol
48 :version "20.3")
49
50 (defcustom query-replace-to-history-variable 'query-replace-history
51 "History list to use for the TO argument of query-replace commands.
52 The value of this variable should be a symbol; that symbol
53 is used as a variable to hold a history list for replacement
54 strings or patterns."
55 :group 'matching
56 :type 'symbol
57 :version "20.3")
58
59 (defun query-replace-read-args (string regexp-flag)
60 (let (from to)
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
65 query-replace-from-history-variable
66 nil t)))
67 (setq to (read-from-minibuffer (format "%s %s with: " string from)
68 nil nil nil
69 query-replace-to-history-variable from t))
70 (list from to current-prefix-arg)))
71
72 (defun query-replace (from-string to-string &optional delimited)
73 "Replace some occurrences of FROM-STRING with TO-STRING.
74 As each match is found, the user must type a character saying
75 what to do with it. For directions, type \\[help-command] at that time.
76
77 In Transient Mark mode, if the mark is active, operate on the contents
78 of the region. Otherwise, operate from point to the end of the buffer.
79
80 If `query-replace-interactive' is non-nil, the last incremental search
81 string is used as FROM-STRING--you don't have to specify it with the
82 minibuffer.
83
84 Replacement transfers the case of the old text to the new text,
85 if `case-replace' and `case-fold-search'
86 are non-nil and FROM-STRING has no uppercase letters.
87 \(Preserving case means that if the string matched is all caps, or capitalized,
88 then its replacement is upcased or capitalized.)
89
90 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
91 only matches surrounded by word boundaries.
92
93 To customize possible responses, change the \"bindings\" in `query-replace-map'."
94 (interactive (query-replace-read-args "Query replace" nil))
95 (perform-replace from-string to-string t nil delimited))
96
97 (define-key esc-map "%" 'query-replace)
98
99 (defun query-replace-regexp (regexp to-string &optional delimited)
100 "Replace some things after point matching REGEXP with TO-STRING.
101 As each match is found, the user must type a character saying
102 what to do with it. For directions, type \\[help-command] at that time.
103
104 In Transient Mark mode, if the mark is active, operate on the contents
105 of the region. Otherwise, operate from point to the end of the buffer.
106
107 If `query-replace-interactive' is non-nil, the last incremental search
108 regexp is used as REGEXP--you don't have to specify it with the
109 minibuffer.
110
111 Preserves case in each replacement if `case-replace' and `case-fold-search'
112 are non-nil and REGEXP has no uppercase letters.
113 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
114 only matches surrounded by word boundaries.
115 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
116 and `\\=\\N' (where N is a digit) stands for
117 whatever what matched the Nth `\\(...\\)' in REGEXP."
118 (interactive (query-replace-read-args "Query replace regexp" t))
119 (perform-replace regexp to-string t t delimited))
120 (define-key esc-map [?\C-%] 'query-replace-regexp)
121
122 (defun query-replace-regexp-eval (regexp to-expr &optional delimited)
123 "Replace some things after point matching REGEXP with the result of TO-EXPR.
124 As each match is found, the user must type a character saying
125 what to do with it. For directions, type \\[help-command] at that time.
126
127 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
128 reference `replace-count' to get the number of replacements already made.
129 If 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
132 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
133 `\\0'to stand for whatever matched the whole of REGEXP, and `\\=\\N' (where
134 N is a digit) stands for whatever what matched the Nth `\\(...\\)' in REGEXP.
135 Use `\\#&' or `\\#N' if you want a number instead of a string.
136
137 In Transient Mark mode, if the mark is active, operate on the contents
138 of the region. Otherwise, operate from point to the end of the buffer.
139
140 If `query-replace-interactive' is non-nil, the last incremental search
141 regexp is used as REGEXP--you don't have to specify it with the
142 minibuffer.
143
144 Preserves case in each replacement if `case-replace' and `case-fold-search'
145 are non-nil and REGEXP has no uppercase letters.
146 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
147 only 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)))
163 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
164 t t delimited))
165
166 (defun map-query-replace-regexp (regexp to-strings &optional delimited)
167 "Replace some matches for REGEXP with various strings, in rotation.
168 The second argument TO-STRINGS contains the replacement strings, separated
169 by spaces. This command works like `query-replace-regexp' except
170 that each successive replacement uses the next successive replacement string,
171 wrapping around from the last such string to the first.
172
173 In Transient Mark mode, if the mark is active, operate on the contents
174 of the region. Otherwise, operate from point to the end of the buffer.
175
176 Non-interactively, TO-STRINGS may be a list of replacement strings.
177
178 If `query-replace-interactive' is non-nil, the last incremental search
179 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
180
181 A prefix argument N says to use each replacement string N times
182 before rotating to the next."
183 (interactive
184 (let (from to)
185 (setq from (if query-replace-interactive
186 (car regexp-search-ring)
187 (read-from-minibuffer "Map query replace (regexp): "
188 nil nil nil
189 'query-replace-history nil t)))
190 (setq to (read-from-minibuffer
191 (format "Query replace %s with (space-separated strings): "
192 from)
193 nil nil nil
194 'query-replace-history from t))
195 (list from to current-prefix-arg)))
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 ""))))
209 (perform-replace regexp replacements t t nil delimited)))
210
211 (defun replace-string (from-string to-string &optional delimited)
212 "Replace occurrences of FROM-STRING with TO-STRING.
213 Preserve case in each match if `case-replace' and `case-fold-search'
214 are non-nil and FROM-STRING has no uppercase letters.
215 \(Preserving case means that if the string matched is all caps, or capitalized,
216 then its replacement is upcased or capitalized.)
217
218 In Transient Mark mode, if the mark is active, operate on the contents
219 of the region. Otherwise, operate from point to the end of the buffer.
220
221 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
222 only matches surrounded by word boundaries.
223
224 If `query-replace-interactive' is non-nil, the last incremental search
225 string is used as FROM-STRING--you don't have to specify it with the
226 minibuffer.
227
228 This function is usually the wrong thing to use in a Lisp program.
229 What you probably want is a loop like this:
230 (while (search-forward FROM-STRING nil t)
231 (replace-match TO-STRING nil t))
232 which 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
234 and TO-STRING is also null.)"
235 (interactive (query-replace-read-args "Replace string" nil))
236 (perform-replace from-string to-string nil nil delimited))
237
238 (defun replace-regexp (regexp to-string &optional delimited)
239 "Replace things after point matching REGEXP with TO-STRING.
240 Preserve case in each match if `case-replace' and `case-fold-search'
241 are non-nil and REGEXP has no uppercase letters.
242 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
243 only matches surrounded by word boundaries.
244 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
245 and `\\=\\N' (where N is a digit) stands for
246 whatever what matched the Nth `\\(...\\)' in REGEXP.
247
248 In Transient Mark mode, if the mark is active, operate on the contents
249 of the region. Otherwise, operate from point to the end of the buffer.
250
251 If `query-replace-interactive' is non-nil, the last incremental search
252 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
253
254 This function is usually the wrong thing to use in a Lisp program.
255 What you probably want is a loop like this:
256 (while (re-search-forward REGEXP nil t)
257 (replace-match TO-STRING nil nil))
258 which will run faster and will not set the mark or print anything."
259 (interactive (query-replace-read-args "Replace regexp" t))
260 (perform-replace regexp to-string nil t delimited))
261 \f
262 (defvar regexp-history nil
263 "History list for some commands that read regular expressions.")
264
265 (defalias 'delete-non-matching-lines 'keep-lines)
266 (defun keep-lines (regexp)
267 "Delete all lines except those containing matches for REGEXP.
268 A match split across lines preserves all the lines it lies in.
269 Applies to all lines after point.
270
271 If REGEXP contains upper case characters (excluding those preceded by `\\'),
272 the matching is case-sensitive."
273 (interactive (list (read-from-minibuffer
274 "Keep lines (containing match for regexp): "
275 nil nil nil 'regexp-history nil t)))
276 (save-excursion
277 (or (bolp) (forward-line 1))
278 (let ((start (point))
279 (case-fold-search (and case-fold-search
280 (isearch-no-upper-case-p regexp t))))
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
297 (defalias 'delete-matching-lines 'flush-lines)
298 (defun flush-lines (regexp)
299 "Delete lines containing matches for REGEXP.
300 If a match is split across lines, all the lines it lies in are deleted.
301 Applies to lines after point.
302
303 If REGEXP contains upper case characters (excluding those preceded by `\\'),
304 the matching is case-sensitive."
305 (interactive (list (read-from-minibuffer
306 "Flush lines (containing match for regexp): "
307 nil nil nil 'regexp-history nil t)))
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)))))))
317
318 (defalias 'count-matches 'how-many)
319 (defun how-many (regexp)
320 "Print number of matches for REGEXP following point.
321
322 If REGEXP contains upper case characters (excluding those preceded by `\\'),
323 the matching is case-sensitive."
324 (interactive (list (read-from-minibuffer
325 "How many matches for (regexp): "
326 nil nil nil 'regexp-history nil t)))
327 (let ((count 0) opoint
328 (case-fold-search (and case-fold-search
329 (isearch-no-upper-case-p regexp t))))
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))))
338 \f
339 (defvar occur-mode-map ())
340 (if occur-mode-map
341 ()
342 (setq occur-mode-map (make-sparse-keymap))
343 (define-key occur-mode-map [mouse-2] 'occur-mode-mouse-goto)
344 (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence)
345 (define-key occur-mode-map "\C-m" 'occur-mode-goto-occurrence)
346 (define-key occur-mode-map "\M-n" 'occur-next)
347 (define-key occur-mode-map "\M-p" 'occur-prev)
348 (define-key occur-mode-map "g" 'revert-buffer))
349
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
358 (defvar occur-command-arguments nil
359 "Arguments that were given to `occur' when it made this buffer.")
360
361 (put 'occur-mode 'mode-class 'special)
362
363 (defun occur-mode ()
364 "Major mode for output from \\[occur].
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.
367 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
368
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")
374 (make-local-variable 'revert-buffer-function)
375 (setq revert-buffer-function 'occur-revert-function)
376 (make-local-variable 'occur-buffer)
377 (make-local-variable 'occur-nlines)
378 (make-local-variable 'occur-command-arguments)
379 (run-hooks 'occur-mode-hook))
380
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
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 ()
402 (if (or (null occur-buffer)
403 (null (buffer-name occur-buffer)))
404 (progn
405 (setq occur-buffer nil)
406 (error "Buffer in which occurrences were found is deleted")))
407 (let ((pos (get-text-property (point) 'occur)))
408 (if (null pos)
409 (error "No occurrence on this line")
410 pos)))
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)))
416 (pop-to-buffer occur-buffer)
417 (goto-char (marker-position pos))))
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)))))
451 \f
452 (defcustom list-matching-lines-default-context-lines 0
453 "*Default number of context lines to include around a `list-matching-lines'
454 match. A negative number means to include that many lines before the match.
455 A positive number means to include that many lines both before and after."
456 :type 'integer
457 :group 'matching)
458
459 (defalias 'list-matching-lines 'occur)
460
461 (defvar list-matching-lines-face 'bold
462 "*Face used by M-x list-matching-lines to show the text that matches.
463 If the value is nil, don't highlight the matching portions specially.")
464
465 (defun occur (regexp &optional nlines)
466 "Show all lines in the current buffer containing a match for REGEXP.
467
468 If a match spreads across multiple lines, all those lines are shown.
469
470 Each line is displayed with NLINES lines before and after, or -NLINES
471 before if NLINES is negative.
472 NLINES defaults to `list-matching-lines-default-context-lines'.
473 Interactively it is the prefix arg.
474
475 The lines are shown in a buffer named `*Occur*'.
476 It serves as a menu to find any of the occurrences in this buffer.
477 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
478
479 If REGEXP contains upper case characters (excluding those preceded by `\\'),
480 the matching is case-sensitive."
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: ")
489 nil nil nil 'regexp-history default t)))
490 (and (equal input "") default
491 (setq input default))
492 input)
493 current-prefix-arg))
494 (let ((nlines (if nlines
495 (prefix-numeric-value nlines)
496 list-matching-lines-default-context-lines))
497 (first t)
498 ;;flag to prevent printing separator for first match
499 (occur-num-matches 0)
500 (buffer (current-buffer))
501 (dir default-directory)
502 (linenum 1)
503 (prevpos
504 ;;position of most recent match
505 (point-min))
506 (case-fold-search (and case-fold-search
507 (isearch-no-upper-case-p regexp t)))
508 (final-context-start
509 ;; Marker to the start of context immediately following
510 ;; the matched text in *Occur*.
511 (make-marker)))
512 ;;; (save-excursion
513 ;;; (beginning-of-line)
514 ;;; (setq linenum (1+ (count-lines (point-min) (point))))
515 ;;; (setq prevpos (point)))
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)
535 (setq occur-command-arguments
536 (list regexp nlines)))
537 (if (eq buffer standard-output)
538 (goto-char (point-max)))
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))
549 (let* ((start
550 ;;start point of text in source buffer to be put
551 ;;into *Occur*
552 (save-excursion
553 (goto-char (match-beginning 0))
554 (forward-line (if (< nlines 0)
555 nlines
556 (- nlines)))
557 (point)))
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)))
573 (tag (format "%5d" linenum))
574 (empty (make-string (length tag) ?\ ))
575 tem
576 insertion-start
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))
588 )
589 (save-excursion
590 (setq occur-marker (make-marker))
591 (set-marker occur-marker (point))
592 (set-buffer standard-output)
593 (setq occur-num-matches (1+ occur-num-matches))
594 (or first (zerop nlines)
595 (insert "--------\n"))
596 (setq first nil)
597
598 ;; Insert matching text including context lines from
599 ;; source buffer into *Occur*
600 (set-marker text-beg (point))
601 (setq insertion-start (point))
602 (insert-buffer-substring buffer start end)
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)))
616 (set-marker text-end (point))
617
618 ;; Highlight text that was matched.
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
625 ;; `occur-point' property is used by occur-next and
626 ;; occur-prev to move between matching lines.
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)
631
632 ;; Now go back to the start of the matching text
633 ;; adding the space and colon to the start of each line.
634 (goto-char insertion-start)
635 ;; Insert space and colon for lines of context before match.
636 (setq tem (if (< linenum nlines)
637 (- nlines linenum)
638 nlines))
639 (while (> tem 0)
640 (insert empty ?:)
641 (forward-line 1)
642 (setq tem (1- tem)))
643
644 ;; Insert line number and colon for the lines of
645 ;; matching text.
646 (let ((this-linenum linenum))
647 (while (< (point) final-context-start)
648 (if (null tag)
649 (setq tag (format "%5d" this-linenum)))
650 (insert tag ?:)
651 (forward-line 1)
652 (setq tag nil)
653 (setq this-linenum (1+ this-linenum)))
654 (while (and (not (eobp)) (<= (point) final-context-start))
655 (insert empty ?:)
656 (forward-line 1)
657 (setq this-linenum (1+ this-linenum))))
658
659 ;; Insert space and colon for lines of context after match.
660 (while (and (< (point) (point-max)) (< tem nlines))
661 (insert empty ?:)
662 (forward-line 1)
663 (setq tem (1+ tem)))
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)
672 (marker-position text-end)
673 'occur occur-marker)
674 (goto-char (point-max)))
675 (forward-line 1)))
676 (set-buffer standard-output)
677 ;; Go back to top of *Occur* and finish off by printing the
678 ;; number of matching lines.
679 (goto-char (point-min))
680 (let ((message-string
681 (if (= occur-num-matches 1)
682 "1 line"
683 (format "%d lines" occur-num-matches))))
684 (insert message-string)
685 (if (interactive-p)
686 (message "%s matched" message-string)))
687 (setq buffer-read-only t)))))))
688 \f
689 ;; It would be nice to use \\[...], but there is no reasonable way
690 ;; to make that display both SPC and Y.
691 (defconst query-replace-help
692 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
693 RET or `q' to exit, Period to replace one match and exit,
694 Comma to replace but not move point immediately,
695 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
696 C-w to delete match and recursive edit,
697 C-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
702 (defvar query-replace-map (make-sparse-keymap)
703 "Keymap that defines the responses to questions in `query-replace'.
704 The \"bindings\" in this map are not commands; they are answers.
705 The valid answers include `act', `skip', `act-and-show',
706 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
707 `automatic', `backup', `exit-prefix', and `help'.")
708
709 (define-key query-replace-map " " 'act)
710 (define-key query-replace-map "\d" 'skip)
711 (define-key query-replace-map [delete] 'skip)
712 (define-key query-replace-map [backspace] 'skip)
713 (define-key query-replace-map "y" 'act)
714 (define-key query-replace-map "n" 'skip)
715 (define-key query-replace-map "Y" 'act)
716 (define-key query-replace-map "N" 'skip)
717 (define-key query-replace-map "," 'act-and-show)
718 (define-key query-replace-map "q" 'exit)
719 (define-key query-replace-map "\r" 'exit)
720 (define-key query-replace-map [return] 'exit)
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)
728 (define-key query-replace-map [f1] 'help)
729 (define-key query-replace-map [help] 'help)
730 (define-key query-replace-map "?" 'help)
731 (define-key query-replace-map "\C-g" 'quit)
732 (define-key query-replace-map "\C-]" 'quit)
733 (define-key query-replace-map "\e" 'exit-prefix)
734 (define-key query-replace-map [escape] 'exit-prefix)
735
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
784 (defun perform-replace (from-string replacements
785 query-flag regexp-flag delimited-flag
786 &optional repeat-count map)
787 "Subroutine of `query-replace'. Its complexity handles interactive queries.
788 Don't use this in your own program unless you want to query and set the mark
789 just 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))
792 which will run faster and probably do exactly what you want."
793 (or map (setq map query-replace-map))
794 (and query-flag minibuffer-auto-raise
795 (raise-frame (window-frame (minibuffer-window))))
796 (let ((nocasify (not (and case-fold-search case-replace
797 (string-equal from-string
798 (downcase from-string)))))
799 (case-fold-search (and case-fold-search
800 (string-equal from-string
801 (downcase from-string))))
802 (literal (not regexp-flag))
803 (search-function (if regexp-flag 're-search-forward 'search-forward))
804 (search-string from-string)
805 (real-match-data nil) ; the match data for the current match
806 (next-replacement nil)
807 (keep-going t)
808 (stack nil)
809 (replace-count 0)
810 (nonempty-match nil)
811
812 ;; If non-nil, it is marker saying where in the buffer to stop.
813 (limit nil)
814
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.
817 (match-again t)
818
819 (message
820 (if query-flag
821 (substitute-command-keys
822 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
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)))
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
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)
854 (unwind-protect
855 ;; Loop finding occurrences that perhaps should be replaced.
856 (while (and keep-going
857 (not (eobp))
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
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))))
877 (funcall search-function search-string limit t)
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)
895 (match-data)))))
896
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)))
903 (if (not query-flag)
904 (progn
905 (set-match-data real-match-data)
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)
913 (set-match-data real-match-data)
914 (replace-highlight (match-beginning 0) (match-end 0))
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))
919 (setq key (read-event))
920 ;; Necessary in case something happens during read-event
921 ;; that clobbers the match data.
922 (set-match-data real-match-data)
923 (setq key (vector key))
924 (setq def (lookup-key map key))
925 ;; Restore the match data while we process the command.
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
934 query-replace-help)))
935 (save-excursion
936 (set-buffer standard-output)
937 (help-mode))))
938 ((eq def 'exit)
939 (setq keep-going nil)
940 (setq done t))
941 ((eq def 'backup)
942 (if stack
943 (let ((elt (car stack)))
944 (goto-char (car elt))
945 (setq replaced (eq t (cdr elt)))
946 (or replaced
947 (set-match-data (cdr elt)))
948 (setq stack (cdr stack)))
949 (message "No previous match")
950 (ding 'no-terminate)
951 (sit-for 1)))
952 ((eq def 'act)
953 (or replaced
954 (progn
955 (replace-match next-replacement nocasify literal)
956 (setq replace-count (1+ replace-count))))
957 (setq done t replaced t))
958 ((eq def 'act-and-exit)
959 (or replaced
960 (progn
961 (replace-match next-replacement nocasify literal)
962 (setq replace-count (1+ replace-count))))
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)
969 (setq replace-count (1+ replace-count))
970 (setq replaced t))))
971 ((eq def 'automatic)
972 (or replaced
973 (progn
974 (replace-match next-replacement nocasify literal)
975 (setq replace-count (1+ replace-count))))
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)
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))
989 (set-match-data real-match-data)
990 ;; Before we make the replacement,
991 ;; decide whether the search string
992 ;; can match again just after this match.
993 (if (and regexp-flag nonempty-match)
994 (setq match-again (and (looking-at search-string)
995 (match-data)))))
996 ((eq def 'delete-and-edit)
997 (delete-region (match-beginning 0) (match-end 0))
998 (set-match-data
999 (prog1 (match-data)
1000 (save-excursion (recursive-edit))))
1001 (setq replaced t))
1002 ;; Note: we do not need to treat `exit-prefix'
1003 ;; specially here, since we reread
1004 ;; any unrecognized character.
1005 (t
1006 (setq this-command 'mode-exited)
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)
1017 (or replaced (match-data t)))
1018 stack)))))
1019 (replace-dehighlight))
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)))
1025
1026 (defcustom query-replace-highlight t
1027 "*Non-nil means to highlight words during query replacement."
1028 :type 'boolean
1029 :group 'matching)
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
1050 ;;; replace.el ends here