1 ;;; replace.el --- replace commands for Emacs.
3 ;; Copyright (C) 1985, 86, 87, 88, 89, 90, 91, 92 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.
22 (defconst case-replace t
"\
23 *Non-nil means query-replace should preserve case in replacements.")
25 (defun query-replace (from-string to-string
&optional arg
)
26 "Replace some occurrences of FROM-STRING with TO-STRING.
27 As each match is found, the user must type a character saying
28 what to do with it. For directions, type \\[help-command] at that time.
30 Preserves case in each replacement if case-replace and case-fold-search
31 are non-nil and FROM-STRING has no uppercase letters.
32 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
33 only matches surrounded by word boundaries."
34 (interactive "sQuery replace: \nsQuery replace %s with: \nP")
35 (perform-replace from-string to-string t nil arg
)
37 (define-key esc-map
"%" 'query-replace
)
39 (defun query-replace-regexp (regexp to-string
&optional arg
)
40 "Replace some things after point matching REGEXP with TO-STRING.
41 As each match is found, the user must type a character saying
42 what to do with it. For directions, type \\[help-command] at that time.
44 Preserves case in each replacement if case-replace and case-fold-search
45 are non-nil and REGEXP has no uppercase letters.
46 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
47 only matches surrounded by word boundaries.
48 In TO-STRING, \\& means insert what matched REGEXP,
49 and \\=\\<n> means insert what matched <n>th \\(...\\) in REGEXP."
50 (interactive "sQuery replace regexp: \nsQuery replace regexp %s with: \nP")
51 (perform-replace regexp to-string t t arg
)
54 (defun map-query-replace-regexp (regexp to-strings
&optional arg
)
55 "Replace some matches for REGEXP with various strings, in rotation.
56 The second argument TO-STRINGS contains the replacement strings, separated
57 by spaces. This command works like `query-replace-regexp' except
58 that each successive replacement uses the next successive replacement string,
59 wrapping around from the last such string to the first.
61 Non-interactively, TO-STRINGS may be a list of replacement strings.
63 A prefix argument N says to use each replacement string N times
64 before rotating to the next."
65 (interactive "sMap query replace (regexp): \nsQuery replace %s with (space-separated strings): \nP")
67 (if (listp to-strings
)
68 (setq replacements to-strings
)
69 (while (/= (length to-strings
) 0)
70 (if (string-match " " to-strings
)
73 (list (substring to-strings
0
74 (string-match " " to-strings
))))
75 to-strings
(substring to-strings
76 (1+ (string-match " " to-strings
))))
77 (setq replacements
(append replacements
(list to-strings
))
79 (perform-replace regexp replacements t t nil arg
))
82 (defun replace-string (from-string to-string
&optional delimited
)
83 "Replace occurrences of FROM-STRING with TO-STRING.
84 Preserve case in each match if `case-replace' and `case-fold-search'
85 are non-nil and FROM-STRING has no uppercase letters.
86 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
87 only matches surrounded by word boundaries.
89 This function is usually the wrong thing to use in a Lisp program.
90 What you probably want is a loop like this:
91 (while (search-forward OLD-STRING nil t)
92 (replace-match REPLACEMENT nil t))
93 which will run faster and will not set the mark or print anything."
94 (interactive "sReplace string: \nsReplace string %s with: \nP")
95 (perform-replace from-string to-string nil nil delimited
)
98 (defun replace-regexp (regexp to-string
&optional delimited
)
99 "Replace things after point matching REGEXP with TO-STRING.
100 Preserve case in each match if case-replace and case-fold-search
101 are non-nil and REGEXP has no uppercase letters.
102 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
103 only matches surrounded by word boundaries.
104 In TO-STRING, \\& means insert what matched REGEXP,
105 and \\=\\<n> means insert what matched <n>th \\(...\\) in REGEXP.
107 This function is usually the wrong thing to use in a Lisp program.
108 What you probably want is a loop like this:
109 (while (re-search-forward REGEXP nil t)
110 (replace-match REPLACEMENT nil nil))
111 which will run faster and will not set the mark or print anything."
112 (interactive "sReplace regexp: \nsReplace regexp %s with: \nP")
113 (perform-replace regexp to-string nil t delimited
)
116 (fset 'delete-non-matching-lines
'keep-lines
)
117 (defun keep-lines (regexp)
118 "Delete all lines except those containing matches for REGEXP.
119 A match split across lines preserves all the lines it lies in.
120 Applies to all lines after point."
121 (interactive "sKeep lines (containing match for regexp): ")
123 (or (bolp) (forward-line 1))
124 (let ((start (point)))
126 ;; Start is first char not preserved by previous match.
127 (if (not (re-search-forward regexp nil
'move
))
128 (delete-region start
(point-max))
129 (let ((end (save-excursion (goto-char (match-beginning 0))
132 ;; Now end is first char preserved by the new match.
134 (delete-region start end
))))
135 (setq start
(save-excursion (forward-line 1)
137 ;; If the match was empty, avoid matching again at same place.
138 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
139 (forward-char 1))))))
141 (fset 'delete-matching-lines
'flush-lines
)
142 (defun flush-lines (regexp)
143 "Delete lines containing matches for REGEXP.
144 If a match is split across lines, all the lines it lies in are deleted.
145 Applies to lines after point."
146 (interactive "sFlush lines (containing match for regexp): ")
148 (while (and (not (eobp))
149 (re-search-forward regexp nil t
))
150 (delete-region (save-excursion (goto-char (match-beginning 0))
153 (progn (forward-line 1) (point))))))
155 (fset 'count-matches
'how-many
)
156 (defun how-many (regexp)
157 "Print number of matches for REGEXP following point."
158 (interactive "sHow many matches for (regexp): ")
159 (let ((count 0) opoint
)
161 (while (and (not (eobp))
162 (progn (setq opoint
(point))
163 (re-search-forward regexp nil t
)))
164 (if (= opoint
(point))
166 (setq count
(1+ count
))))
167 (message "%d occurrences" count
))))
169 (defvar occur-mode-map
())
172 (setq occur-mode-map
(make-sparse-keymap))
173 (define-key occur-mode-map
"\C-c\C-c" 'occur-mode-goto-occurrence
))
175 (defvar occur-buffer nil
)
176 (defvar occur-nlines nil
)
177 (defvar occur-pos-list nil
)
178 (defvar occur-last-string
"")
181 "Major mode for output from \\[occur].
182 Move point to one of the occurrences in this buffer,
183 then use \\[occur-mode-goto-occurrence] to go to the same occurrence
184 in the buffer that the occurrences were found in.
186 (kill-all-local-variables)
187 (use-local-map occur-mode-map
)
188 (setq major-mode
'occur-mode
)
189 (setq mode-name
"Occur")
190 (make-local-variable 'occur-buffer
)
191 (make-local-variable 'occur-nlines
)
192 (make-local-variable 'occur-pos-list
))
194 (defun occur-mode-goto-occurrence ()
195 "Go to the line this occurrence was found in, in the buffer it was found in."
197 (if (or (null occur-buffer
)
198 (null (buffer-name occur-buffer
)))
200 (setq occur-buffer nil
202 (error "Buffer in which occurrences were found is deleted")))
203 (let* ((occur-number (save-excursion
205 (/ (1- (count-lines (point-min)
209 (cond ((< occur-nlines
0)
212 (+ 2 (* 2 occur-nlines
)))
214 (pos (nth occur-number occur-pos-list
)))
215 (pop-to-buffer occur-buffer
)
216 (goto-char (marker-position pos
))))
218 (defvar list-matching-lines-default-context-lines
0
219 "*Default number of context lines to include around a `list-matching-lines'
220 match. A negative number means to include that many lines before the match.
221 A positive number means to include that many lines both before and after.")
223 (defvar occur-whole-buffer nil
224 "If t, occur operates on whole buffer, otherwise occur starts from point.
227 (fset 'list-matching-lines
'occur
)
229 (defun occur (regexp &optional nlines
)
230 "Show lines containing a match for REGEXP. If the global variable
231 `occur-whole-buffer' is non-nil, the entire buffer is searched, otherwise
232 search begins at point. Interactively, REGEXP defaults to the last REGEXP
233 used interactively with \\[occur].
235 If a match spreads across multiple lines, all those lines are shown.
237 Each line is displayed with NLINES lines before and after, or -NLINES
238 before if NLINES is negative.
239 NLINES defaults to `list-matching-lines-default-context-lines'.
240 Interactively it is the prefix arg.
242 The lines are shown in a buffer named *Occur*.
243 It serves as a menu to find any of the occurrences in this buffer.
244 \\[describe-mode] in that buffer will explain how."
245 (interactive (list (setq occur-last-string
246 (read-string "List lines matching regexp: "
249 (setq nlines
(if nlines
(prefix-numeric-value nlines
)
250 list-matching-lines-default-context-lines
))
252 (buffer (current-buffer))
254 (prevpos (point-min))
255 (final-context-start (make-marker)))
256 (if (not occur-whole-buffer
)
259 (setq linenum
(1+ (count-lines (point-min) (point))))
260 (setq prevpos
(point))))
261 (with-output-to-temp-buffer "*Occur*"
263 (set-buffer standard-output
)
264 (insert "Lines matching ")
266 (insert " in buffer " (buffer-name buffer
) ?. ?
\n)
268 (setq occur-buffer buffer
)
269 (setq occur-nlines nlines
)
270 (setq occur-pos-list
()))
271 (if (eq buffer standard-output
)
272 (goto-char (point-max)))
274 (if occur-whole-buffer
275 (beginning-of-buffer))
276 ;; Find next match, but give up if prev match was at end of buffer.
277 (while (and (not (= prevpos
(point-max)))
278 (re-search-forward regexp nil t
))
279 (goto-char (match-beginning 0))
281 (setq linenum
(+ linenum
(count-lines prevpos
(point))))
282 (setq prevpos
(point))
283 (goto-char (match-end 0))
284 (let* ((start (save-excursion
285 (goto-char (match-beginning 0))
286 (forward-line (if (< nlines
0) nlines
(- nlines
)))
289 (goto-char (match-end 0))
291 (forward-line (1+ nlines
))
294 (tag (format "%3d" linenum
))
295 (empty (make-string (length tag
) ?\
))
298 (setq tem
(make-marker))
299 (set-marker tem
(point))
300 (set-buffer standard-output
)
301 (setq occur-pos-list
(cons tem occur-pos-list
))
302 (or first
(zerop nlines
)
303 (insert "--------\n"))
305 (insert-buffer-substring buffer start end
)
306 (backward-char (- end start
))
312 (let ((this-linenum linenum
))
313 (set-marker final-context-start
314 (+ (point) (- (match-end 0) (match-beginning 0))))
315 (while (< (point) final-context-start
)
317 (setq tag
(format "%3d" this-linenum
)))
321 (setq this-linenum
(1+ this-linenum
))))
322 (while (< tem nlines
)
325 (setq tem
(1+ tem
))))
327 (set-buffer standard-output
)
328 ;; Put positions in increasing order to go with buffer.
329 (setq occur-pos-list
(nreverse occur-pos-list
))
331 (message "%d matching lines." (length occur-pos-list
)))))))
333 (defconst query-replace-help
334 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
335 ESC or `q' to exit, Period to replace one match and exit,
336 Comma to replace but not move point immediately,
337 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
338 C-w to delete match and recursive edit,
339 C-l to clear the screen, redisplay, and offer same replacement again,
340 ! to replace all remaining matches with no more questions,
341 ^ to move point back to previous match."
342 "Help message while in query-replace")
344 (defun perform-replace (from-string replacements
345 query-flag regexp-flag delimited-flag
346 &optional repeat-count
)
347 "Subroutine of `query-replace'. Its complexity handles interactive queries.
348 Don't use this in your own program unless you want to query and set the mark
349 just as `query-replace' does. Instead, write a simple loop like this:
350 (while (re-search-forward \"foo[ \t]+bar\" nil t)
351 (replace-match \"foobar\" nil nil))
352 which will run faster and do exactly what you probably want."
353 (let ((nocasify (not (and case-fold-search case-replace
354 (string-equal from-string
355 (downcase from-string
)))))
356 (literal (not regexp-flag
))
357 (search-function (if regexp-flag
're-search-forward
'search-forward
))
358 (search-string from-string
)
359 (real-match-data nil
) ; the match data for the current match
360 (next-replacement nil
)
361 (replacement-index 0)
364 (next-rotate-count 0)
366 (lastrepl nil
) ;Position after last match considered.
368 (if (stringp replacements
)
369 (setq next-replacement replacements
)
370 (or repeat-count
(setq repeat-count
1)))
372 (setq search-function
're-search-forward
373 search-string
(concat "\\b"
374 (if regexp-flag from-string
375 (regexp-quote from-string
))
379 (while (and keep-going
381 (funcall search-function search-string nil t
)
382 ;; If the search string matches immediately after
383 ;; the previous match, but it did not match there
384 ;; before the replacement was done, ignore the match.
385 (if (or (eq lastrepl
(point))
387 (eq lastrepl
(match-beginning 0))
391 ;; Don't replace the null string
392 ;; right after end of previous replacement.
394 (funcall search-function search-string nil t
))
397 ;; Save the data associated with the real match.
398 (setq real-match-data
(match-data))
400 ;; Before we make the replacement, decide whether the search string
401 ;; can match again just after this match.
403 (setq match-again
(looking-at search-string
)))
404 ;; If time for a change, advance to next replacement string.
405 (if (and (listp replacements
)
406 (= next-rotate-count replace-count
))
408 (setq next-rotate-count
409 (+ next-rotate-count repeat-count
))
410 (setq next-replacement
(nth replacement-index replacements
))
411 (setq replacement-index
(%
(1+ replacement-index
) (length replacements
)))))
414 (store-match-data real-match-data
)
415 (replace-match next-replacement nocasify literal
)
416 (setq replace-count
(1+ replace-count
)))
421 '(concat "Query replacing "
422 (if regexp-flag
"regexp " "")
423 from-string
" with " next-replacement
".\n\n"
424 (substitute-command-keys query-replace-help
))))
425 (setq char help-char
)
426 (while (or (not (numberp char
)) (= char help-char
))
427 (message "Query replacing %s with %s: " from-string next-replacement
)
428 (setq char
(read-event))
429 (if (and (numberp char
) (= char ??
))
430 (setq unread-command-char help-char char help-char
))))
431 ;; Restore the match data while we process the command.
432 (store-match-data real-match-data
)
433 (cond ((or (= char ?\e
)
435 (setq keep-going nil
)
438 (let ((elt (car stack
)))
439 (goto-char (car elt
))
440 (setq replaced
(eq t
(cdr elt
)))
442 (store-match-data (cdr elt
)))
443 (setq stack
(cdr stack
))))
447 (replace-match next-replacement nocasify literal
))
448 (setq done t replaced t
))
451 (replace-match next-replacement nocasify literal
))
452 (setq keep-going nil
)
453 (setq done t replaced t
))
457 (replace-match next-replacement nocasify literal
)
461 (replace-match next-replacement nocasify literal
))
462 (setq done t query-flag nil replaced t
))
471 (save-excursion (recursive-edit))))
472 ;; Before we make the replacement,
473 ;; decide whether the search string
474 ;; can match again just after this match.
476 (setq match-again
(looking-at search-string
))))
478 (delete-region (match-beginning 0) (match-end 0))
481 (save-excursion (recursive-edit))))
484 (setq keep-going nil
)
485 (setq unread-command-char char
)
487 ;; Record previous position for ^ when we move on.
488 ;; Change markers to numbers in the match data
489 ;; since lots of markers slow down editing.
494 (function (lambda (elt)
496 (marker-position elt
))))
499 (if replaced
(setq replace-count
(1+ replace-count
)))))
500 (setq lastrepl
(point)))
501 (and keep-going stack
)))
503 (defun map-query-replace-regexp (regexp to-strings
&optional arg
)
504 "Replace some matches for REGEXP with various strings, in rotation.
505 The second argument TO-STRINGS contains the replacement strings, separated
506 by spaces. This command works like `query-replace-regexp' except
507 that each successive replacement uses the next successive replacement
508 string, wrapping around from the last such string to the first.
510 Non-interactively, TO-STRINGS may be a list of replacement strings.
512 A prefix argument N says to use each replacement string N times
513 before rotating to the next."
514 (interactive "sMap query replace (regexp): \nsQuery replace %s with (space-separated strings): \nP")
516 (if (listp to-strings
)
517 (setq replacements to-strings
)
518 (while (/= (length to-strings
) 0)
519 (if (string-match " " to-strings
)
522 (list (substring to-strings
0
523 (string-match " " to-strings
))))
524 to-strings
(substring to-strings
525 (1+ (string-match " " to-strings
))))
526 (setq replacements
(append replacements
(list to-strings
))
528 (perform-replace regexp replacements t t nil arg
))
531 ;;; replace.el ends here