1 ;;; replace.el --- replace commands for Emacs.
4 ;; Last-Modified: 09 Jul 1992
6 ;; Copyright (C) 1985, 86, 87, 88, 89, 90, 91, 92 Free Software Foundation, Inc.
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to
22 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
26 (defconst case-replace t
"\
27 *Non-nil means query-replace should preserve case in replacements.")
29 (defun query-replace (from-string to-string
&optional arg
)
30 "Replace some occurrences of FROM-STRING with TO-STRING.
31 As each match is found, the user must type a character saying
32 what to do with it. For directions, type \\[help-command] at that time.
34 Preserves case in each replacement if case-replace and case-fold-search
35 are non-nil and FROM-STRING has no uppercase letters.
36 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
37 only matches surrounded by word boundaries."
38 (interactive "sQuery replace: \nsQuery replace %s with: \nP")
39 (perform-replace from-string to-string t nil arg
)
41 (define-key esc-map
"%" 'query-replace
)
43 (defun query-replace-regexp (regexp to-string
&optional arg
)
44 "Replace some things after point matching REGEXP with TO-STRING.
45 As each match is found, the user must type a character saying
46 what to do with it. For directions, type \\[help-command] at that time.
48 Preserves case in each replacement if case-replace and case-fold-search
49 are non-nil and REGEXP has no uppercase letters.
50 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
51 only matches surrounded by word boundaries.
52 In TO-STRING, \\& means insert what matched REGEXP,
53 and \\=\\<n> means insert what matched <n>th \\(...\\) in REGEXP."
54 (interactive "sQuery replace regexp: \nsQuery replace regexp %s with: \nP")
55 (perform-replace regexp to-string t t arg
)
58 (defun map-query-replace-regexp (regexp to-strings
&optional arg
)
59 "Replace some matches for REGEXP with various strings, in rotation.
60 The second argument TO-STRINGS contains the replacement strings, separated
61 by spaces. This command works like `query-replace-regexp' except
62 that each successive replacement uses the next successive replacement string,
63 wrapping around from the last such string to the first.
65 Non-interactively, TO-STRINGS may be a list of replacement strings.
67 A prefix argument N says to use each replacement string N times
68 before rotating to the next."
69 (interactive "sMap query replace (regexp): \nsQuery replace %s with (space-separated strings): \nP")
71 (if (listp to-strings
)
72 (setq replacements to-strings
)
73 (while (/= (length to-strings
) 0)
74 (if (string-match " " to-strings
)
77 (list (substring to-strings
0
78 (string-match " " to-strings
))))
79 to-strings
(substring to-strings
80 (1+ (string-match " " to-strings
))))
81 (setq replacements
(append replacements
(list to-strings
))
83 (perform-replace regexp replacements t t nil arg
))
86 (defun replace-string (from-string to-string
&optional delimited
)
87 "Replace occurrences of FROM-STRING with TO-STRING.
88 Preserve case in each match if `case-replace' and `case-fold-search'
89 are non-nil and FROM-STRING has no uppercase letters.
90 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
91 only matches surrounded by word boundaries.
93 This function is usually the wrong thing to use in a Lisp program.
94 What you probably want is a loop like this:
95 (while (search-forward OLD-STRING nil t)
96 (replace-match REPLACEMENT nil t))
97 which will run faster and will not set the mark or print anything."
98 (interactive "sReplace string: \nsReplace string %s with: \nP")
99 (perform-replace from-string to-string nil nil delimited
)
102 (defun replace-regexp (regexp to-string
&optional delimited
)
103 "Replace things after point matching REGEXP with TO-STRING.
104 Preserve case in each match if case-replace and case-fold-search
105 are non-nil and REGEXP has no uppercase letters.
106 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
107 only matches surrounded by word boundaries.
108 In TO-STRING, \\& means insert what matched REGEXP,
109 and \\=\\<n> means insert what matched <n>th \\(...\\) in REGEXP.
111 This function is usually the wrong thing to use in a Lisp program.
112 What you probably want is a loop like this:
113 (while (re-search-forward REGEXP nil t)
114 (replace-match REPLACEMENT nil nil))
115 which will run faster and will not set the mark or print anything."
116 (interactive "sReplace regexp: \nsReplace regexp %s with: \nP")
117 (perform-replace regexp to-string nil t delimited
)
120 (fset 'delete-non-matching-lines
'keep-lines
)
121 (defun keep-lines (regexp)
122 "Delete all lines except those containing matches for REGEXP.
123 A match split across lines preserves all the lines it lies in.
124 Applies to all lines after point."
125 (interactive "sKeep lines (containing match for regexp): ")
127 (or (bolp) (forward-line 1))
128 (let ((start (point)))
130 ;; Start is first char not preserved by previous match.
131 (if (not (re-search-forward regexp nil
'move
))
132 (delete-region start
(point-max))
133 (let ((end (save-excursion (goto-char (match-beginning 0))
136 ;; Now end is first char preserved by the new match.
138 (delete-region start end
))))
139 (setq start
(save-excursion (forward-line 1)
141 ;; If the match was empty, avoid matching again at same place.
142 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
143 (forward-char 1))))))
145 (fset 'delete-matching-lines
'flush-lines
)
146 (defun flush-lines (regexp)
147 "Delete lines containing matches for REGEXP.
148 If a match is split across lines, all the lines it lies in are deleted.
149 Applies to lines after point."
150 (interactive "sFlush lines (containing match for regexp): ")
152 (while (and (not (eobp))
153 (re-search-forward regexp nil t
))
154 (delete-region (save-excursion (goto-char (match-beginning 0))
157 (progn (forward-line 1) (point))))))
159 (fset 'count-matches
'how-many
)
160 (defun how-many (regexp)
161 "Print number of matches for REGEXP following point."
162 (interactive "sHow many matches for (regexp): ")
163 (let ((count 0) opoint
)
165 (while (and (not (eobp))
166 (progn (setq opoint
(point))
167 (re-search-forward regexp nil t
)))
168 (if (= opoint
(point))
170 (setq count
(1+ count
))))
171 (message "%d occurrences" count
))))
173 (defvar occur-mode-map
())
176 (setq occur-mode-map
(make-sparse-keymap))
177 (define-key occur-mode-map
"\C-c\C-c" 'occur-mode-goto-occurrence
))
179 (defvar occur-buffer nil
)
180 (defvar occur-nlines nil
)
181 (defvar occur-pos-list nil
)
182 (defvar occur-last-string
"")
185 "Major mode for output from \\[occur].
186 Move point to one of the occurrences in this buffer,
187 then use \\[occur-mode-goto-occurrence] to go to the same occurrence
188 in the buffer that the occurrences were found in.
190 (kill-all-local-variables)
191 (use-local-map occur-mode-map
)
192 (setq major-mode
'occur-mode
)
193 (setq mode-name
"Occur")
194 (make-local-variable 'occur-buffer
)
195 (make-local-variable 'occur-nlines
)
196 (make-local-variable 'occur-pos-list
))
198 (defun occur-mode-goto-occurrence ()
199 "Go to the line this occurrence was found in, in the buffer it was found in."
201 (if (or (null occur-buffer
)
202 (null (buffer-name occur-buffer
)))
204 (setq occur-buffer nil
206 (error "Buffer in which occurrences were found is deleted")))
207 (let* ((occur-number (save-excursion
209 (/ (1- (count-lines (point-min)
213 (cond ((< occur-nlines
0)
216 (+ 2 (* 2 occur-nlines
)))
218 (pos (nth occur-number occur-pos-list
)))
219 (pop-to-buffer occur-buffer
)
220 (goto-char (marker-position pos
))))
222 (defvar list-matching-lines-default-context-lines
0
223 "*Default number of context lines to include around a `list-matching-lines'
224 match. A negative number means to include that many lines before the match.
225 A positive number means to include that many lines both before and after.")
227 (defvar occur-whole-buffer nil
228 "If t, occur operates on whole buffer, otherwise occur starts from point.
231 (fset 'list-matching-lines
'occur
)
233 (defun occur (regexp &optional nlines
)
234 "Show lines containing a match for REGEXP. If the global variable
235 `occur-whole-buffer' is non-nil, the entire buffer is searched, otherwise
236 search begins at point. Interactively, REGEXP defaults to the last REGEXP
237 used interactively with \\[occur].
239 If a match spreads across multiple lines, all those lines are shown.
241 Each line is displayed with NLINES lines before and after, or -NLINES
242 before if NLINES is negative.
243 NLINES defaults to `list-matching-lines-default-context-lines'.
244 Interactively it is the prefix arg.
246 The lines are shown in a buffer named *Occur*.
247 It serves as a menu to find any of the occurrences in this buffer.
248 \\[describe-mode] in that buffer will explain how."
249 (interactive (list (setq occur-last-string
250 (read-string "List lines matching regexp: "
253 (setq nlines
(if nlines
(prefix-numeric-value nlines
)
254 list-matching-lines-default-context-lines
))
256 (buffer (current-buffer))
258 (prevpos (point-min))
259 (final-context-start (make-marker)))
260 (if (not occur-whole-buffer
)
263 (setq linenum
(1+ (count-lines (point-min) (point))))
264 (setq prevpos
(point))))
265 (with-output-to-temp-buffer "*Occur*"
267 (set-buffer standard-output
)
268 (insert "Lines matching ")
270 (insert " in buffer " (buffer-name buffer
) ?. ?
\n)
272 (setq occur-buffer buffer
)
273 (setq occur-nlines nlines
)
274 (setq occur-pos-list
()))
275 (if (eq buffer standard-output
)
276 (goto-char (point-max)))
278 (if occur-whole-buffer
279 (beginning-of-buffer))
280 ;; Find next match, but give up if prev match was at end of buffer.
281 (while (and (not (= prevpos
(point-max)))
282 (re-search-forward regexp nil t
))
283 (goto-char (match-beginning 0))
285 (setq linenum
(+ linenum
(count-lines prevpos
(point))))
286 (setq prevpos
(point))
287 (goto-char (match-end 0))
288 (let* ((start (save-excursion
289 (goto-char (match-beginning 0))
290 (forward-line (if (< nlines
0) nlines
(- nlines
)))
293 (goto-char (match-end 0))
295 (forward-line (1+ nlines
))
298 (tag (format "%3d" linenum
))
299 (empty (make-string (length tag
) ?\
))
302 (setq tem
(make-marker))
303 (set-marker tem
(point))
304 (set-buffer standard-output
)
305 (setq occur-pos-list
(cons tem occur-pos-list
))
306 (or first
(zerop nlines
)
307 (insert "--------\n"))
309 (insert-buffer-substring buffer start end
)
310 (backward-char (- end start
))
316 (let ((this-linenum linenum
))
317 (set-marker final-context-start
318 (+ (point) (- (match-end 0) (match-beginning 0))))
319 (while (< (point) final-context-start
)
321 (setq tag
(format "%3d" this-linenum
)))
325 (setq this-linenum
(1+ this-linenum
))))
326 (while (< tem nlines
)
329 (setq tem
(1+ tem
))))
331 (set-buffer standard-output
)
332 ;; Put positions in increasing order to go with buffer.
333 (setq occur-pos-list
(nreverse occur-pos-list
))
335 (message "%d matching lines." (length occur-pos-list
)))))))
337 (defconst query-replace-help
338 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
339 ESC or `q' to exit, Period to replace one match and exit,
340 Comma to replace but not move point immediately,
341 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
342 C-w to delete match and recursive edit,
343 C-l to clear the screen, redisplay, and offer same replacement again,
344 ! to replace all remaining matches with no more questions,
345 ^ to move point back to previous match."
346 "Help message while in query-replace")
348 (defun perform-replace (from-string replacements
349 query-flag regexp-flag delimited-flag
350 &optional repeat-count
)
351 "Subroutine of `query-replace'. Its complexity handles interactive queries.
352 Don't use this in your own program unless you want to query and set the mark
353 just as `query-replace' does. Instead, write a simple loop like this:
354 (while (re-search-forward \"foo[ \t]+bar\" nil t)
355 (replace-match \"foobar\" nil nil))
356 which will run faster and do exactly what you probably want."
357 (let ((nocasify (not (and case-fold-search case-replace
358 (string-equal from-string
359 (downcase from-string
)))))
360 (literal (not regexp-flag
))
361 (search-function (if regexp-flag
're-search-forward
'search-forward
))
362 (search-string from-string
)
363 (real-match-data nil
) ; the match data for the current match
364 (next-replacement nil
)
365 (replacement-index 0)
368 (next-rotate-count 0)
370 (lastrepl nil
) ;Position after last match considered.
372 (if (stringp replacements
)
373 (setq next-replacement replacements
)
374 (or repeat-count
(setq repeat-count
1)))
376 (setq search-function
're-search-forward
377 search-string
(concat "\\b"
378 (if regexp-flag from-string
379 (regexp-quote from-string
))
383 (while (and keep-going
385 (funcall search-function search-string nil t
)
386 ;; If the search string matches immediately after
387 ;; the previous match, but it did not match there
388 ;; before the replacement was done, ignore the match.
389 (if (or (eq lastrepl
(point))
391 (eq lastrepl
(match-beginning 0))
395 ;; Don't replace the null string
396 ;; right after end of previous replacement.
398 (funcall search-function search-string nil t
))
401 ;; Save the data associated with the real match.
402 (setq real-match-data
(match-data))
404 ;; Before we make the replacement, decide whether the search string
405 ;; can match again just after this match.
407 (setq match-again
(looking-at search-string
)))
408 ;; If time for a change, advance to next replacement string.
409 (if (and (listp replacements
)
410 (= next-rotate-count replace-count
))
412 (setq next-rotate-count
413 (+ next-rotate-count repeat-count
))
414 (setq next-replacement
(nth replacement-index replacements
))
415 (setq replacement-index
(%
(1+ replacement-index
) (length replacements
)))))
418 (store-match-data real-match-data
)
419 (replace-match next-replacement nocasify literal
)
420 (setq replace-count
(1+ replace-count
)))
425 '(concat "Query replacing "
426 (if regexp-flag
"regexp " "")
427 from-string
" with " next-replacement
".\n\n"
428 (substitute-command-keys query-replace-help
))))
429 (setq char help-char
)
430 (while (or (not (numberp char
)) (= char help-char
))
431 (message "Query replacing %s with %s: " from-string next-replacement
)
432 (setq char
(read-event))
433 (if (and (numberp char
) (= char ??
))
434 (setq unread-command-char help-char char help-char
))))
435 ;; Restore the match data while we process the command.
436 (store-match-data real-match-data
)
437 (cond ((or (= char ?\e
)
439 (setq keep-going nil
)
442 (let ((elt (car stack
)))
443 (goto-char (car elt
))
444 (setq replaced
(eq t
(cdr elt
)))
446 (store-match-data (cdr elt
)))
447 (setq stack
(cdr stack
))))
451 (replace-match next-replacement nocasify literal
))
452 (setq done t replaced t
))
455 (replace-match next-replacement nocasify literal
))
456 (setq keep-going nil
)
457 (setq done t replaced t
))
461 (replace-match next-replacement nocasify literal
)
465 (replace-match next-replacement nocasify literal
))
466 (setq done t query-flag nil replaced t
))
475 (save-excursion (recursive-edit))))
476 ;; Before we make the replacement,
477 ;; decide whether the search string
478 ;; can match again just after this match.
480 (setq match-again
(looking-at search-string
))))
482 (delete-region (match-beginning 0) (match-end 0))
485 (save-excursion (recursive-edit))))
488 (setq keep-going nil
)
489 (setq unread-command-char char
)
491 ;; Record previous position for ^ when we move on.
492 ;; Change markers to numbers in the match data
493 ;; since lots of markers slow down editing.
498 (function (lambda (elt)
500 (marker-position elt
))))
503 (if replaced
(setq replace-count
(1+ replace-count
)))))
504 (setq lastrepl
(point)))
505 (and keep-going stack
)))
507 (defun map-query-replace-regexp (regexp to-strings
&optional arg
)
508 "Replace some matches for REGEXP with various strings, in rotation.
509 The second argument TO-STRINGS contains the replacement strings, separated
510 by spaces. This command works like `query-replace-regexp' except
511 that each successive replacement uses the next successive replacement
512 string, wrapping around from the last such string to the first.
514 Non-interactively, TO-STRINGS may be a list of replacement strings.
516 A prefix argument N says to use each replacement string N times
517 before rotating to the next."
518 (interactive "sMap query replace (regexp): \nsQuery replace %s with (space-separated strings): \nP")
520 (if (listp to-strings
)
521 (setq replacements to-strings
)
522 (while (/= (length to-strings
) 0)
523 (if (string-match " " to-strings
)
526 (list (substring to-strings
0
527 (string-match " " to-strings
))))
528 to-strings
(substring to-strings
529 (1+ (string-match " " to-strings
))))
530 (setq replacements
(append replacements
(list to-strings
))
532 (perform-replace regexp replacements t t nil arg
))
535 ;;; replace.el ends here