1 ;;; replace.el --- replace commands for Emacs.
3 ;; Copyright (C) 1985, 1986, 1987, 1992, 1994 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)
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.
24 ;; This package supplies the string and regular-expression replace functions
25 ;; documented in the Emacs user's manual.
29 (defconst case-replace t
"\
30 *Non-nil means query-replace should preserve case in replacements.")
32 (defvar query-replace-history nil
)
34 (defvar query-replace-interactive nil
35 "Non-nil means `query-replace' uses the last search string.
36 That becomes the \"string to replace\".")
38 (defun query-replace-read-args (string regexp-flag
)
40 (if query-replace-interactive
41 (setq from
(car (if regexp-flag regexp-search-ring search-ring
)))
42 (setq from
(read-from-minibuffer (format "%s: " string
)
44 'query-replace-history
)))
45 (setq to
(read-from-minibuffer (format "%s %s with: " string from
)
47 'query-replace-history
))
48 (list from to current-prefix-arg
)))
50 (defun query-replace (from-string to-string
&optional arg
)
51 "Replace some occurrences of FROM-STRING with TO-STRING.
52 As each match is found, the user must type a character saying
53 what to do with it. For directions, type \\[help-command] at that time.
55 If `query-replace-interactive' is non-nil, the last incremental search
56 string is used as FROM-STRING--you don't have to specify it with the
59 Preserves case in each replacement if `case-replace' and `case-fold-search'
60 are non-nil and FROM-STRING has no uppercase letters.
61 \(Preserving case means that if the string matched is all caps, or capitalized,
62 then its replacement is upcased or capitalized.)
64 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
65 only matches surrounded by word boundaries.
67 To customize possible responses, change the \"bindings\" in `query-replace-map'."
68 (interactive (query-replace-read-args "Query replace" nil
))
69 (perform-replace from-string to-string t nil arg
))
70 (define-key esc-map
"%" 'query-replace
)
72 (defun query-replace-regexp (regexp to-string
&optional arg
)
73 "Replace some things after point matching REGEXP 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.
77 If `query-replace-interactive' is non-nil, the last incremental search
78 regexp is used as REGEXP--you don't have to specify it with the
81 Preserves case in each replacement if `case-replace' and `case-fold-search'
82 are non-nil and REGEXP has no uppercase letters.
83 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
84 only matches surrounded by word boundaries.
85 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
86 and `\\=\\N' (where N is a digit) stands for
87 whatever what matched the Nth `\\(...\\)' in REGEXP."
88 (interactive (query-replace-read-args "Query replace regexp" t
))
89 (perform-replace regexp to-string t t arg
))
91 (defun map-query-replace-regexp (regexp to-strings
&optional arg
)
92 "Replace some matches for REGEXP with various strings, in rotation.
93 The second argument TO-STRINGS contains the replacement strings, separated
94 by spaces. This command works like `query-replace-regexp' except
95 that each successive replacement uses the next successive replacement string,
96 wrapping around from the last such string to the first.
98 Non-interactively, TO-STRINGS may be a list of replacement strings.
100 If `query-replace-interactive' is non-nil, the last incremental search
101 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
103 A prefix argument N says to use each replacement string N times
104 before rotating to the next."
107 (setq from
(if query-replace-interactive
108 (car regexp-search-ring
)
109 (read-from-minibuffer "Map query replace (regexp): "
111 'query-replace-history
)))
112 (setq to
(read-from-minibuffer
113 (format "Query replace %s with (space-separated strings): "
116 'query-replace-history
))
117 (list from to current-prefix-arg
)))
119 (if (listp to-strings
)
120 (setq replacements to-strings
)
121 (while (/= (length to-strings
) 0)
122 (if (string-match " " to-strings
)
125 (list (substring to-strings
0
126 (string-match " " to-strings
))))
127 to-strings
(substring to-strings
128 (1+ (string-match " " to-strings
))))
129 (setq replacements
(append replacements
(list to-strings
))
131 (perform-replace regexp replacements t t nil arg
)))
133 (defun replace-string (from-string to-string
&optional delimited
)
134 "Replace occurrences of FROM-STRING with TO-STRING.
135 Preserve case in each match if `case-replace' and `case-fold-search'
136 are non-nil and FROM-STRING has no uppercase letters.
137 \(Preserving case means that if the string matched is all caps, or capitalized,
138 then its replacement is upcased or capitalized.)
140 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
141 only matches surrounded by word boundaries.
143 If `query-replace-interactive' is non-nil, the last incremental search
144 string is used as FROM-STRING--you don't have to specify it with the
147 This function is usually the wrong thing to use in a Lisp program.
148 What you probably want is a loop like this:
149 (while (search-forward FROM-STRING nil t)
150 (replace-match TO-STRING nil t))
151 which will run faster and will not set the mark or print anything."
152 (interactive (query-replace-read-args "Replace string" nil
))
153 (perform-replace from-string to-string nil nil delimited
))
155 (defun replace-regexp (regexp to-string
&optional delimited
)
156 "Replace things after point matching REGEXP with TO-STRING.
157 Preserve case in each match if `case-replace' and `case-fold-search'
158 are non-nil and REGEXP has no uppercase letters.
159 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
160 only matches surrounded by word boundaries.
161 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
162 and `\\=\\N' (where N is a digit) stands for
163 whatever what matched the Nth `\\(...\\)' in REGEXP.
165 If `query-replace-interactive' is non-nil, the last incremental search
166 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
168 This function is usually the wrong thing to use in a Lisp program.
169 What you probably want is a loop like this:
170 (while (re-search-forward REGEXP nil t)
171 (replace-match TO-STRING nil nil))
172 which will run faster and will not set the mark or print anything."
173 (interactive (query-replace-read-args "Replace regexp" t
))
174 (perform-replace regexp to-string nil t delimited
))
176 (defvar regexp-history nil
177 "History list for some commands that read regular expressions.")
179 (defalias 'delete-non-matching-lines
'keep-lines
)
180 (defun keep-lines (regexp)
181 "Delete all lines except those containing matches for REGEXP.
182 A match split across lines preserves all the lines it lies in.
183 Applies to all lines after point."
184 (interactive (list (read-from-minibuffer
185 "Keep lines (containing match for regexp): "
186 nil nil nil
'regexp-history
)))
188 (or (bolp) (forward-line 1))
189 (let ((start (point)))
191 ;; Start is first char not preserved by previous match.
192 (if (not (re-search-forward regexp nil
'move
))
193 (delete-region start
(point-max))
194 (let ((end (save-excursion (goto-char (match-beginning 0))
197 ;; Now end is first char preserved by the new match.
199 (delete-region start end
))))
200 (setq start
(save-excursion (forward-line 1)
202 ;; If the match was empty, avoid matching again at same place.
203 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
204 (forward-char 1))))))
206 (defalias 'delete-matching-lines
'flush-lines
)
207 (defun flush-lines (regexp)
208 "Delete lines containing matches for REGEXP.
209 If a match is split across lines, all the lines it lies in are deleted.
210 Applies to lines after point."
211 (interactive (list (read-from-minibuffer
212 "Flush lines (containing match for regexp): "
213 nil nil nil
'regexp-history
)))
215 (while (and (not (eobp))
216 (re-search-forward regexp nil t
))
217 (delete-region (save-excursion (goto-char (match-beginning 0))
220 (progn (forward-line 1) (point))))))
222 (defalias 'count-matches
'how-many
)
223 (defun how-many (regexp)
224 "Print number of matches for REGEXP following point."
225 (interactive (list (read-from-minibuffer
226 "How many matches for (regexp): "
227 nil nil nil
'regexp-history
)))
228 (let ((count 0) opoint
)
230 (while (and (not (eobp))
231 (progn (setq opoint
(point))
232 (re-search-forward regexp nil t
)))
233 (if (= opoint
(point))
235 (setq count
(1+ count
))))
236 (message "%d occurrences" count
))))
238 (defvar occur-mode-map
())
241 (setq occur-mode-map
(make-sparse-keymap))
242 (define-key occur-mode-map
[mouse-2
] 'occur-mode-mouse-goto
)
243 (define-key occur-mode-map
"\C-c\C-c" 'occur-mode-goto-occurrence
)
244 (define-key occur-mode-map
"\C-m" 'occur-mode-goto-occurrence
))
246 (defvar occur-buffer nil
)
247 (defvar occur-nlines nil
)
248 (defvar occur-pos-list nil
)
251 "Major mode for output from \\[occur].
252 \\<occur-mode-map>Move point to one of the items in this buffer, then use
253 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
254 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
257 (kill-all-local-variables)
258 (use-local-map occur-mode-map
)
259 (setq major-mode
'occur-mode
)
260 (setq mode-name
"Occur")
261 (make-local-variable 'occur-buffer
)
262 (make-local-variable 'occur-nlines
)
263 (make-local-variable 'occur-pos-list
)
264 (run-hooks 'occur-mode-hook
))
266 (defun occur-mode-mouse-goto (event)
267 "In Occur mode, go to the occurrence whose line you click on."
271 (set-buffer (window-buffer (posn-window (event-end event
))))
273 (goto-char (posn-point (event-end event
)))
274 (setq pos
(occur-mode-find-occurrence))
275 (setq buffer occur-buffer
)))
276 (pop-to-buffer buffer
)
277 (goto-char (marker-position pos
))))
279 (defun occur-mode-find-occurrence ()
280 (if (or (null occur-buffer
)
281 (null (buffer-name occur-buffer
)))
283 (setq occur-buffer nil
285 (error "Buffer in which occurrences were found is deleted")))
287 (count-lines (point-min)
291 (occur-number (save-excursion
294 (cond ((< occur-nlines
0)
297 (+ 2 (* 2 occur-nlines
)))
299 (pos (nth occur-number occur-pos-list
)))
301 (error "No occurrence on this line"))
303 (error "No occurrence on this line"))
306 (defun occur-mode-goto-occurrence ()
307 "Go to the occurrence the current line describes."
309 (let ((pos (occur-mode-find-occurrence)))
310 (pop-to-buffer occur-buffer
)
311 (goto-char (marker-position pos
))))
313 (defvar list-matching-lines-default-context-lines
0
314 "*Default number of context lines to include around a `list-matching-lines'
315 match. A negative number means to include that many lines before the match.
316 A positive number means to include that many lines both before and after.")
318 (defalias 'list-matching-lines
'occur
)
320 (defun occur (regexp &optional nlines
)
321 "Show all lines in the current buffer containing a match for REGEXP.
323 If a match spreads across multiple lines, all those lines are shown.
325 Each line is displayed with NLINES lines before and after, or -NLINES
326 before if NLINES is negative.
327 NLINES defaults to `list-matching-lines-default-context-lines'.
328 Interactively it is the prefix arg.
330 The lines are shown in a buffer named `*Occur*'.
331 It serves as a menu to find any of the occurrences in this buffer.
332 \\[describe-mode] in that buffer will explain how."
333 (interactive (list (let* ((default (car regexp-history
))
335 (read-from-minibuffer
337 (format "List lines matching regexp (default `%s'): " default
)
338 "List lines matching regexp: ")
341 (if (> (length input
) 0) input
342 (setcar regexp-history default
)))
344 (setq nlines
(if nlines
(prefix-numeric-value nlines
)
345 list-matching-lines-default-context-lines
))
347 (buffer (current-buffer))
348 (dir default-directory
)
350 (prevpos (point-min))
351 (final-context-start (make-marker)))
353 ;;; (beginning-of-line)
354 ;;; (setq linenum (1+ (count-lines (point-min) (point))))
355 ;;; (setq prevpos (point)))
356 (with-output-to-temp-buffer "*Occur*"
358 (set-buffer standard-output
)
359 (setq default-directory dir
)
360 ;; We will insert the number of lines, and "lines", later.
361 (insert " matching ")
362 (let ((print-escape-newlines t
))
364 (insert " in buffer " (buffer-name buffer
) ?. ?
\n)
366 (setq occur-buffer buffer
)
367 (setq occur-nlines nlines
)
368 (setq occur-pos-list
()))
369 (if (eq buffer standard-output
)
370 (goto-char (point-max)))
372 (beginning-of-buffer)
373 ;; Find next match, but give up if prev match was at end of buffer.
374 (while (and (not (= prevpos
(point-max)))
375 (re-search-forward regexp nil t
))
376 (goto-char (match-beginning 0))
379 (setq linenum
(+ linenum
(count-lines prevpos
(point)))))
380 (setq prevpos
(point))
381 (goto-char (match-end 0))
382 (let* ((start (save-excursion
383 (goto-char (match-beginning 0))
384 (forward-line (if (< nlines
0) nlines
(- nlines
)))
387 (goto-char (match-end 0))
389 (forward-line (1+ nlines
))
392 (tag (format "%5d" linenum
))
393 (empty (make-string (length tag
) ?\
))
396 (setq tem
(make-marker))
397 (set-marker tem
(point))
398 (set-buffer standard-output
)
399 (setq occur-pos-list
(cons tem occur-pos-list
))
400 (or first
(zerop nlines
)
401 (insert "--------\n"))
403 (insert-buffer-substring buffer start end
)
404 (set-marker final-context-start
405 (- (point) (- end
(match-end 0))))
406 (backward-char (- end start
))
412 (let ((this-linenum linenum
))
413 (while (< (point) final-context-start
)
415 (setq tag
(format "%5d" this-linenum
)))
417 (put-text-property (save-excursion
423 'mouse-face
'highlight
)
426 (setq this-linenum
(1+ this-linenum
)))
427 (while (<= (point) final-context-start
)
430 (setq this-linenum
(1+ this-linenum
))))
431 (while (< tem nlines
)
435 (goto-char (point-max)))
437 (set-buffer standard-output
)
438 ;; Put positions in increasing order to go with buffer.
439 (setq occur-pos-list
(nreverse occur-pos-list
))
440 (goto-char (point-min))
441 (if (= (length occur-pos-list
) 1)
443 (insert (format "%d lines" (length occur-pos-list
))))
445 (message "%d matching lines." (length occur-pos-list
)))))))
447 ;; It would be nice to use \\[...], but there is no reasonable way
448 ;; to make that display both SPC and Y.
449 (defconst query-replace-help
450 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
451 RET or `q' to exit, Period to replace one match and exit,
452 Comma to replace but not move point immediately,
453 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
454 C-w to delete match and recursive edit,
455 C-l to clear the screen, redisplay, and offer same replacement again,
456 ! to replace all remaining matches with no more questions,
457 ^ to move point back to previous match."
458 "Help message while in query-replace")
460 (defvar query-replace-map
(make-sparse-keymap)
461 "Keymap that defines the responses to questions in `query-replace'.
462 The \"bindings\" in this map are not commands; they are answers.
463 The valid answers include `act', `skip', `act-and-show',
464 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
465 `automatic', `backup', `exit-prefix', and `help'.")
467 (define-key query-replace-map
" " 'act
)
468 (define-key query-replace-map
"\d" 'skip
)
469 (define-key query-replace-map
[delete] 'skip)
470 (define-key query-replace-map [backspace] 'skip)
471 (define-key query-replace-map "y" 'act)
472 (define-key query-replace-map "n" 'skip)
473 (define-key query-replace-map "Y" 'act)
474 (define-key query-replace-map "N" 'skip)
475 (define-key query-replace-map "," 'act-and-show)
476 (define-key query-replace-map "q" 'exit)
477 (define-key query-replace-map "\r" 'exit)
478 (define-key query-replace-map [return] 'exit)
479 (define-key query-replace-map "." 'act-and-exit)
480 (define-key query-replace-map "\C-r" 'edit)
481 (define-key query-replace-map "\C-w" 'delete-and-edit)
482 (define-key query-replace-map "\C-l" 'recenter)
483 (define-key query-replace-map "!" 'automatic)
484 (define-key query-replace-map "^" 'backup)
485 (define-key query-replace-map "\C-h" 'help)
486 (define-key query-replace-map [f1] 'help)
487 (define-key query-replace-map [help] 'help)
488 (define-key query-replace-map "?" 'help)
489 (define-key query-replace-map "\C-g" 'quit)
490 (define-key query-replace-map "\C-]" 'quit)
491 (define-key query-replace-map "\e" 'exit-prefix)
492 (define-key query-replace-map [escape] 'exit-prefix)
494 (defun perform-replace (from-string replacements
495 query-flag regexp-flag delimited-flag
496 &optional repeat-count map)
497 "Subroutine of `query-replace'. Its complexity handles interactive queries.
498 Don't use this in your own program unless you want to query and set the mark
499 just as `query-replace' does. Instead, write a simple loop like this:
500 (while (re-search-forward \"foo[ \t]+bar\" nil t)
501 (replace-match \"foobar\" nil nil))
502 which will run faster and probably do exactly what you want."
503 (or map (setq map query-replace-map))
504 (let ((nocasify (not (and case-fold-search case-replace
505 (string-equal from-string
506 (downcase from-string)))))
507 (literal (not regexp-flag))
508 (search-function (if regexp-flag 're-search-forward 'search-forward))
509 (search-string from-string)
510 (real-match-data nil) ; the match data for the current match
511 (next-replacement nil)
512 (replacement-index 0)
515 (next-rotate-count 0)
517 (lastrepl nil) ;Position after last match considered.
521 (substitute-command-keys
522 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
523 (if (stringp replacements)
524 (setq next-replacement replacements)
525 (or repeat-count (setq repeat-count 1)))
527 (setq search-function 're-search-forward
528 search-string (concat "\\b"
529 (if regexp-flag from-string
530 (regexp-quote from-string))
535 ;; Loop finding occurrences that perhaps should be replaced.
536 (while (and keep-going
538 (funcall search-function search-string nil t)
539 ;; If the search string matches immediately after
540 ;; the previous match, but it did not match there
541 ;; before the replacement was done, ignore the match.
542 (if (or (eq lastrepl (point))
544 (eq lastrepl (match-beginning 0))
548 ;; Don't replace the null string
549 ;; right after end of previous replacement.
551 (funcall search-function search-string nil t))
554 ;; Save the data associated with the real match.
555 (setq real-match-data (match-data))
557 ;; Before we make the replacement, decide whether the search string
558 ;; can match again just after this match.
560 (setq match-again (looking-at search-string)))
561 ;; If time for a change, advance to next replacement string.
562 (if (and (listp replacements)
563 (= next-rotate-count replace-count))
565 (setq next-rotate-count
566 (+ next-rotate-count repeat-count))
567 (setq next-replacement (nth replacement-index replacements))
568 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
571 (store-match-data real-match-data)
572 (replace-match next-replacement nocasify literal)
573 (setq replace-count (1+ replace-count)))
575 (let (done replaced key def)
576 ;; Loop reading commands until one of them sets done,
577 ;; which means it has finished handling this occurrence.
579 (store-match-data real-match-data)
580 (replace-highlight (match-beginning 0) (match-end 0))
581 ;; Bind message-log-max so we don't fill up the message log
582 ;; with a bunch of identical messages.
583 (let ((message-log-max nil))
584 (message message from-string next-replacement))
585 (setq key (read-event))
586 (setq key (vector key))
587 (setq def (lookup-key map key))
588 ;; Restore the match data while we process the command.
589 (cond ((eq def 'help)
590 (with-output-to-temp-buffer "*Help*"
592 (concat "Query replacing "
593 (if regexp-flag "regexp " "")
595 next-replacement ".\n\n"
596 (substitute-command-keys
597 query-replace-help)))
599 (set-buffer standard-output)
602 (setq keep-going nil)
606 (let ((elt (car stack)))
607 (goto-char (car elt))
608 (setq replaced (eq t (cdr elt)))
610 (store-match-data (cdr elt)))
611 (setq stack (cdr stack)))
612 (message "No previous match")
617 (replace-match next-replacement nocasify literal))
618 (setq done t replaced t))
619 ((eq def 'act-and-exit)
621 (replace-match next-replacement nocasify literal))
622 (setq keep-going nil)
623 (setq done t replaced t))
624 ((eq def 'act-and-show)
627 (replace-match next-replacement nocasify literal)
631 (replace-match next-replacement nocasify literal))
632 (setq done t query-flag nil replaced t))
640 (save-excursion (recursive-edit))))
641 ;; Before we make the replacement,
642 ;; decide whether the search string
643 ;; can match again just after this match.
645 (setq match-again (looking-at search-string))))
646 ((eq def 'delete-and-edit)
647 (delete-region (match-beginning 0) (match-end 0))
650 (save-excursion (recursive-edit))))
652 ;; Note: we do not need to treat `exit-prefix'
653 ;; specially here, since we reread
654 ;; any unrecognized character.
656 (setq this-command 'mode-exited)
657 (setq keep-going nil)
658 (setq unread-command-events
659 (append (listify-key-sequence key)
660 unread-command-events))
662 ;; Record previous position for ^ when we move on.
663 ;; Change markers to numbers in the match data
664 ;; since lots of markers slow down editing.
668 (mapcar (lambda (elt)
670 (prog1 (marker-position elt)
671 (set-marker elt nil))))
674 (if replaced (setq replace-count (1+ replace-count)))))
675 (setq lastrepl (point)))
676 (replace-dehighlight))
677 (or unread-command-events
678 (message "Replaced %d occurrence%s"
680 (if (= replace-count 1) "" "s")))
681 (and keep-going stack)))
683 (defvar query-replace-highlight nil
684 "*Non-nil means to highlight words during query replacement.")
686 (defvar replace-overlay nil)
688 (defun replace-dehighlight ()
691 (delete-overlay replace-overlay)
692 (setq replace-overlay nil))))
694 (defun replace-highlight (start end)
695 (and query-replace-highlight
699 (setq replace-overlay (make-overlay start end))
700 (overlay-put replace-overlay 'face
701 (if (internal-find-face 'query-replace)
702 'query-replace 'region))))
703 (move-overlay replace-overlay start end (current-buffer)))))
705 ;;; replace.el ends here