*** empty log message ***
[bpt/emacs.git] / lisp / replace.el
1 ;;; replace.el --- replace commands for Emacs.
2
3 ;; Copyright (C) 1985, 1986, 1987, 1992 Free Software Foundation, Inc.
4
5 ;; This file is part of GNU Emacs.
6
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)
10 ;; any later version.
11
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.
16
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.
20
21 ;;; Code:
22
23 (defconst case-replace t "\
24 *Non-nil means query-replace should preserve case in replacements.")
25
26 (defvar query-replace-history nil)
27
28 (defun query-replace-read-args (string)
29 (let (from to)
30 (setq from (read-from-minibuffer (format "%s: " string)
31 nil nil nil
32 'query-replace-history))
33 (setq to (read-from-minibuffer (format "%s %s with: " string from)
34 nil nil nil
35 'query-replace-history))
36 (list from to current-prefix-arg)))
37
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.
42
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)
49 (message "Done"))
50 (define-key esc-map "%" 'query-replace)
51
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.
56
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)
65 (message "Done"))
66
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.
73
74 Non-interactively, TO-STRINGS may be a list of replacement strings.
75
76 A prefix argument N says to use each replacement string N times
77 before rotating to the next."
78 (interactive
79 (let (from to)
80 (setq from (read-from-minibuffer "Map query replace (regexp): "
81 nil nil nil
82 'query-replace-history))
83 (setq to (read-from-minibuffer
84 (format "Query replace %s with (space-separated strings): "
85 from)
86 nil nil nil
87 'query-replace-history))
88 (list from to current-prefix-arg)))
89 (let (replacements)
90 (if (listp to-strings)
91 (setq replacements to-strings)
92 (while (/= (length to-strings) 0)
93 (if (string-match " " to-strings)
94 (setq replacements
95 (append replacements
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))
101 to-strings ""))))
102 (perform-replace regexp replacements t t nil arg))
103 (message "Done"))
104
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.
111
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)
119 (message "Done"))
120
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.
129
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)
137 (message "Done"))
138
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): ")
145 (save-excursion
146 (or (bolp) (forward-line 1))
147 (let ((start (point)))
148 (while (not (eobp))
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))
153 (beginning-of-line)
154 (point))))
155 ;; Now end is first char preserved by the new match.
156 (if (< start end)
157 (delete-region start end))))
158 (setq start (save-excursion (forward-line 1)
159 (point)))
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))))))
163
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): ")
170 (save-excursion
171 (while (and (not (eobp))
172 (re-search-forward regexp nil t))
173 (delete-region (save-excursion (goto-char (match-beginning 0))
174 (beginning-of-line)
175 (point))
176 (progn (forward-line 1) (point))))))
177
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)
183 (save-excursion
184 (while (and (not (eobp))
185 (progn (setq opoint (point))
186 (re-search-forward regexp nil t)))
187 (if (= opoint (point))
188 (forward-char 1)
189 (setq count (1+ count))))
190 (message "%d occurrences" count))))
191
192 (defvar occur-mode-map ())
193 (if occur-mode-map
194 ()
195 (setq occur-mode-map (make-sparse-keymap))
196 (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence))
197
198 (defvar occur-buffer nil)
199 (defvar occur-nlines nil)
200 (defvar occur-pos-list nil)
201 (defvar occur-last-string "")
202
203 (defun occur-mode ()
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.
208 \\{occur-mode-map}"
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))
216
217 (defun occur-mode-goto-occurrence ()
218 "Go to the line this occurrence was found in, in the buffer it was found in."
219 (interactive)
220 (if (or (null occur-buffer)
221 (null (buffer-name occur-buffer)))
222 (progn
223 (setq occur-buffer nil
224 occur-pos-list nil)
225 (error "Buffer in which occurrences were found is deleted")))
226 (let* ((occur-number (save-excursion
227 (beginning-of-line)
228 (/ (1- (count-lines (point-min)
229 (save-excursion
230 (beginning-of-line)
231 (point))))
232 (cond ((< occur-nlines 0)
233 (- 2 occur-nlines))
234 ((> occur-nlines 0)
235 (+ 2 (* 2 occur-nlines)))
236 (t 1)))))
237 (pos (nth occur-number occur-pos-list)))
238 (pop-to-buffer occur-buffer)
239 (goto-char (marker-position pos))))
240
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.")
245
246 (defvar occur-whole-buffer nil
247 "If t, occur operates on whole buffer, otherwise occur starts from point.
248 default is nil.")
249
250 (fset 'list-matching-lines 'occur)
251
252 (defun occur (regexp &optional nlines)
253 "Show lines containing a match for REGEXP. If the global variable
254 `occur-whole-buffer' is non-nil, the entire buffer is searched, otherwise
255 search begins at point. Interactively, REGEXP defaults to the last REGEXP
256 used interactively with \\[occur].
257
258 If a match spreads across multiple lines, all those lines are shown.
259
260 Each line is displayed with NLINES lines before and after, or -NLINES
261 before if NLINES is negative.
262 NLINES defaults to `list-matching-lines-default-context-lines'.
263 Interactively it is the prefix arg.
264
265 The lines are shown in a buffer named *Occur*.
266 It serves as a menu to find any of the occurrences in this buffer.
267 \\[describe-mode] in that buffer will explain how."
268 (interactive (list (setq occur-last-string
269 (read-string "List lines matching regexp: "
270 occur-last-string))
271 current-prefix-arg))
272 (setq nlines (if nlines (prefix-numeric-value nlines)
273 list-matching-lines-default-context-lines))
274 (let ((first t)
275 (buffer (current-buffer))
276 (linenum 1)
277 (prevpos (point-min))
278 (final-context-start (make-marker)))
279 (if (not occur-whole-buffer)
280 (save-excursion
281 (beginning-of-line)
282 (setq linenum (1+ (count-lines (point-min) (point))))
283 (setq prevpos (point))))
284 (with-output-to-temp-buffer "*Occur*"
285 (save-excursion
286 (set-buffer standard-output)
287 (insert "Lines matching ")
288 (prin1 regexp)
289 (insert " in buffer " (buffer-name buffer) ?. ?\n)
290 (occur-mode)
291 (setq occur-buffer buffer)
292 (setq occur-nlines nlines)
293 (setq occur-pos-list ()))
294 (if (eq buffer standard-output)
295 (goto-char (point-max)))
296 (save-excursion
297 (if occur-whole-buffer
298 (beginning-of-buffer))
299 ;; Find next match, but give up if prev match was at end of buffer.
300 (while (and (not (= prevpos (point-max)))
301 (re-search-forward regexp nil t))
302 (goto-char (match-beginning 0))
303 (beginning-of-line)
304 (setq linenum (+ linenum (count-lines prevpos (point))))
305 (setq prevpos (point))
306 (goto-char (match-end 0))
307 (let* ((start (save-excursion
308 (goto-char (match-beginning 0))
309 (forward-line (if (< nlines 0) nlines (- nlines)))
310 (point)))
311 (end (save-excursion
312 (goto-char (match-end 0))
313 (if (> nlines 0)
314 (forward-line (1+ nlines))
315 (forward-line 1))
316 (point)))
317 (tag (format "%3d" linenum))
318 (empty (make-string (length tag) ?\ ))
319 tem)
320 (save-excursion
321 (setq tem (make-marker))
322 (set-marker tem (point))
323 (set-buffer standard-output)
324 (setq occur-pos-list (cons tem occur-pos-list))
325 (or first (zerop nlines)
326 (insert "--------\n"))
327 (setq first nil)
328 (insert-buffer-substring buffer start end)
329 (backward-char (- end start))
330 (setq tem nlines)
331 (while (> tem 0)
332 (insert empty ?:)
333 (forward-line 1)
334 (setq tem (1- tem)))
335 (let ((this-linenum linenum))
336 (set-marker final-context-start
337 (+ (point) (- (match-end 0) (match-beginning 0))))
338 (while (< (point) final-context-start)
339 (if (null tag)
340 (setq tag (format "%3d" this-linenum)))
341 (insert tag ?:)
342 (setq tag nil)
343 (forward-line 1)
344 (setq this-linenum (1+ this-linenum))))
345 (while (< tem nlines)
346 (insert empty ?:)
347 (forward-line 1)
348 (setq tem (1+ tem))))
349 (forward-line 1)))
350 (set-buffer standard-output)
351 ;; Put positions in increasing order to go with buffer.
352 (setq occur-pos-list (nreverse occur-pos-list))
353 (if (interactive-p)
354 (message "%d matching lines." (length occur-pos-list)))))))
355 \f
356 (defconst query-replace-help
357 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
358 ESC or `q' to exit, Period to replace one match and exit,
359 Comma to replace but not move point immediately,
360 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
361 C-w to delete match and recursive edit,
362 C-l to clear the screen, redisplay, and offer same replacement again,
363 ! to replace all remaining matches with no more questions,
364 ^ to move point back to previous match."
365 "Help message while in query-replace")
366
367 (defun perform-replace (from-string replacements
368 query-flag regexp-flag delimited-flag
369 &optional repeat-count)
370 "Subroutine of `query-replace'. Its complexity handles interactive queries.
371 Don't use this in your own program unless you want to query and set the mark
372 just as `query-replace' does. Instead, write a simple loop like this:
373 (while (re-search-forward \"foo[ \t]+bar\" nil t)
374 (replace-match \"foobar\" nil nil))
375 which will run faster and do exactly what you probably want."
376 (let ((nocasify (not (and case-fold-search case-replace
377 (string-equal from-string
378 (downcase from-string)))))
379 (literal (not regexp-flag))
380 (search-function (if regexp-flag 're-search-forward 'search-forward))
381 (search-string from-string)
382 (real-match-data nil) ; the match data for the current match
383 (next-replacement nil)
384 (replacement-index 0)
385 (keep-going t)
386 (stack nil)
387 (next-rotate-count 0)
388 (replace-count 0)
389 (lastrepl nil) ;Position after last match considered.
390 (match-again t))
391 (if (stringp replacements)
392 (setq next-replacement replacements)
393 (or repeat-count (setq repeat-count 1)))
394 (if delimited-flag
395 (setq search-function 're-search-forward
396 search-string (concat "\\b"
397 (if regexp-flag from-string
398 (regexp-quote from-string))
399 "\\b")))
400 (push-mark)
401 (undo-boundary)
402 (while (and keep-going
403 (not (eobp))
404 (funcall search-function search-string nil t)
405 ;; If the search string matches immediately after
406 ;; the previous match, but it did not match there
407 ;; before the replacement was done, ignore the match.
408 (if (or (eq lastrepl (point))
409 (and regexp-flag
410 (eq lastrepl (match-beginning 0))
411 (not match-again)))
412 (if (eobp)
413 nil
414 ;; Don't replace the null string
415 ;; right after end of previous replacement.
416 (forward-char 1)
417 (funcall search-function search-string nil t))
418 t))
419
420 ;; Save the data associated with the real match.
421 (setq real-match-data (match-data))
422
423 ;; Before we make the replacement, decide whether the search string
424 ;; can match again just after this match.
425 (if regexp-flag
426 (setq match-again (looking-at search-string)))
427 ;; If time for a change, advance to next replacement string.
428 (if (and (listp replacements)
429 (= next-rotate-count replace-count))
430 (progn
431 (setq next-rotate-count
432 (+ next-rotate-count repeat-count))
433 (setq next-replacement (nth replacement-index replacements))
434 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
435 (if (not query-flag)
436 (progn
437 (store-match-data real-match-data)
438 (replace-match next-replacement nocasify literal)
439 (setq replace-count (1+ replace-count)))
440 (undo-boundary)
441 (let (done replaced)
442 (while (not done)
443 (let ((help-form
444 '(concat "Query replacing "
445 (if regexp-flag "regexp " "")
446 from-string " with " next-replacement ".\n\n"
447 (substitute-command-keys query-replace-help))))
448 (setq char help-char)
449 (while (or (not (numberp char)) (= char help-char))
450 (message "Query replacing %s with %s: " from-string next-replacement)
451 (setq char (read-event))
452 (if (and (numberp char) (= char ??))
453 (setq unread-command-char help-char char help-char))))
454 ;; Restore the match data while we process the command.
455 (store-match-data real-match-data)
456 (cond ((or (= char ?\e)
457 (= char ?q))
458 (setq keep-going nil)
459 (setq done t))
460 ((= char ?^)
461 (let ((elt (car stack)))
462 (goto-char (car elt))
463 (setq replaced (eq t (cdr elt)))
464 (or replaced
465 (store-match-data (cdr elt)))
466 (setq stack (cdr stack))))
467 ((or (= char ?\ )
468 (= char ?y))
469 (or replaced
470 (replace-match next-replacement nocasify literal))
471 (setq done t replaced t))
472 ((= char ?\.)
473 (or replaced
474 (replace-match next-replacement nocasify literal))
475 (setq keep-going nil)
476 (setq done t replaced t))
477 ((= char ?\,)
478 (if (not replaced)
479 (progn
480 (replace-match next-replacement nocasify literal)
481 (setq replaced t))))
482 ((= char ?!)
483 (or replaced
484 (replace-match next-replacement nocasify literal))
485 (setq done t query-flag nil replaced t))
486 ((or (= char ?\177)
487 (= char ?n))
488 (setq done t))
489 ((= char ?\C-l)
490 (recenter nil))
491 ((= char ?\C-r)
492 (store-match-data
493 (prog1 (match-data)
494 (save-excursion (recursive-edit))))
495 ;; Before we make the replacement,
496 ;; decide whether the search string
497 ;; can match again just after this match.
498 (if regexp-flag
499 (setq match-again (looking-at search-string))))
500 ((= char ?\C-w)
501 (delete-region (match-beginning 0) (match-end 0))
502 (store-match-data
503 (prog1 (match-data)
504 (save-excursion (recursive-edit))))
505 (setq replaced t))
506 (t
507 (setq keep-going nil)
508 (setq unread-command-char char)
509 (setq done t))))
510 ;; Record previous position for ^ when we move on.
511 ;; Change markers to numbers in the match data
512 ;; since lots of markers slow down editing.
513 (setq stack
514 (cons (cons (point)
515 (or replaced
516 (mapcar
517 (function (lambda (elt)
518 (and elt
519 (marker-position elt))))
520 (match-data))))
521 stack))
522 (if replaced (setq replace-count (1+ replace-count)))))
523 (setq lastrepl (point)))
524 (and keep-going stack)))
525
526 ;;; replace.el ends here