*** empty log message ***
[bpt/emacs.git] / lisp / replace.el
1 ;; Replace commands for Emacs.
2 ;; Copyright (C) 1985-1991 Free Software Foundation, Inc.
3
4 ;; This file is part of GNU Emacs.
5
6 ;; GNU Emacs is free software; you can redistribute it and/or modify
7 ;; it under the terms of the GNU General Public License as published by
8 ;; the Free Software Foundation; either version 1, or (at your option)
9 ;; any later version.
10
11 ;; GNU Emacs is distributed in the hope that it will be useful,
12 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 ;; GNU General Public License for more details.
15
16 ;; You should have received a copy of the GNU General Public License
17 ;; along with GNU Emacs; see the file COPYING. If not, write to
18 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
19
20
21 ;;;###autoload
22 (defconst case-replace t "\
23 *Non-nil means query-replace should preserve case in replacements.")
24
25 ;;;###autoload
26 (defun query-replace (from-string to-string &optional arg)
27 "Replace some occurrences of FROM-STRING with TO-STRING.
28 As each match is found, the user must type a character saying
29 what to do with it. For directions, type \\[help-command] at that time.
30
31 Preserves case in each replacement if case-replace and case-fold-search
32 are non-nil and FROM-STRING has no uppercase letters.
33 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
34 only matches surrounded by word boundaries."
35 (interactive "sQuery replace: \nsQuery replace %s with: \nP")
36 (perform-replace from-string to-string t nil arg)
37 (message "Done"))
38 ;;;###autoload
39 (define-key esc-map "%" 'query-replace)
40
41 ;;;###autoload
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.
46
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)
55 (message "Done"))
56
57 ;;;###autoload
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.
64
65 Non-interactively, TO-STRINGS may be a list of replacement strings.
66
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"))
85
86 ;;;###autoload
87 (defun replace-string (from-string to-string &optional delimited)
88 "Replace occurrences of FROM-STRING with TO-STRING.
89 Preserve case in each match if `case-replace' and `case-fold-search'
90 are non-nil and FROM-STRING has no uppercase letters.
91 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
92 only matches surrounded by word boundaries.
93
94 This function is usually the wrong thing to use in a Lisp program.
95 What you probably want is a loop like this:
96 (while (search-forward OLD-STRING nil t)
97 (replace-match REPLACEMENT nil t))
98 which will run faster and will not set the mark or print anything."
99 (interactive "sReplace string: \nsReplace string %s with: \nP")
100 (perform-replace from-string to-string nil nil delimited)
101 (message "Done"))
102
103 ;;;###autoload
104 (defun replace-regexp (regexp to-string &optional delimited)
105 "Replace things after point matching REGEXP with TO-STRING.
106 Preserve case in each match if case-replace and case-fold-search
107 are non-nil and REGEXP has no uppercase letters.
108 Third arg DELIMITED (prefix arg if interactive) non-nil means replace
109 only matches surrounded by word boundaries.
110 In TO-STRING, \\& means insert what matched REGEXP,
111 and \\=\\<n> means insert what matched <n>th \\(...\\) in REGEXP.
112
113 This function is usually the wrong thing to use in a Lisp program.
114 What you probably want is a loop like this:
115 (while (re-search-forward REGEXP nil t)
116 (replace-match REPLACEMENT nil nil))
117 which will run faster and will not set the mark or print anything."
118 (interactive "sReplace regexp: \nsReplace regexp %s with: \nP")
119 (perform-replace regexp to-string nil t delimited)
120 (message "Done"))
121
122 (fset 'delete-non-matching-lines 'keep-lines)
123 (defun keep-lines (regexp)
124 "Delete all lines except those containing matches for REGEXP.
125 A match split across lines preserves all the lines it lies in.
126 Applies to all lines after point."
127 (interactive "sKeep lines (containing match for regexp): ")
128 (save-excursion
129 (or (bolp) (forward-line 1))
130 (let ((start (point)))
131 (while (not (eobp))
132 ;; Start is first char not preserved by previous match.
133 (if (not (re-search-forward regexp nil 'move))
134 (delete-region start (point-max))
135 (let ((end (save-excursion (goto-char (match-beginning 0))
136 (beginning-of-line)
137 (point))))
138 ;; Now end is first char preserved by the new match.
139 (if (< start end)
140 (delete-region start end))))
141 (setq start (save-excursion (forward-line 1)
142 (point)))
143 ;; If the match was empty, avoid matching again at same place.
144 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
145 (forward-char 1))))))
146
147 (fset 'delete-matching-lines 'flush-lines)
148 (defun flush-lines (regexp)
149 "Delete lines containing matches for REGEXP.
150 If a match is split across lines, all the lines it lies in are deleted.
151 Applies to lines after point."
152 (interactive "sFlush lines (containing match for regexp): ")
153 (save-excursion
154 (while (and (not (eobp))
155 (re-search-forward regexp nil t))
156 (delete-region (save-excursion (goto-char (match-beginning 0))
157 (beginning-of-line)
158 (point))
159 (progn (forward-line 1) (point))))))
160
161 (fset 'count-matches 'how-many)
162 (defun how-many (regexp)
163 "Print number of matches for REGEXP following point."
164 (interactive "sHow many matches for (regexp): ")
165 (let ((count 0) opoint)
166 (save-excursion
167 (while (and (not (eobp))
168 (progn (setq opoint (point))
169 (re-search-forward regexp nil t)))
170 (if (= opoint (point))
171 (forward-char 1)
172 (setq count (1+ count))))
173 (message "%d occurrences" count))))
174
175 (defvar occur-mode-map ())
176 (if occur-mode-map
177 ()
178 (setq occur-mode-map (make-sparse-keymap))
179 (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence))
180
181 (defvar occur-buffer nil)
182 (defvar occur-nlines nil)
183 (defvar occur-pos-list nil)
184 (defvar occur-last-string "")
185
186 (defun occur-mode ()
187 "Major mode for output from \\[occur].
188 Move point to one of the occurrences in this buffer,
189 then use \\[occur-mode-goto-occurrence] to go to the same occurrence
190 in the buffer that the occurrences were found in.
191 \\{occur-mode-map}"
192 (kill-all-local-variables)
193 (use-local-map occur-mode-map)
194 (setq major-mode 'occur-mode)
195 (setq mode-name "Occur")
196 (make-local-variable 'occur-buffer)
197 (make-local-variable 'occur-nlines)
198 (make-local-variable 'occur-pos-list))
199
200 (defun occur-mode-goto-occurrence ()
201 "Go to the line this occurrence was found in, in the buffer it was found in."
202 (interactive)
203 (if (or (null occur-buffer)
204 (null (buffer-name occur-buffer)))
205 (progn
206 (setq occur-buffer nil
207 occur-pos-list nil)
208 (error "Buffer in which occurrences were found is deleted")))
209 (let* ((occur-number (save-excursion
210 (beginning-of-line)
211 (/ (1- (count-lines (point-min)
212 (save-excursion
213 (beginning-of-line)
214 (point))))
215 (cond ((< occur-nlines 0)
216 (- 2 occur-nlines))
217 ((> occur-nlines 0)
218 (+ 2 (* 2 occur-nlines)))
219 (t 1)))))
220 (pos (nth occur-number occur-pos-list)))
221 (pop-to-buffer occur-buffer)
222 (goto-char (marker-position pos))))
223
224 (defvar list-matching-lines-default-context-lines 0
225 "*Default number of context lines to include around a `list-matching-lines'
226 match. A negative number means to include that many lines before the match.
227 A positive number means to include that many lines both before and after.")
228
229 (defvar occur-whole-buffer nil
230 "If t, occur operates on whole buffer, otherwise occur starts from point.
231 default is nil.")
232
233 (fset 'list-matching-lines 'occur)
234
235 (defun occur (regexp &optional nlines)
236 "Show lines containing a match for REGEXP. If the global variable
237 `occur-whole-buffer' is non-nil, the entire buffer is searched, otherwise
238 search begins at point. Interactively, REGEXP defaults to the last REGEXP
239 used interactively with \\[occur].
240
241 If a match spreads across multiple lines, all those lines are shown.
242
243 Each line is displayed with NLINES lines before and after, or -NLINES
244 before if NLINES is negative.
245 NLINES defaults to `list-matching-lines-default-context-lines'.
246 Interactively it is the prefix arg.
247
248 The lines are shown in a buffer named *Occur*.
249 It serves as a menu to find any of the occurrences in this buffer.
250 \\[describe-mode] in that buffer will explain how."
251 (interactive (list (setq occur-last-string
252 (read-string "List lines matching regexp: "
253 occur-last-string))
254 current-prefix-arg))
255 (setq nlines (if nlines (prefix-numeric-value nlines)
256 list-matching-lines-default-context-lines))
257 (let ((first t)
258 (buffer (current-buffer))
259 (linenum 1)
260 (prevpos (point-min))
261 (final-context-start (make-marker)))
262 (if (not occur-whole-buffer)
263 (save-excursion
264 (beginning-of-line)
265 (setq linenum (1+ (count-lines (point-min) (point))))
266 (setq prevpos (point))))
267 (with-output-to-temp-buffer "*Occur*"
268 (save-excursion
269 (set-buffer standard-output)
270 (insert "Lines matching ")
271 (prin1 regexp)
272 (insert " in buffer " (buffer-name buffer) ?. ?\n)
273 (occur-mode)
274 (setq occur-buffer buffer)
275 (setq occur-nlines nlines)
276 (setq occur-pos-list ()))
277 (if (eq buffer standard-output)
278 (goto-char (point-max)))
279 (save-excursion
280 (if occur-whole-buffer
281 (beginning-of-buffer))
282 ;; Find next match, but give up if prev match was at end of buffer.
283 (while (and (not (= prevpos (point-max)))
284 (re-search-forward regexp nil t))
285 (goto-char (match-beginning 0))
286 (beginning-of-line)
287 (setq linenum (+ linenum (count-lines prevpos (point))))
288 (setq prevpos (point))
289 (goto-char (match-end 0))
290 (let* ((start (save-excursion
291 (goto-char (match-beginning 0))
292 (forward-line (if (< nlines 0) nlines (- nlines)))
293 (point)))
294 (end (save-excursion
295 (goto-char (match-end 0))
296 (if (> nlines 0)
297 (forward-line (1+ nlines))
298 (forward-line 1))
299 (point)))
300 (tag (format "%3d" linenum))
301 (empty (make-string (length tag) ?\ ))
302 tem)
303 (save-excursion
304 (setq tem (make-marker))
305 (set-marker tem (point))
306 (set-buffer standard-output)
307 (setq occur-pos-list (cons tem occur-pos-list))
308 (or first (zerop nlines)
309 (insert "--------\n"))
310 (setq first nil)
311 (insert-buffer-substring buffer start end)
312 (backward-char (- end start))
313 (setq tem nlines)
314 (while (> tem 0)
315 (insert empty ?:)
316 (forward-line 1)
317 (setq tem (1- tem)))
318 (let ((this-linenum linenum))
319 (set-marker final-context-start
320 (+ (point) (- (match-end 0) (match-beginning 0))))
321 (while (< (point) final-context-start)
322 (if (null tag)
323 (setq tag (format "%3d" this-linenum)))
324 (insert tag ?:)
325 (setq tag nil)
326 (forward-line 1)
327 (setq this-linenum (1+ this-linenum))))
328 (while (< tem nlines)
329 (insert empty ?:)
330 (forward-line 1)
331 (setq tem (1+ tem))))
332 (forward-line 1)))
333 (set-buffer standard-output)
334 ;; Put positions in increasing order to go with buffer.
335 (setq occur-pos-list (nreverse occur-pos-list))
336 (if (interactive-p)
337 (message "%d matching lines." (length occur-pos-list)))))))
338 \f
339 (defconst query-replace-help
340 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
341 ESC or `q' to exit, Period to replace one match and exit,
342 Comma to replace but not move point immediately,
343 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
344 C-w to delete match and recursive edit,
345 C-l to clear the screen, redisplay, and offer same replacement again,
346 ! to replace all remaining matches with no more questions,
347 ^ to move point back to previous match."
348 "Help message while in query-replace")
349
350 ;;;###autoload
351 (defun perform-replace (from-string replacements
352 query-flag regexp-flag delimited-flag
353 &optional repeat-count)
354 "Subroutine of `query-replace'. Its complexity handles interactive queries.
355 Don't use this in your own program unless you want to query and set the mark
356 just as `query-replace' does. Instead, write a simple loop like this:
357 (while (re-search-forward \"foo[ \t]+bar\" nil t)
358 (replace-match \"foobar\" nil nil))
359 which will run faster and do exactly what you probably want."
360 (let ((nocasify (not (and case-fold-search case-replace
361 (string-equal from-string
362 (downcase from-string)))))
363 (literal (not regexp-flag))
364 (search-function (if regexp-flag 're-search-forward 'search-forward))
365 (search-string from-string)
366 (next-replacement nil)
367 (replacement-index 0)
368 (keep-going t)
369 (stack nil)
370 (next-rotate-count 0)
371 (replace-count 0)
372 (lastrepl nil) ;Position after last match considered.
373 (match-after t))
374 (if (stringp replacements)
375 (setq next-replacement replacements)
376 (or repeat-count (setq repeat-count 1)))
377 (if delimited-flag
378 (setq search-function 're-search-forward
379 search-string (concat "\\b"
380 (if regexp-flag from-string
381 (regexp-quote from-string))
382 "\\b")))
383 (push-mark)
384 (undo-boundary)
385 (while (and keep-going
386 (not (eobp))
387 (funcall search-function search-string nil t)
388 ;; If the search string matches immediately after
389 ;; the previous match, but it did not match there
390 ;; before the replacement was done, ignore the match.
391 (if (or (eq lastrepl (point))
392 (and regexp-flag
393 (eq lastrepl (match-beginning 0))
394 (not match-again)))
395 (if (eobp)
396 nil
397 ;; Don't replace the null string
398 ;; right after end of previous replacement.
399 (forward-char 1)
400 (funcall search-function search-string nil t))
401 t))
402 ;; Before we make the replacement, decide whether the search string
403 ;; can match again just after this match.
404 (if regexp-flag
405 (setq match-again (looking-at search-string)))
406 ;; If time for a change, advance to next replacement string.
407 (if (and (listp replacements)
408 (= next-rotate-count replace-count))
409 (progn
410 (setq next-rotate-count
411 (+ next-rotate-count repeat-count))
412 (setq next-replacement (nth replacement-index replacements))
413 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
414 (if (not query-flag)
415 (progn
416 (replace-match next-replacement nocasify literal)
417 (setq replace-count (1+ replace-count)))
418 (undo-boundary)
419 (let (done replaced)
420 (while (not done)
421 ;; Preserve the match data. Process filters and sentinels
422 ;; could run inside read-char..
423 (let ((data (match-data))
424 (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 (store-match-data data))
436 (cond ((or (= char ?\e)
437 (= char ?q))
438 (setq keep-going nil)
439 (setq done t))
440 ((= char ?^)
441 (let ((elt (car stack)))
442 (goto-char (car elt))
443 (setq replaced (eq t (cdr elt)))
444 (or replaced
445 (store-match-data (cdr elt)))
446 (setq stack (cdr stack))))
447 ((or (= char ?\ )
448 (= char ?y))
449 (or replaced
450 (replace-match next-replacement nocasify literal))
451 (setq done t replaced t))
452 ((= char ?\.)
453 (or replaced
454 (replace-match next-replacement nocasify literal))
455 (setq keep-going nil)
456 (setq done t replaced t))
457 ((= char ?\,)
458 (if (not replaced)
459 (progn
460 (replace-match next-replacement nocasify literal)
461 (setq replaced t))))
462 ((= char ?!)
463 (or replaced
464 (replace-match next-replacement nocasify literal))
465 (setq done t query-flag nil replaced t))
466 ((or (= char ?\177)
467 (= char ?n))
468 (setq done t))
469 ((= char ?\C-l)
470 (recenter nil))
471 ((= char ?\C-r)
472 (store-match-data
473 (prog1 (match-data)
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.
478 (if regexp-flag
479 (setq match-again (looking-at search-string))))
480 ((= char ?\C-w)
481 (delete-region (match-beginning 0) (match-end 0))
482 (store-match-data
483 (prog1 (match-data)
484 (save-excursion (recursive-edit))))
485 (setq replaced t))
486 (t
487 (setq keep-going nil)
488 (setq unread-command-char char)
489 (setq done t))))
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.
493 (setq stack
494 (cons (cons (point)
495 (or replaced
496 (mapcar
497 (function (lambda (elt)
498 (and elt
499 (marker-position elt))))
500 (match-data))))
501 stack))
502 (if replaced (setq replace-count (1+ replace-count)))))
503 (setq lastrepl (point)))
504 (and keep-going stack)))
505 \f
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.
512
513 Non-interactively, TO-STRINGS may be a list of replacement strings.
514
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")
518 (let (replacements)
519 (if (listp to-strings)
520 (setq replacements to-strings)
521 (while (/= (length to-strings) 0)
522 (if (string-match " " to-strings)
523 (setq replacements
524 (append replacements
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))
530 to-strings ""))))
531 (perform-replace regexp replacements t t nil arg))
532 (message "Done"))
533