*** empty log message ***
[emacs.git] / lisp / replace.el
blobdf34fe4fabf4dea637238ba376ac98d70178d3c6
1 ;;; replace.el --- replace commands for Emacs.
3 ;; Maintainer: FSF
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)
13 ;; any later version.
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.
24 ;;; Code:
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)
40 (message "Done"))
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)
56 (message "Done"))
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")
70 (let (replacements)
71 (if (listp to-strings)
72 (setq replacements to-strings)
73 (while (/= (length to-strings) 0)
74 (if (string-match " " to-strings)
75 (setq replacements
76 (append replacements
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))
82 to-strings ""))))
83 (perform-replace regexp replacements t t nil arg))
84 (message "Done"))
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)
100 (message "Done"))
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)
118 (message "Done"))
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): ")
126 (save-excursion
127 (or (bolp) (forward-line 1))
128 (let ((start (point)))
129 (while (not (eobp))
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))
134 (beginning-of-line)
135 (point))))
136 ;; Now end is first char preserved by the new match.
137 (if (< start end)
138 (delete-region start end))))
139 (setq start (save-excursion (forward-line 1)
140 (point)))
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): ")
151 (save-excursion
152 (while (and (not (eobp))
153 (re-search-forward regexp nil t))
154 (delete-region (save-excursion (goto-char (match-beginning 0))
155 (beginning-of-line)
156 (point))
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)
164 (save-excursion
165 (while (and (not (eobp))
166 (progn (setq opoint (point))
167 (re-search-forward regexp nil t)))
168 (if (= opoint (point))
169 (forward-char 1)
170 (setq count (1+ count))))
171 (message "%d occurrences" count))))
173 (defvar occur-mode-map ())
174 (if 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 "")
184 (defun occur-mode ()
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.
189 \\{occur-mode-map}"
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."
200 (interactive)
201 (if (or (null occur-buffer)
202 (null (buffer-name occur-buffer)))
203 (progn
204 (setq occur-buffer nil
205 occur-pos-list nil)
206 (error "Buffer in which occurrences were found is deleted")))
207 (let* ((occur-number (save-excursion
208 (beginning-of-line)
209 (/ (1- (count-lines (point-min)
210 (save-excursion
211 (beginning-of-line)
212 (point))))
213 (cond ((< occur-nlines 0)
214 (- 2 occur-nlines))
215 ((> occur-nlines 0)
216 (+ 2 (* 2 occur-nlines)))
217 (t 1)))))
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.
229 default is nil.")
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: "
251 occur-last-string))
252 current-prefix-arg))
253 (setq nlines (if nlines (prefix-numeric-value nlines)
254 list-matching-lines-default-context-lines))
255 (let ((first t)
256 (buffer (current-buffer))
257 (linenum 1)
258 (prevpos (point-min))
259 (final-context-start (make-marker)))
260 (if (not occur-whole-buffer)
261 (save-excursion
262 (beginning-of-line)
263 (setq linenum (1+ (count-lines (point-min) (point))))
264 (setq prevpos (point))))
265 (with-output-to-temp-buffer "*Occur*"
266 (save-excursion
267 (set-buffer standard-output)
268 (insert "Lines matching ")
269 (prin1 regexp)
270 (insert " in buffer " (buffer-name buffer) ?. ?\n)
271 (occur-mode)
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)))
277 (save-excursion
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))
284 (beginning-of-line)
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)))
291 (point)))
292 (end (save-excursion
293 (goto-char (match-end 0))
294 (if (> nlines 0)
295 (forward-line (1+ nlines))
296 (forward-line 1))
297 (point)))
298 (tag (format "%3d" linenum))
299 (empty (make-string (length tag) ?\ ))
300 tem)
301 (save-excursion
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"))
308 (setq first nil)
309 (insert-buffer-substring buffer start end)
310 (backward-char (- end start))
311 (setq tem nlines)
312 (while (> tem 0)
313 (insert empty ?:)
314 (forward-line 1)
315 (setq tem (1- tem)))
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)
320 (if (null tag)
321 (setq tag (format "%3d" this-linenum)))
322 (insert tag ?:)
323 (setq tag nil)
324 (forward-line 1)
325 (setq this-linenum (1+ this-linenum))))
326 (while (< tem nlines)
327 (insert empty ?:)
328 (forward-line 1)
329 (setq tem (1+ tem))))
330 (forward-line 1)))
331 (set-buffer standard-output)
332 ;; Put positions in increasing order to go with buffer.
333 (setq occur-pos-list (nreverse occur-pos-list))
334 (if (interactive-p)
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)
366 (keep-going t)
367 (stack nil)
368 (next-rotate-count 0)
369 (replace-count 0)
370 (lastrepl nil) ;Position after last match considered.
371 (match-after t))
372 (if (stringp replacements)
373 (setq next-replacement replacements)
374 (or repeat-count (setq repeat-count 1)))
375 (if delimited-flag
376 (setq search-function 're-search-forward
377 search-string (concat "\\b"
378 (if regexp-flag from-string
379 (regexp-quote from-string))
380 "\\b")))
381 (push-mark)
382 (undo-boundary)
383 (while (and keep-going
384 (not (eobp))
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))
390 (and regexp-flag
391 (eq lastrepl (match-beginning 0))
392 (not match-again)))
393 (if (eobp)
395 ;; Don't replace the null string
396 ;; right after end of previous replacement.
397 (forward-char 1)
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.
406 (if regexp-flag
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))
411 (progn
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)))))
416 (if (not query-flag)
417 (progn
418 (store-match-data real-match-data)
419 (replace-match next-replacement nocasify literal)
420 (setq replace-count (1+ replace-count)))
421 (undo-boundary)
422 (let (done replaced)
423 (while (not done)
424 (let ((help-form
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)
438 (= char ?q))
439 (setq keep-going nil)
440 (setq done t))
441 ((= char ?^)
442 (let ((elt (car stack)))
443 (goto-char (car elt))
444 (setq replaced (eq t (cdr elt)))
445 (or replaced
446 (store-match-data (cdr elt)))
447 (setq stack (cdr stack))))
448 ((or (= char ?\ )
449 (= char ?y))
450 (or replaced
451 (replace-match next-replacement nocasify literal))
452 (setq done t replaced t))
453 ((= char ?\.)
454 (or replaced
455 (replace-match next-replacement nocasify literal))
456 (setq keep-going nil)
457 (setq done t replaced t))
458 ((= char ?\,)
459 (if (not replaced)
460 (progn
461 (replace-match next-replacement nocasify literal)
462 (setq replaced t))))
463 ((= char ?!)
464 (or replaced
465 (replace-match next-replacement nocasify literal))
466 (setq done t query-flag nil replaced t))
467 ((or (= char ?\177)
468 (= char ?n))
469 (setq done t))
470 ((= char ?\C-l)
471 (recenter nil))
472 ((= char ?\C-r)
473 (store-match-data
474 (prog1 (match-data)
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.
479 (if regexp-flag
480 (setq match-again (looking-at search-string))))
481 ((= char ?\C-w)
482 (delete-region (match-beginning 0) (match-end 0))
483 (store-match-data
484 (prog1 (match-data)
485 (save-excursion (recursive-edit))))
486 (setq replaced t))
488 (setq keep-going nil)
489 (setq unread-command-char char)
490 (setq done t))))
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.
494 (setq stack
495 (cons (cons (point)
496 (or replaced
497 (mapcar
498 (function (lambda (elt)
499 (and elt
500 (marker-position elt))))
501 (match-data))))
502 stack))
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")
519 (let (replacements)
520 (if (listp to-strings)
521 (setq replacements to-strings)
522 (while (/= (length to-strings) 0)
523 (if (string-match " " to-strings)
524 (setq replacements
525 (append replacements
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))
531 to-strings ""))))
532 (perform-replace regexp replacements t t nil arg))
533 (message "Done"))
535 ;;; replace.el ends here