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