1 ;;; replace.el --- replace commands for Emacs.
3 ;; Copyright (C) 1985, 1986, 1987, 1992 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 (defconst case-replace t
"\
24 *Non-nil means query-replace should preserve case in replacements.")
26 (defvar query-replace-history nil
)
28 (defun query-replace-read-args (string)
30 (setq from
(read-from-minibuffer (format "%s: " string
)
32 'query-replace-history
))
33 (setq to
(read-from-minibuffer (format "%s %s with: " string from
)
35 'query-replace-history
))
36 (list from to current-prefix-arg
)))
38 (defun query-replace (from-string to-string
&optional arg
)
39 "Replace some occurrences of FROM-STRING with TO-STRING.
40 As each match is found, the user must type a character saying
41 what to do with it. For directions, type \\[help-command] at that time.
43 Preserves case in each replacement if case-replace and case-fold-search
44 are non-nil and FROM-STRING has no uppercase letters.
45 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
46 only matches surrounded by word boundaries."
47 (interactive (query-replace-read-args "Query replace"))
48 (perform-replace from-string to-string t nil arg
)
50 (define-key esc-map
"%" 'query-replace
)
52 (defun query-replace-regexp (regexp to-string
&optional arg
)
53 "Replace some things after point matching REGEXP with TO-STRING.
54 As each match is found, the user must type a character saying
55 what to do with it. For directions, type \\[help-command] at that time.
57 Preserves case in each replacement if case-replace and case-fold-search
58 are non-nil and REGEXP has no uppercase letters.
59 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
60 only matches surrounded by word boundaries.
61 In TO-STRING, \\& means insert what matched REGEXP,
62 and \\=\\<n> means insert what matched <n>th \\(...\\) in REGEXP."
63 (interactive (query-replace-read-args "Query replace regexp"))
64 (perform-replace regexp to-string t t arg
)
67 (defun map-query-replace-regexp (regexp to-strings
&optional arg
)
68 "Replace some matches for REGEXP with various strings, in rotation.
69 The second argument TO-STRINGS contains the replacement strings, separated
70 by spaces. This command works like `query-replace-regexp' except
71 that each successive replacement uses the next successive replacement string,
72 wrapping around from the last such string to the first.
74 Non-interactively, TO-STRINGS may be a list of replacement strings.
76 A prefix argument N says to use each replacement string N times
77 before rotating to the next."
80 (setq from
(read-from-minibuffer "Map query replace (regexp): "
82 'query-replace-history
))
83 (setq to
(read-from-minibuffer
84 (format "Query replace %s with (space-separated strings): "
87 'query-replace-history
))
88 (list from to current-prefix-arg
)))
90 (if (listp to-strings
)
91 (setq replacements to-strings
)
92 (while (/= (length to-strings
) 0)
93 (if (string-match " " to-strings
)
96 (list (substring to-strings
0
97 (string-match " " to-strings
))))
98 to-strings
(substring to-strings
99 (1+ (string-match " " to-strings
))))
100 (setq replacements
(append replacements
(list to-strings
))
102 (perform-replace regexp replacements t t nil arg
))
105 (defun replace-string (from-string to-string
&optional delimited
)
106 "Replace occurrences of FROM-STRING with TO-STRING.
107 Preserve case in each match if `case-replace' and `case-fold-search'
108 are non-nil and FROM-STRING has no uppercase letters.
109 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
110 only matches surrounded by word boundaries.
112 This function is usually the wrong thing to use in a Lisp program.
113 What you probably want is a loop like this:
114 (while (search-forward OLD-STRING nil t)
115 (replace-match REPLACEMENT nil t))
116 which will run faster and will not set the mark or print anything."
117 (interactive (query-replace-read-args "Replace string"))
118 (perform-replace from-string to-string nil nil delimited
)
121 (defun replace-regexp (regexp to-string
&optional delimited
)
122 "Replace things after point matching REGEXP with TO-STRING.
123 Preserve case in each match if case-replace and case-fold-search
124 are non-nil and REGEXP has no uppercase letters.
125 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
126 only matches surrounded by word boundaries.
127 In TO-STRING, \\& means insert what matched REGEXP,
128 and \\=\\<n> means insert what matched <n>th \\(...\\) in REGEXP.
130 This function is usually the wrong thing to use in a Lisp program.
131 What you probably want is a loop like this:
132 (while (re-search-forward REGEXP nil t)
133 (replace-match REPLACEMENT nil nil))
134 which will run faster and will not set the mark or print anything."
135 (interactive (query-replace-read-args "Replace regexp"))
136 (perform-replace regexp to-string nil t delimited
)
139 (fset 'delete-non-matching-lines
'keep-lines
)
140 (defun keep-lines (regexp)
141 "Delete all lines except those containing matches for REGEXP.
142 A match split across lines preserves all the lines it lies in.
143 Applies to all lines after point."
144 (interactive "sKeep lines (containing match for regexp): ")
146 (or (bolp) (forward-line 1))
147 (let ((start (point)))
149 ;; Start is first char not preserved by previous match.
150 (if (not (re-search-forward regexp nil
'move
))
151 (delete-region start
(point-max))
152 (let ((end (save-excursion (goto-char (match-beginning 0))
155 ;; Now end is first char preserved by the new match.
157 (delete-region start end
))))
158 (setq start
(save-excursion (forward-line 1)
160 ;; If the match was empty, avoid matching again at same place.
161 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
162 (forward-char 1))))))
164 (fset 'delete-matching-lines
'flush-lines
)
165 (defun flush-lines (regexp)
166 "Delete lines containing matches for REGEXP.
167 If a match is split across lines, all the lines it lies in are deleted.
168 Applies to lines after point."
169 (interactive "sFlush lines (containing match for regexp): ")
171 (while (and (not (eobp))
172 (re-search-forward regexp nil t
))
173 (delete-region (save-excursion (goto-char (match-beginning 0))
176 (progn (forward-line 1) (point))))))
178 (fset 'count-matches
'how-many
)
179 (defun how-many (regexp)
180 "Print number of matches for REGEXP following point."
181 (interactive "sHow many matches for (regexp): ")
182 (let ((count 0) opoint
)
184 (while (and (not (eobp))
185 (progn (setq opoint
(point))
186 (re-search-forward regexp nil t
)))
187 (if (= opoint
(point))
189 (setq count
(1+ count
))))
190 (message "%d occurrences" count
))))
192 (defvar occur-mode-map
())
195 (setq occur-mode-map
(make-sparse-keymap))
196 (define-key occur-mode-map
"\C-c\C-c" 'occur-mode-goto-occurrence
))
198 (defvar occur-buffer nil
)
199 (defvar occur-nlines nil
)
200 (defvar occur-pos-list nil
)
201 (defvar occur-last-string
"")
204 "Major mode for output from \\[occur].
205 Move point to one of the occurrences in this buffer,
206 then use \\[occur-mode-goto-occurrence] to go to the same occurrence
207 in the buffer that the occurrences were found in.
209 (kill-all-local-variables)
210 (use-local-map occur-mode-map
)
211 (setq major-mode
'occur-mode
)
212 (setq mode-name
"Occur")
213 (make-local-variable 'occur-buffer
)
214 (make-local-variable 'occur-nlines
)
215 (make-local-variable 'occur-pos-list
))
217 (defun occur-mode-goto-occurrence ()
218 "Go to the line this occurrence was found in, in the buffer it was found in."
220 (if (or (null occur-buffer
)
221 (null (buffer-name occur-buffer
)))
223 (setq occur-buffer nil
225 (error "Buffer in which occurrences were found is deleted")))
226 (let* ((occur-number (save-excursion
228 (/ (1- (count-lines (point-min)
232 (cond ((< occur-nlines
0)
235 (+ 2 (* 2 occur-nlines
)))
237 (pos (nth occur-number occur-pos-list
)))
238 (pop-to-buffer occur-buffer
)
239 (goto-char (marker-position pos
))))
241 (defvar list-matching-lines-default-context-lines
0
242 "*Default number of context lines to include around a `list-matching-lines'
243 match. A negative number means to include that many lines before the match.
244 A positive number means to include that many lines both before and after.")
246 (fset 'list-matching-lines
'occur
)
248 (defun occur (regexp &optional nlines
)
249 "Show all lines in the current buffer containing a match for REGEXP.
250 Interactively, REGEXP defaults to the last REGEXP
251 used interactively with \\[occur].
253 If a match spreads across multiple lines, all those lines are shown.
255 Each line is displayed with NLINES lines before and after, or -NLINES
256 before if NLINES is negative.
257 NLINES defaults to `list-matching-lines-default-context-lines'.
258 Interactively it is the prefix arg.
260 The lines are shown in a buffer named *Occur*.
261 It serves as a menu to find any of the occurrences in this buffer.
262 \\[describe-mode] in that buffer will explain how."
263 (interactive (list (setq occur-last-string
264 (read-string "List lines matching regexp: "
267 (setq nlines
(if nlines
(prefix-numeric-value nlines
)
268 list-matching-lines-default-context-lines
))
270 (buffer (current-buffer))
272 (prevpos (point-min))
273 (final-context-start (make-marker)))
275 ;;; (beginning-of-line)
276 ;;; (setq linenum (1+ (count-lines (point-min) (point))))
277 ;;; (setq prevpos (point)))
278 (with-output-to-temp-buffer "*Occur*"
280 (set-buffer standard-output
)
281 (insert "Lines matching ")
283 (insert " in buffer " (buffer-name buffer
) ?. ?
\n)
285 (setq occur-buffer buffer
)
286 (setq occur-nlines nlines
)
287 (setq occur-pos-list
()))
288 (if (eq buffer standard-output
)
289 (goto-char (point-max)))
291 (beginning-of-buffer)
292 ;; Find next match, but give up if prev match was at end of buffer.
293 (while (and (not (= prevpos
(point-max)))
294 (re-search-forward regexp nil t
))
295 (goto-char (match-beginning 0))
297 (setq linenum
(+ linenum
(count-lines prevpos
(point))))
298 (setq prevpos
(point))
299 (goto-char (match-end 0))
300 (let* ((start (save-excursion
301 (goto-char (match-beginning 0))
302 (forward-line (if (< nlines
0) nlines
(- nlines
)))
305 (goto-char (match-end 0))
307 (forward-line (1+ nlines
))
310 (tag (format "%3d" linenum
))
311 (empty (make-string (length tag
) ?\
))
314 (setq tem
(make-marker))
315 (set-marker tem
(point))
316 (set-buffer standard-output
)
317 (setq occur-pos-list
(cons tem occur-pos-list
))
318 (or first
(zerop nlines
)
319 (insert "--------\n"))
321 (insert-buffer-substring buffer start end
)
322 (backward-char (- end start
))
328 (let ((this-linenum linenum
))
329 (set-marker final-context-start
330 (+ (point) (- (match-end 0) (match-beginning 0))))
331 (while (< (point) final-context-start
)
333 (setq tag
(format "%3d" this-linenum
)))
337 (setq this-linenum
(1+ this-linenum
))))
338 (while (< tem nlines
)
341 (setq tem
(1+ tem
))))
343 (set-buffer standard-output
)
344 ;; Put positions in increasing order to go with buffer.
345 (setq occur-pos-list
(nreverse occur-pos-list
))
347 (message "%d matching lines." (length occur-pos-list
)))))))
349 (defconst query-replace-help
350 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
351 ESC or `q' to exit, Period to replace one match and exit,
352 Comma to replace but not move point immediately,
353 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
354 C-w to delete match and recursive edit,
355 C-l to clear the screen, redisplay, and offer same replacement again,
356 ! to replace all remaining matches with no more questions,
357 ^ to move point back to previous match."
358 "Help message while in query-replace")
360 (defun perform-replace (from-string replacements
361 query-flag regexp-flag delimited-flag
362 &optional repeat-count
)
363 "Subroutine of `query-replace'. Its complexity handles interactive queries.
364 Don't use this in your own program unless you want to query and set the mark
365 just as `query-replace' does. Instead, write a simple loop like this:
366 (while (re-search-forward \"foo[ \t]+bar\" nil t)
367 (replace-match \"foobar\" nil nil))
368 which will run faster and do exactly what you probably want."
369 (let ((nocasify (not (and case-fold-search case-replace
370 (string-equal from-string
371 (downcase from-string
)))))
372 (literal (not regexp-flag
))
373 (search-function (if regexp-flag
're-search-forward
'search-forward
))
374 (search-string from-string
)
375 (real-match-data nil
) ; the match data for the current match
376 (next-replacement nil
)
377 (replacement-index 0)
380 (next-rotate-count 0)
382 (lastrepl nil
) ;Position after last match considered.
384 (if (stringp replacements
)
385 (setq next-replacement replacements
)
386 (or repeat-count
(setq repeat-count
1)))
388 (setq search-function
're-search-forward
389 search-string
(concat "\\b"
390 (if regexp-flag from-string
391 (regexp-quote from-string
))
395 (while (and keep-going
397 (funcall search-function search-string nil t
)
398 ;; If the search string matches immediately after
399 ;; the previous match, but it did not match there
400 ;; before the replacement was done, ignore the match.
401 (if (or (eq lastrepl
(point))
403 (eq lastrepl
(match-beginning 0))
407 ;; Don't replace the null string
408 ;; right after end of previous replacement.
410 (funcall search-function search-string nil t
))
413 ;; Save the data associated with the real match.
414 (setq real-match-data
(match-data))
416 ;; Before we make the replacement, decide whether the search string
417 ;; can match again just after this match.
419 (setq match-again
(looking-at search-string
)))
420 ;; If time for a change, advance to next replacement string.
421 (if (and (listp replacements
)
422 (= next-rotate-count replace-count
))
424 (setq next-rotate-count
425 (+ next-rotate-count repeat-count
))
426 (setq next-replacement
(nth replacement-index replacements
))
427 (setq replacement-index
(%
(1+ replacement-index
) (length replacements
)))))
430 (store-match-data real-match-data
)
431 (replace-match next-replacement nocasify literal
)
432 (setq replace-count
(1+ replace-count
)))
434 (let (done replaced char
)
437 '(concat "Query replacing "
438 (if regexp-flag
"regexp " "")
439 from-string
" with " next-replacement
".\n\n"
440 (substitute-command-keys query-replace-help
))))
441 (setq char help-char
)
442 (while (or (not (numberp char
)) (= char help-char
))
443 (message "Query replacing %s with %s: " from-string next-replacement
)
444 (setq char
(read-event))
445 (if (and (numberp char
) (= char ??
))
446 (setq unread-command-events
(list help-char
)
448 ;; Restore the match data while we process the command.
449 (store-match-data real-match-data
)
450 (cond ((or (= char ?\e
)
452 (setq keep-going nil
)
455 (let ((elt (car stack
)))
456 (goto-char (car elt
))
457 (setq replaced
(eq t
(cdr elt
)))
459 (store-match-data (cdr elt
)))
460 (setq stack
(cdr stack
))))
464 (replace-match next-replacement nocasify literal
))
465 (setq done t replaced t
))
468 (replace-match next-replacement nocasify literal
))
469 (setq keep-going nil
)
470 (setq done t replaced t
))
474 (replace-match next-replacement nocasify literal
)
478 (replace-match next-replacement nocasify literal
))
479 (setq done t query-flag nil replaced t
))
488 (save-excursion (recursive-edit))))
489 ;; Before we make the replacement,
490 ;; decide whether the search string
491 ;; can match again just after this match.
493 (setq match-again
(looking-at search-string
))))
495 (delete-region (match-beginning 0) (match-end 0))
498 (save-excursion (recursive-edit))))
501 (setq keep-going nil
)
502 (setq unread-command-events
(list char
))
504 ;; Record previous position for ^ when we move on.
505 ;; Change markers to numbers in the match data
506 ;; since lots of markers slow down editing.
511 (function (lambda (elt)
513 (marker-position elt
))))
516 (if replaced
(setq replace-count
(1+ replace-count
)))))
517 (setq lastrepl
(point)))
518 (and keep-going stack
)))
520 ;;; replace.el ends here