1 ;;; replace.el --- replace commands for Emacs.
3 ;; Copyright (C) 1985, 86, 87, 88, 89, 90, 91, 92 Free Software Foundation, Inc.
7 ;; This file is part of GNU Emacs.
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING. If not, write to
21 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
25 (defconst case-replace t
"\
26 *Non-nil means query-replace should preserve case in replacements.")
28 (defun query-replace (from-string to-string
&optional arg
)
29 "Replace some occurrences of FROM-STRING with TO-STRING.
30 As each match is found, the user must type a character saying
31 what to do with it. For directions, type \\[help-command] at that time.
33 Preserves case in each replacement if case-replace and case-fold-search
34 are non-nil and FROM-STRING has no uppercase letters.
35 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
36 only matches surrounded by word boundaries."
37 (interactive "sQuery replace: \nsQuery replace %s with: \nP")
38 (perform-replace from-string to-string t nil arg
)
40 (define-key esc-map
"%" 'query-replace
)
42 (defun query-replace-regexp (regexp to-string
&optional arg
)
43 "Replace some things after point matching REGEXP with TO-STRING.
44 As each match is found, the user must type a character saying
45 what to do with it. For directions, type \\[help-command] at that time.
47 Preserves case in each replacement if case-replace and case-fold-search
48 are non-nil and REGEXP has no uppercase letters.
49 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
50 only matches surrounded by word boundaries.
51 In TO-STRING, \\& means insert what matched REGEXP,
52 and \\=\\<n> means insert what matched <n>th \\(...\\) in REGEXP."
53 (interactive "sQuery replace regexp: \nsQuery replace regexp %s with: \nP")
54 (perform-replace regexp to-string t t arg
)
57 (defun map-query-replace-regexp (regexp to-strings
&optional arg
)
58 "Replace some matches for REGEXP with various strings, in rotation.
59 The second argument TO-STRINGS contains the replacement strings, separated
60 by spaces. This command works like `query-replace-regexp' except
61 that each successive replacement uses the next successive replacement string,
62 wrapping around from the last such string to the first.
64 Non-interactively, TO-STRINGS may be a list of replacement strings.
66 A prefix argument N says to use each replacement string N times
67 before rotating to the next."
68 (interactive "sMap query replace (regexp): \nsQuery replace %s with (space-separated strings): \nP")
70 (if (listp to-strings
)
71 (setq replacements to-strings
)
72 (while (/= (length to-strings
) 0)
73 (if (string-match " " to-strings
)
76 (list (substring to-strings
0
77 (string-match " " to-strings
))))
78 to-strings
(substring to-strings
79 (1+ (string-match " " to-strings
))))
80 (setq replacements
(append replacements
(list to-strings
))
82 (perform-replace regexp replacements t t nil arg
))
85 (defun replace-string (from-string to-string
&optional delimited
)
86 "Replace occurrences of FROM-STRING with TO-STRING.
87 Preserve case in each match if `case-replace' and `case-fold-search'
88 are non-nil and FROM-STRING has no uppercase letters.
89 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
90 only matches surrounded by word boundaries.
92 This function is usually the wrong thing to use in a Lisp program.
93 What you probably want is a loop like this:
94 (while (search-forward OLD-STRING nil t)
95 (replace-match REPLACEMENT nil t))
96 which will run faster and will not set the mark or print anything."
97 (interactive "sReplace string: \nsReplace string %s with: \nP")
98 (perform-replace from-string to-string nil nil delimited
)
101 (defun replace-regexp (regexp to-string
&optional delimited
)
102 "Replace things after point matching REGEXP with TO-STRING.
103 Preserve case in each match if case-replace and case-fold-search
104 are non-nil and REGEXP has no uppercase letters.
105 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
106 only matches surrounded by word boundaries.
107 In TO-STRING, \\& means insert what matched REGEXP,
108 and \\=\\<n> means insert what matched <n>th \\(...\\) in REGEXP.
110 This function is usually the wrong thing to use in a Lisp program.
111 What you probably want is a loop like this:
112 (while (re-search-forward REGEXP nil t)
113 (replace-match REPLACEMENT nil nil))
114 which will run faster and will not set the mark or print anything."
115 (interactive "sReplace regexp: \nsReplace regexp %s with: \nP")
116 (perform-replace regexp to-string nil t delimited
)
119 (fset 'delete-non-matching-lines
'keep-lines
)
120 (defun keep-lines (regexp)
121 "Delete all lines except those containing matches for REGEXP.
122 A match split across lines preserves all the lines it lies in.
123 Applies to all lines after point."
124 (interactive "sKeep lines (containing match for regexp): ")
126 (or (bolp) (forward-line 1))
127 (let ((start (point)))
129 ;; Start is first char not preserved by previous match.
130 (if (not (re-search-forward regexp nil
'move
))
131 (delete-region start
(point-max))
132 (let ((end (save-excursion (goto-char (match-beginning 0))
135 ;; Now end is first char preserved by the new match.
137 (delete-region start end
))))
138 (setq start
(save-excursion (forward-line 1)
140 ;; If the match was empty, avoid matching again at same place.
141 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
142 (forward-char 1))))))
144 (fset 'delete-matching-lines
'flush-lines
)
145 (defun flush-lines (regexp)
146 "Delete lines containing matches for REGEXP.
147 If a match is split across lines, all the lines it lies in are deleted.
148 Applies to lines after point."
149 (interactive "sFlush lines (containing match for regexp): ")
151 (while (and (not (eobp))
152 (re-search-forward regexp nil t
))
153 (delete-region (save-excursion (goto-char (match-beginning 0))
156 (progn (forward-line 1) (point))))))
158 (fset 'count-matches
'how-many
)
159 (defun how-many (regexp)
160 "Print number of matches for REGEXP following point."
161 (interactive "sHow many matches for (regexp): ")
162 (let ((count 0) opoint
)
164 (while (and (not (eobp))
165 (progn (setq opoint
(point))
166 (re-search-forward regexp nil t
)))
167 (if (= opoint
(point))
169 (setq count
(1+ count
))))
170 (message "%d occurrences" count
))))
172 (defvar occur-mode-map
())
175 (setq occur-mode-map
(make-sparse-keymap))
176 (define-key occur-mode-map
"\C-c\C-c" 'occur-mode-goto-occurrence
))
178 (defvar occur-buffer nil
)
179 (defvar occur-nlines nil
)
180 (defvar occur-pos-list nil
)
181 (defvar occur-last-string
"")
184 "Major mode for output from \\[occur].
185 Move point to one of the occurrences in this buffer,
186 then use \\[occur-mode-goto-occurrence] to go to the same occurrence
187 in the buffer that the occurrences were found in.
189 (kill-all-local-variables)
190 (use-local-map occur-mode-map
)
191 (setq major-mode
'occur-mode
)
192 (setq mode-name
"Occur")
193 (make-local-variable 'occur-buffer
)
194 (make-local-variable 'occur-nlines
)
195 (make-local-variable 'occur-pos-list
))
197 (defun occur-mode-goto-occurrence ()
198 "Go to the line this occurrence was found in, in the buffer it was found in."
200 (if (or (null occur-buffer
)
201 (null (buffer-name occur-buffer
)))
203 (setq occur-buffer nil
205 (error "Buffer in which occurrences were found is deleted")))
206 (let* ((occur-number (save-excursion
208 (/ (1- (count-lines (point-min)
212 (cond ((< occur-nlines
0)
215 (+ 2 (* 2 occur-nlines
)))
217 (pos (nth occur-number occur-pos-list
)))
218 (pop-to-buffer occur-buffer
)
219 (goto-char (marker-position pos
))))
221 (defvar list-matching-lines-default-context-lines
0
222 "*Default number of context lines to include around a `list-matching-lines'
223 match. A negative number means to include that many lines before the match.
224 A positive number means to include that many lines both before and after.")
226 (defvar occur-whole-buffer nil
227 "If t, occur operates on whole buffer, otherwise occur starts from point.
230 (fset 'list-matching-lines
'occur
)
232 (defun occur (regexp &optional nlines
)
233 "Show lines containing a match for REGEXP. If the global variable
234 `occur-whole-buffer' is non-nil, the entire buffer is searched, otherwise
235 search begins at point. Interactively, REGEXP defaults to the last REGEXP
236 used interactively with \\[occur].
238 If a match spreads across multiple lines, all those lines are shown.
240 Each line is displayed with NLINES lines before and after, or -NLINES
241 before if NLINES is negative.
242 NLINES defaults to `list-matching-lines-default-context-lines'.
243 Interactively it is the prefix arg.
245 The lines are shown in a buffer named *Occur*.
246 It serves as a menu to find any of the occurrences in this buffer.
247 \\[describe-mode] in that buffer will explain how."
248 (interactive (list (setq occur-last-string
249 (read-string "List lines matching regexp: "
252 (setq nlines
(if nlines
(prefix-numeric-value nlines
)
253 list-matching-lines-default-context-lines
))
255 (buffer (current-buffer))
257 (prevpos (point-min))
258 (final-context-start (make-marker)))
259 (if (not occur-whole-buffer
)
262 (setq linenum
(1+ (count-lines (point-min) (point))))
263 (setq prevpos
(point))))
264 (with-output-to-temp-buffer "*Occur*"
266 (set-buffer standard-output
)
267 (insert "Lines matching ")
269 (insert " in buffer " (buffer-name buffer
) ?. ?
\n)
271 (setq occur-buffer buffer
)
272 (setq occur-nlines nlines
)
273 (setq occur-pos-list
()))
274 (if (eq buffer standard-output
)
275 (goto-char (point-max)))
277 (if occur-whole-buffer
278 (beginning-of-buffer))
279 ;; Find next match, but give up if prev match was at end of buffer.
280 (while (and (not (= prevpos
(point-max)))
281 (re-search-forward regexp nil t
))
282 (goto-char (match-beginning 0))
284 (setq linenum
(+ linenum
(count-lines prevpos
(point))))
285 (setq prevpos
(point))
286 (goto-char (match-end 0))
287 (let* ((start (save-excursion
288 (goto-char (match-beginning 0))
289 (forward-line (if (< nlines
0) nlines
(- nlines
)))
292 (goto-char (match-end 0))
294 (forward-line (1+ nlines
))
297 (tag (format "%3d" linenum
))
298 (empty (make-string (length tag
) ?\
))
301 (setq tem
(make-marker))
302 (set-marker tem
(point))
303 (set-buffer standard-output
)
304 (setq occur-pos-list
(cons tem occur-pos-list
))
305 (or first
(zerop nlines
)
306 (insert "--------\n"))
308 (insert-buffer-substring buffer start end
)
309 (backward-char (- end start
))
315 (let ((this-linenum linenum
))
316 (set-marker final-context-start
317 (+ (point) (- (match-end 0) (match-beginning 0))))
318 (while (< (point) final-context-start
)
320 (setq tag
(format "%3d" this-linenum
)))
324 (setq this-linenum
(1+ this-linenum
))))
325 (while (< tem nlines
)
328 (setq tem
(1+ tem
))))
330 (set-buffer standard-output
)
331 ;; Put positions in increasing order to go with buffer.
332 (setq occur-pos-list
(nreverse occur-pos-list
))
334 (message "%d matching lines." (length occur-pos-list
)))))))
336 (defconst query-replace-help
337 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
338 ESC or `q' to exit, Period to replace one match and exit,
339 Comma to replace but not move point immediately,
340 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
341 C-w to delete match and recursive edit,
342 C-l to clear the screen, redisplay, and offer same replacement again,
343 ! to replace all remaining matches with no more questions,
344 ^ to move point back to previous match."
345 "Help message while in query-replace")
347 (defun perform-replace (from-string replacements
348 query-flag regexp-flag delimited-flag
349 &optional repeat-count
)
350 "Subroutine of `query-replace'. Its complexity handles interactive queries.
351 Don't use this in your own program unless you want to query and set the mark
352 just as `query-replace' does. Instead, write a simple loop like this:
353 (while (re-search-forward \"foo[ \t]+bar\" nil t)
354 (replace-match \"foobar\" nil nil))
355 which will run faster and do exactly what you probably want."
356 (let ((nocasify (not (and case-fold-search case-replace
357 (string-equal from-string
358 (downcase from-string
)))))
359 (literal (not regexp-flag
))
360 (search-function (if regexp-flag
're-search-forward
'search-forward
))
361 (search-string from-string
)
362 (real-match-data nil
) ; the match data for the current match
363 (next-replacement nil
)
364 (replacement-index 0)
367 (next-rotate-count 0)
369 (lastrepl nil
) ;Position after last match considered.
371 (if (stringp replacements
)
372 (setq next-replacement replacements
)
373 (or repeat-count
(setq repeat-count
1)))
375 (setq search-function
're-search-forward
376 search-string
(concat "\\b"
377 (if regexp-flag from-string
378 (regexp-quote from-string
))
382 (while (and keep-going
384 (funcall search-function search-string nil t
)
385 ;; If the search string matches immediately after
386 ;; the previous match, but it did not match there
387 ;; before the replacement was done, ignore the match.
388 (if (or (eq lastrepl
(point))
390 (eq lastrepl
(match-beginning 0))
394 ;; Don't replace the null string
395 ;; right after end of previous replacement.
397 (funcall search-function search-string nil t
))
400 ;; Save the data associated with the real match.
401 (setq real-match-data
(match-data))
403 ;; Before we make the replacement, decide whether the search string
404 ;; can match again just after this match.
406 (setq match-again
(looking-at search-string
)))
407 ;; If time for a change, advance to next replacement string.
408 (if (and (listp replacements
)
409 (= next-rotate-count replace-count
))
411 (setq next-rotate-count
412 (+ next-rotate-count repeat-count
))
413 (setq next-replacement
(nth replacement-index replacements
))
414 (setq replacement-index
(%
(1+ replacement-index
) (length replacements
)))))
417 (store-match-data real-match-data
)
418 (replace-match next-replacement nocasify literal
)
419 (setq replace-count
(1+ replace-count
)))
424 '(concat "Query replacing "
425 (if regexp-flag
"regexp " "")
426 from-string
" with " next-replacement
".\n\n"
427 (substitute-command-keys query-replace-help
))))
428 (setq char help-char
)
429 (while (or (not (numberp char
)) (= char help-char
))
430 (message "Query replacing %s with %s: " from-string next-replacement
)
431 (setq char
(read-event))
432 (if (and (numberp char
) (= char ??
))
433 (setq unread-command-char help-char char help-char
))))
434 ;; Restore the match data while we process the command.
435 (store-match-data real-match-data
)
436 (cond ((or (= char ?\e
)
438 (setq keep-going nil
)
441 (let ((elt (car stack
)))
442 (goto-char (car elt
))
443 (setq replaced
(eq t
(cdr elt
)))
445 (store-match-data (cdr elt
)))
446 (setq stack
(cdr stack
))))
450 (replace-match next-replacement nocasify literal
))
451 (setq done t replaced t
))
454 (replace-match next-replacement nocasify literal
))
455 (setq keep-going nil
)
456 (setq done t replaced t
))
460 (replace-match next-replacement nocasify literal
)
464 (replace-match next-replacement nocasify literal
))
465 (setq done t query-flag nil replaced t
))
474 (save-excursion (recursive-edit))))
475 ;; Before we make the replacement,
476 ;; decide whether the search string
477 ;; can match again just after this match.
479 (setq match-again
(looking-at search-string
))))
481 (delete-region (match-beginning 0) (match-end 0))
484 (save-excursion (recursive-edit))))
487 (setq keep-going nil
)
488 (setq unread-command-char char
)
490 ;; Record previous position for ^ when we move on.
491 ;; Change markers to numbers in the match data
492 ;; since lots of markers slow down editing.
497 (function (lambda (elt)
499 (marker-position elt
))))
502 (if replaced
(setq replace-count
(1+ replace-count
)))))
503 (setq lastrepl
(point)))
504 (and keep-going stack
)))
506 (defun map-query-replace-regexp (regexp to-strings
&optional arg
)
507 "Replace some matches for REGEXP with various strings, in rotation.
508 The second argument TO-STRINGS contains the replacement strings, separated
509 by spaces. This command works like `query-replace-regexp' except
510 that each successive replacement uses the next successive replacement
511 string, wrapping around from the last such string to the first.
513 Non-interactively, TO-STRINGS may be a list of replacement strings.
515 A prefix argument N says to use each replacement string N times
516 before rotating to the next."
517 (interactive "sMap query replace (regexp): \nsQuery replace %s with (space-separated strings): \nP")
519 (if (listp to-strings
)
520 (setq replacements to-strings
)
521 (while (/= (length to-strings
) 0)
522 (if (string-match " " to-strings
)
525 (list (substring to-strings
0
526 (string-match " " to-strings
))))
527 to-strings
(substring to-strings
528 (1+ (string-match " " to-strings
))))
529 (setq replacements
(append replacements
(list to-strings
))
531 (perform-replace regexp replacements t t nil arg
))
534 ;;; replace.el ends here