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
19 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
23 ;; This package supplies the string and regular-expression replace functions
24 ;; documented in the Emacs user's manual.
28 (defconst case-replace t "\
29 *Non-nil means query-replace should preserve case in replacements.")
31 (defvar query-replace-history nil)
33 (defvar query-replace-interactive nil
34 "Non-nil means `query-replace' uses the last search string.
35 That becomes the \"string to replace\".")
37 (defun query-replace-read-args (string regexp-flag)
39 (if query-replace-interactive
40 (setq from (car (if regexp-flag regexp-search-ring search-ring)))
41 (setq from (read-from-minibuffer (format "%s: " string)
43 'query-replace-history)))
44 (setq to (read-from-minibuffer (format "%s %s with: " string from)
46 'query-replace-history))
47 (list from to current-prefix-arg)))
49 (defun query-replace (from-string to-string &optional arg)
50 "Replace some occurrences of FROM-STRING with TO-STRING.
51 As each match is found, the user must type a character saying
52 what to do with it. For directions, type \\[help-command] at that time.
54 If `query-replace-interactive' is non-nil, the last incremental search
55 string is used as FROM-STRING--you don't have to specify it with the
58 Preserves case in each replacement if `case-replace' and `case-fold-search'
59 are non-nil and FROM-STRING has no uppercase letters.
60 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
61 only matches surrounded by word boundaries.
63 To customize possible responses, change the \"bindings\" in `query-replace-map'."
64 (interactive (query-replace-read-args "Query replace" nil))
65 (perform-replace from-string to-string t nil arg)
66 (or unread-command-events (message "Done")))
67 (define-key esc-map "%" 'query-replace)
69 (defun query-replace-regexp (regexp to-string &optional arg)
70 "Replace some things after point matching REGEXP with TO-STRING.
71 As each match is found, the user must type a character saying
72 what to do with it. For directions, type \\[help-command] at that time.
74 If `query-replace-interactive' is non-nil, the last incremental search
75 regexp is used as REGEXP--you don't have to specify it with the
78 Preserves case in each replacement if `case-replace' and `case-fold-search'
79 are non-nil and REGEXP has no uppercase letters.
80 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
81 only matches surrounded by word boundaries.
82 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
83 and `\\=\\N' (where N is a digit) stands for
84 whatever what matched the Nth `\\(...\\)' in REGEXP."
85 (interactive (query-replace-read-args "Query replace regexp" t))
86 (perform-replace regexp to-string t t arg)
87 (or unread-command-events (message "Done")))
89 (defun map-query-replace-regexp (regexp to-strings &optional arg)
90 "Replace some matches for REGEXP with various strings, in rotation.
91 The second argument TO-STRINGS contains the replacement strings, separated
92 by spaces. This command works like `query-replace-regexp' except
93 that each successive replacement uses the next successive replacement string,
94 wrapping around from the last such string to the first.
96 Non-interactively, TO-STRINGS may be a list of replacement strings.
98 If `query-replace-interactive' is non-nil, the last incremental search
99 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
101 A prefix argument N says to use each replacement string N times
102 before rotating to the next."
105 (setq from (if query-replace-interactive
106 (car regexp-search-ring)
107 (read-from-minibuffer "Map query replace (regexp): "
109 'query-replace-history)))
110 (setq to (read-from-minibuffer
111 (format "Query replace %s with (space-separated strings): "
114 'query-replace-history))
115 (list from to current-prefix-arg)))
117 (if (listp to-strings)
118 (setq replacements to-strings)
119 (while (/= (length to-strings) 0)
120 (if (string-match " " to-strings)
123 (list (substring to-strings 0
124 (string-match " " to-strings))))
125 to-strings (substring to-strings
126 (1+ (string-match " " to-strings))))
127 (setq replacements (append replacements (list to-strings))
129 (perform-replace regexp replacements t t nil arg))
130 (or unread-command-events (message "Done")))
132 (defun replace-string (from-string to-string &optional delimited)
133 "Replace occurrences of FROM-STRING with TO-STRING.
134 Preserve case in each match if `case-replace' and `case-fold-search'
135 are non-nil and FROM-STRING has no uppercase letters.
136 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
137 only matches surrounded by word boundaries.
139 If `query-replace-interactive' is non-nil, the last incremental search
140 string is used as FROM-STRING--you don't have to specify it with the
143 This function is usually the wrong thing to use in a Lisp program.
144 What you probably want is a loop like this:
145 (while (search-forward FROM-STRING nil t)
146 (replace-match TO-STRING nil t))
147 which will run faster and will not set the mark or print anything."
148 (interactive (query-replace-read-args "Replace string" nil))
149 (perform-replace from-string to-string nil nil delimited)
150 (or unread-command-events (message "Done")))
152 (defun replace-regexp (regexp to-string &optional delimited)
153 "Replace things after point matching REGEXP with TO-STRING.
154 Preserve case in each match if `case-replace' and `case-fold-search'
155 are non-nil and REGEXP has no uppercase letters.
156 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
157 only matches surrounded by word boundaries.
158 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
159 and `\\=\\N' (where N is a digit) stands for
160 whatever what matched the Nth `\\(...\\)' in REGEXP.
162 If `query-replace-interactive' is non-nil, the last incremental search
163 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
165 This function is usually the wrong thing to use in a Lisp program.
166 What you probably want is a loop like this:
167 (while (re-search-forward REGEXP nil t)
168 (replace-match TO-STRING nil nil))
169 which will run faster and will not set the mark or print anything."
170 (interactive (query-replace-read-args "Replace regexp" t))
171 (perform-replace regexp to-string nil t delimited)
172 (or unread-command-events (message "Done")))
174 (defvar regexp-history nil
175 "History list for some commands that read regular expressions.")
177 (defalias 'delete-non-matching-lines 'keep-lines)
178 (defun keep-lines (regexp)
179 "Delete all lines except those containing matches for REGEXP.
180 A match split across lines preserves all the lines it lies in.
181 Applies to all lines after point."
182 (interactive (list (read-from-minibuffer
183 "Keep lines (containing match for regexp): "
184 nil nil nil 'regexp-history)))
186 (or (bolp) (forward-line 1))
187 (let ((start (point)))
189 ;; Start is first char not preserved by previous match.
190 (if (not (re-search-forward regexp nil 'move))
191 (delete-region start (point-max))
192 (let ((end (save-excursion (goto-char (match-beginning 0))
195 ;; Now end is first char preserved by the new match.
197 (delete-region start end))))
198 (setq start (save-excursion (forward-line 1)
200 ;; If the match was empty, avoid matching again at same place.
201 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
202 (forward-char 1))))))
204 (defalias 'delete-matching-lines 'flush-lines)
205 (defun flush-lines (regexp)
206 "Delete lines containing matches for REGEXP.
207 If a match is split across lines, all the lines it lies in are deleted.
208 Applies to lines after point."
209 (interactive (list (read-from-minibuffer
210 "Flush lines (containing match for regexp): "
211 nil nil nil 'regexp-history)))
213 (while (and (not (eobp))
214 (re-search-forward regexp nil t))
215 (delete-region (save-excursion (goto-char (match-beginning 0))
218 (progn (forward-line 1) (point))))))
220 (defalias 'count-matches 'how-many)
221 (defun how-many (regexp)
222 "Print number of matches for REGEXP following point."
223 (interactive (list (read-from-minibuffer
224 "How many matches for (regexp): "
225 nil nil nil 'regexp-history)))
226 (let ((count 0) opoint)
228 (while (and (not (eobp))
229 (progn (setq opoint (point))
230 (re-search-forward regexp nil t)))
231 (if (= opoint (point))
233 (setq count (1+ count))))
234 (message "%d occurrences" count))))
236 (defvar occur-mode-map ())
239 (setq occur-mode-map (make-sparse-keymap))
240 (define-key occur-mode-map [mouse-2] 'occur-mode-mouse-goto)
241 (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence))
243 (defvar occur-buffer nil)
244 (defvar occur-nlines nil)
245 (defvar occur-pos-list nil)
248 "Major mode for output from \\[occur].
249 Move point to one of the occurrences in this buffer,
250 then use \\[occur-mode-goto-occurrence] to go to the same occurrence
251 in the buffer that the occurrences were found in.
252 Or click \\<occur-mode-map>\\[occur-mode-mouse-goto] on an occurrence line.
254 (kill-all-local-variables)
255 (use-local-map occur-mode-map)
256 (setq major-mode 'occur-mode)
257 (setq mode-name "Occur")
258 (make-local-variable 'occur-buffer)
259 (make-local-variable 'occur-nlines)
260 (make-local-variable 'occur-pos-list)
261 (run-hooks 'occur-mode-hook))
263 (defun occur-mode-mouse-goto (event)
264 "In Occur mode, go to the occurrence whose line you click on."
268 (set-buffer (window-buffer (posn-window (event-end event))))
270 (goto-char (posn-point (event-end event)))
271 (setq pos (occur-mode-find-occurrence))
272 (setq buffer occur-buffer)))
273 (pop-to-buffer buffer)
274 (goto-char (marker-position pos))))
276 (defun occur-mode-find-occurrence ()
277 (if (or (null occur-buffer)
278 (null (buffer-name occur-buffer)))
280 (setq occur-buffer nil
282 (error "Buffer in which occurrences were found is deleted")))
284 (count-lines (point-min)
288 (occur-number (save-excursion
291 (cond ((< occur-nlines 0)
294 (+ 2 (* 2 occur-nlines)))
296 (pos (nth occur-number occur-pos-list)))
298 (error "No occurrence on this line"))
300 (error "No occurrence on this line"))
303 (defun occur-mode-goto-occurrence ()
304 "Go to the occurrence the current line describes."
306 (let ((pos (occur-mode-find-occurrence)))
307 (pop-to-buffer occur-buffer)
308 (goto-char (marker-position pos))))
310 (defvar list-matching-lines-default-context-lines 0
311 "*Default number of context lines to include around a `list-matching-lines'
312 match. A negative number means to include that many lines before the match.
313 A positive number means to include that many lines both before and after.")
315 (defalias 'list-matching-lines 'occur)
317 (defun occur (regexp &optional nlines)
318 "Show all lines in the current buffer containing a match for REGEXP.
320 If a match spreads across multiple lines, all those lines are shown.
322 Each line is displayed with NLINES lines before and after, or -NLINES
323 before if NLINES is negative.
324 NLINES defaults to `list-matching-lines-default-context-lines'.
325 Interactively it is the prefix arg.
327 The lines are shown in a buffer named `*Occur*'.
328 It serves as a menu to find any of the occurrences in this buffer.
329 \\[describe-mode] in that buffer will explain how."
330 (interactive (list (let* ((default (car regexp-history))
332 (read-from-minibuffer
334 (format "List lines matching regexp (default `%s'): " default)
335 "List lines matching regexp: ")
338 (if (> (length input) 0) input
339 (setcar regexp-history default)))
341 (setq nlines (if nlines (prefix-numeric-value nlines)
342 list-matching-lines-default-context-lines))
344 (buffer (current-buffer))
346 (prevpos (point-min))
347 (final-context-start (make-marker)))
349 ;;; (beginning-of-line)
350 ;;; (setq linenum (1+ (count-lines (point-min) (point))))
351 ;;; (setq prevpos (point)))
352 (with-output-to-temp-buffer "*Occur*"
354 (set-buffer standard-output)
355 (insert "Lines matching ")
357 (insert " in buffer " (buffer-name buffer) ?. ?\n)
359 (setq occur-buffer buffer)
360 (setq occur-nlines nlines)
361 (setq occur-pos-list ()))
362 (if (eq buffer standard-output)
363 (goto-char (point-max)))
365 (beginning-of-buffer)
366 ;; Find next match, but give up if prev match was at end of buffer.
367 (while (and (not (= prevpos (point-max)))
368 (re-search-forward regexp nil t))
369 (goto-char (match-beginning 0))
372 (setq linenum (+ linenum (count-lines prevpos (point)))))
373 (setq prevpos (point))
374 (goto-char (match-end 0))
375 (let* ((start (save-excursion
376 (goto-char (match-beginning 0))
377 (forward-line (if (< nlines 0) nlines (- nlines)))
380 (goto-char (match-end 0))
382 (forward-line (1+ nlines))
385 (tag (format "%3d" linenum))
386 (empty (make-string (length tag) ?\ ))
389 (setq tem (make-marker))
390 (set-marker tem (point))
391 (set-buffer standard-output)
392 (setq occur-pos-list (cons tem occur-pos-list))
393 (or first (zerop nlines)
394 (insert "--------\n"))
396 (insert-buffer-substring buffer start end)
397 (backward-char (- end start))
403 (let ((this-linenum linenum))
404 (set-marker final-context-start
405 (+ (point) (- (match-end 0) (match-beginning 0))))
406 (while (< (point) final-context-start)
408 (setq tag (format "%3d" this-linenum)))
410 (put-text-property (save-excursion
416 'mouse-face 'highlight)
419 (setq this-linenum (1+ this-linenum))))
420 (while (< tem nlines)
423 (setq tem (1+ tem))))
425 (set-buffer standard-output)
426 ;; Put positions in increasing order to go with buffer.
427 (setq occur-pos-list (nreverse occur-pos-list))
429 (message "%d matching lines." (length occur-pos-list)))))))
431 ;; It would be nice to use \\[...], but there is no reasonable way
432 ;; to make that display both SPC and Y.
433 (defconst query-replace-help
434 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
435 RET or `q' to exit, Period to replace one match and exit,
436 Comma to replace but not move point immediately,
437 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
438 C-w to delete match and recursive edit,
439 C-l to clear the screen, redisplay, and offer same replacement again,
440 ! to replace all remaining matches with no more questions,
441 ^ to move point back to previous match."
442 "Help message while in query-replace")
444 (defvar query-replace-map (make-sparse-keymap)
445 "Keymap that defines the responses to questions in `query-replace'.
446 The \"bindings\" in this map are not commands; they are answers.
447 The valid answers include `act', `skip', `act-and-show',
448 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
449 `automatic', `backup', and `help'.")
451 (define-key query-replace-map " " 'act)
452 (define-key query-replace-map "\d" 'skip)
453 (define-key query-replace-map [delete] 'skip)
454 (define-key query-replace-map [backspace] 'skip)
455 (define-key query-replace-map "y" 'act)
456 (define-key query-replace-map "n" 'skip)
457 (define-key query-replace-map "," 'act-and-show)
458 (define-key query-replace-map "q" 'exit)
459 (define-key query-replace-map "\r" 'exit)
460 (define-key query-replace-map [return] 'exit)
461 (define-key query-replace-map "." 'act-and-exit)
462 (define-key query-replace-map "\C-r" 'edit)
463 (define-key query-replace-map "\C-w" 'delete-and-edit)
464 (define-key query-replace-map "\C-l" 'recenter)
465 (define-key query-replace-map "!" 'automatic)
466 (define-key query-replace-map "^" 'backup)
467 (define-key query-replace-map "\C-h" 'help)
468 (define-key query-replace-map "?" 'help)
469 (define-key query-replace-map "\C-g" 'quit)
470 (define-key query-replace-map "\C-]" 'quit)
472 (defun perform-replace (from-string replacements
473 query-flag regexp-flag delimited-flag
474 &optional repeat-count map)
475 "Subroutine of `query-replace'. Its complexity handles interactive queries.
476 Don't use this in your own program unless you want to query and set the mark
477 just as `query-replace' does. Instead, write a simple loop like this:
478 (while (re-search-forward \"foo[ \t]+bar\" nil t)
479 (replace-match \"foobar\" nil nil))
480 which will run faster and probably do exactly what you want."
481 (or map (setq map query-replace-map))
482 (let ((nocasify (not (and case-fold-search case-replace
483 (string-equal from-string
484 (downcase from-string)))))
485 (literal (not regexp-flag))
486 (search-function (if regexp-flag 're-search-forward 'search-forward))
487 (search-string from-string)
488 (real-match-data nil) ; the match data for the current match
489 (next-replacement nil)
490 (replacement-index 0)
493 (next-rotate-count 0)
495 (lastrepl nil) ;Position after last match considered.
499 (substitute-command-keys
500 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
501 (if (stringp replacements)
502 (setq next-replacement replacements)
503 (or repeat-count (setq repeat-count 1)))
505 (setq search-function 're-search-forward
506 search-string (concat "\\b"
507 (if regexp-flag from-string
508 (regexp-quote from-string))
513 ;; Loop finding occurrences that perhaps should be replaced.
514 (while (and keep-going
516 (funcall search-function search-string nil t)
517 ;; If the search string matches immediately after
518 ;; the previous match, but it did not match there
519 ;; before the replacement was done, ignore the match.
520 (if (or (eq lastrepl (point))
522 (eq lastrepl (match-beginning 0))
526 ;; Don't replace the null string
527 ;; right after end of previous replacement.
529 (funcall search-function search-string nil t))
532 ;; Save the data associated with the real match.
533 (setq real-match-data (match-data))
535 ;; Before we make the replacement, decide whether the search string
536 ;; can match again just after this match.
538 (setq match-again (looking-at search-string)))
539 ;; If time for a change, advance to next replacement string.
540 (if (and (listp replacements)
541 (= next-rotate-count replace-count))
543 (setq next-rotate-count
544 (+ next-rotate-count repeat-count))
545 (setq next-replacement (nth replacement-index replacements))
546 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
549 (store-match-data real-match-data)
550 (replace-match next-replacement nocasify literal)
551 (setq replace-count (1+ replace-count)))
553 (let (done replaced key def)
554 ;; Loop reading commands until one of them sets done,
555 ;; which means it has finished handling this occurrence.
557 (store-match-data real-match-data)
558 (replace-highlight (match-beginning 0) (match-end 0))
559 (message message from-string next-replacement)
560 (setq key (read-event))
561 (setq key (vector key))
562 (setq def (lookup-key map key))
563 ;; Restore the match data while we process the command.
564 (cond ((eq def 'help)
565 (with-output-to-temp-buffer "*Help*"
567 (concat "Query replacing "
568 (if regexp-flag "regexp " "")
570 next-replacement ".\n\n"
571 (substitute-command-keys
572 query-replace-help)))))
574 (setq keep-going nil)
578 (let ((elt (car stack)))
579 (goto-char (car elt))
580 (setq replaced (eq t (cdr elt)))
582 (store-match-data (cdr elt)))
583 (setq stack (cdr stack)))
584 (message "No previous match")
589 (replace-match next-replacement nocasify literal))
590 (setq done t replaced t))
591 ((eq def 'act-and-exit)
593 (replace-match next-replacement nocasify literal))
594 (setq keep-going nil)
595 (setq done t replaced t))
596 ((eq def 'act-and-show)
599 (replace-match next-replacement nocasify literal)
603 (replace-match next-replacement nocasify literal))
604 (setq done t query-flag nil replaced t))
612 (save-excursion (recursive-edit))))
613 ;; Before we make the replacement,
614 ;; decide whether the search string
615 ;; can match again just after this match.
617 (setq match-again (looking-at search-string))))
618 ((eq def 'delete-and-edit)
619 (delete-region (match-beginning 0) (match-end 0))
622 (save-excursion (recursive-edit))))
625 (setq keep-going nil)
626 (setq unread-command-events
627 (append (listify-key-sequence key)
628 unread-command-events))
630 ;; Record previous position for ^ when we move on.
631 ;; Change markers to numbers in the match data
632 ;; since lots of markers slow down editing.
636 (mapcar (lambda (elt)
638 (prog1 (marker-position elt)
639 (set-marker elt nil))))
642 (if replaced (setq replace-count (1+ replace-count)))))
643 (setq lastrepl (point)))
644 (replace-dehighlight))
645 (and keep-going stack)))
647 (defvar query-replace-highlight nil
648 "*Non-nil means to highlight words during query replacement.")
650 (defvar replace-overlay nil)
652 (defun replace-dehighlight ()
655 (delete-overlay replace-overlay)
656 (setq replace-overlay nil))))
658 (defun replace-highlight (start end)
659 (and query-replace-highlight
663 (setq replace-overlay (make-overlay start end))
664 (overlay-put replace-overlay 'face
665 (if (internal-find-face 'query-replace)
666 'query-replace 'region))))
667 (move-overlay replace-overlay start end (current-buffer)))))
669 ;;; replace.el ends here