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