(command-apropos): Print echo area message iff found symbols.
[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 (fset 'list-matching-lines 'occur)
247
248 (defun occur (regexp &optional nlines)
249 "Show all lines in the current buffer containing a match for REGEXP.
250 Interactively, REGEXP defaults to the last REGEXP
251 used interactively with \\[occur].
252
253 If a match spreads across multiple lines, all those lines are shown.
254
255 Each line is displayed with NLINES lines before and after, or -NLINES
256 before if NLINES is negative.
257 NLINES defaults to `list-matching-lines-default-context-lines'.
258 Interactively it is the prefix arg.
259
260 The lines are shown in a buffer named *Occur*.
261 It serves as a menu to find any of the occurrences in this buffer.
262 \\[describe-mode] in that buffer will explain how."
263 (interactive (list (setq occur-last-string
264 (read-string "List lines matching regexp: "
265 occur-last-string))
266 current-prefix-arg))
267 (setq nlines (if nlines (prefix-numeric-value nlines)
268 list-matching-lines-default-context-lines))
269 (let ((first t)
270 (buffer (current-buffer))
271 (linenum 1)
272 (prevpos (point-min))
273 (final-context-start (make-marker)))
274 ;;; (save-excursion
275 ;;; (beginning-of-line)
276 ;;; (setq linenum (1+ (count-lines (point-min) (point))))
277 ;;; (setq prevpos (point)))
278 (with-output-to-temp-buffer "*Occur*"
279 (save-excursion
280 (set-buffer standard-output)
281 (insert "Lines matching ")
282 (prin1 regexp)
283 (insert " in buffer " (buffer-name buffer) ?. ?\n)
284 (occur-mode)
285 (setq occur-buffer buffer)
286 (setq occur-nlines nlines)
287 (setq occur-pos-list ()))
288 (if (eq buffer standard-output)
289 (goto-char (point-max)))
290 (save-excursion
291 (beginning-of-buffer)
292 ;; Find next match, but give up if prev match was at end of buffer.
293 (while (and (not (= prevpos (point-max)))
294 (re-search-forward regexp nil t))
295 (goto-char (match-beginning 0))
296 (beginning-of-line)
297 (setq linenum (+ linenum (count-lines prevpos (point))))
298 (setq prevpos (point))
299 (goto-char (match-end 0))
300 (let* ((start (save-excursion
301 (goto-char (match-beginning 0))
302 (forward-line (if (< nlines 0) nlines (- nlines)))
303 (point)))
304 (end (save-excursion
305 (goto-char (match-end 0))
306 (if (> nlines 0)
307 (forward-line (1+ nlines))
308 (forward-line 1))
309 (point)))
310 (tag (format "%3d" linenum))
311 (empty (make-string (length tag) ?\ ))
312 tem)
313 (save-excursion
314 (setq tem (make-marker))
315 (set-marker tem (point))
316 (set-buffer standard-output)
317 (setq occur-pos-list (cons tem occur-pos-list))
318 (or first (zerop nlines)
319 (insert "--------\n"))
320 (setq first nil)
321 (insert-buffer-substring buffer start end)
322 (backward-char (- end start))
323 (setq tem nlines)
324 (while (> tem 0)
325 (insert empty ?:)
326 (forward-line 1)
327 (setq tem (1- tem)))
328 (let ((this-linenum linenum))
329 (set-marker final-context-start
330 (+ (point) (- (match-end 0) (match-beginning 0))))
331 (while (< (point) final-context-start)
332 (if (null tag)
333 (setq tag (format "%3d" this-linenum)))
334 (insert tag ?:)
335 (setq tag nil)
336 (forward-line 1)
337 (setq this-linenum (1+ this-linenum))))
338 (while (< tem nlines)
339 (insert empty ?:)
340 (forward-line 1)
341 (setq tem (1+ tem))))
342 (forward-line 1)))
343 (set-buffer standard-output)
344 ;; Put positions in increasing order to go with buffer.
345 (setq occur-pos-list (nreverse occur-pos-list))
346 (if (interactive-p)
347 (message "%d matching lines." (length occur-pos-list)))))))
348 \f
349 (defconst query-replace-help
350 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
351 ESC or `q' to exit, Period to replace one match and exit,
352 Comma to replace but not move point immediately,
353 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
354 C-w to delete match and recursive edit,
355 C-l to clear the screen, redisplay, and offer same replacement again,
356 ! to replace all remaining matches with no more questions,
357 ^ to move point back to previous match."
358 "Help message while in query-replace")
359
360 (defun perform-replace (from-string replacements
361 query-flag regexp-flag delimited-flag
362 &optional repeat-count)
363 "Subroutine of `query-replace'. Its complexity handles interactive queries.
364 Don't use this in your own program unless you want to query and set the mark
365 just as `query-replace' does. Instead, write a simple loop like this:
366 (while (re-search-forward \"foo[ \t]+bar\" nil t)
367 (replace-match \"foobar\" nil nil))
368 which will run faster and do exactly what you probably want."
369 (let ((nocasify (not (and case-fold-search case-replace
370 (string-equal from-string
371 (downcase from-string)))))
372 (literal (not regexp-flag))
373 (search-function (if regexp-flag 're-search-forward 'search-forward))
374 (search-string from-string)
375 (real-match-data nil) ; the match data for the current match
376 (next-replacement nil)
377 (replacement-index 0)
378 (keep-going t)
379 (stack nil)
380 (next-rotate-count 0)
381 (replace-count 0)
382 (lastrepl nil) ;Position after last match considered.
383 (match-again t))
384 (if (stringp replacements)
385 (setq next-replacement replacements)
386 (or repeat-count (setq repeat-count 1)))
387 (if delimited-flag
388 (setq search-function 're-search-forward
389 search-string (concat "\\b"
390 (if regexp-flag from-string
391 (regexp-quote from-string))
392 "\\b")))
393 (push-mark)
394 (undo-boundary)
395 (while (and keep-going
396 (not (eobp))
397 (funcall search-function search-string nil t)
398 ;; If the search string matches immediately after
399 ;; the previous match, but it did not match there
400 ;; before the replacement was done, ignore the match.
401 (if (or (eq lastrepl (point))
402 (and regexp-flag
403 (eq lastrepl (match-beginning 0))
404 (not match-again)))
405 (if (eobp)
406 nil
407 ;; Don't replace the null string
408 ;; right after end of previous replacement.
409 (forward-char 1)
410 (funcall search-function search-string nil t))
411 t))
412
413 ;; Save the data associated with the real match.
414 (setq real-match-data (match-data))
415
416 ;; Before we make the replacement, decide whether the search string
417 ;; can match again just after this match.
418 (if regexp-flag
419 (setq match-again (looking-at search-string)))
420 ;; If time for a change, advance to next replacement string.
421 (if (and (listp replacements)
422 (= next-rotate-count replace-count))
423 (progn
424 (setq next-rotate-count
425 (+ next-rotate-count repeat-count))
426 (setq next-replacement (nth replacement-index replacements))
427 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
428 (if (not query-flag)
429 (progn
430 (store-match-data real-match-data)
431 (replace-match next-replacement nocasify literal)
432 (setq replace-count (1+ replace-count)))
433 (undo-boundary)
434 (let (done replaced char)
435 (while (not done)
436 (let ((help-form
437 '(concat "Query replacing "
438 (if regexp-flag "regexp " "")
439 from-string " with " next-replacement ".\n\n"
440 (substitute-command-keys query-replace-help))))
441 (setq char help-char)
442 (while (or (not (numberp char)) (= char help-char))
443 (message "Query replacing %s with %s: " from-string next-replacement)
444 (setq char (read-event))
445 (if (and (numberp char) (= char ??))
446 (setq unread-command-events (list help-char)
447 char help-char))))
448 ;; Restore the match data while we process the command.
449 (store-match-data real-match-data)
450 (cond ((or (= char ?\e)
451 (= char ?q))
452 (setq keep-going nil)
453 (setq done t))
454 ((= char ?^)
455 (let ((elt (car stack)))
456 (goto-char (car elt))
457 (setq replaced (eq t (cdr elt)))
458 (or replaced
459 (store-match-data (cdr elt)))
460 (setq stack (cdr stack))))
461 ((or (= char ?\ )
462 (= char ?y))
463 (or replaced
464 (replace-match next-replacement nocasify literal))
465 (setq done t replaced t))
466 ((= char ?\.)
467 (or replaced
468 (replace-match next-replacement nocasify literal))
469 (setq keep-going nil)
470 (setq done t replaced t))
471 ((= char ?\,)
472 (if (not replaced)
473 (progn
474 (replace-match next-replacement nocasify literal)
475 (setq replaced t))))
476 ((= char ?!)
477 (or replaced
478 (replace-match next-replacement nocasify literal))
479 (setq done t query-flag nil replaced t))
480 ((or (= char ?\177)
481 (= char ?n))
482 (setq done t))
483 ((= char ?\C-l)
484 (recenter nil))
485 ((= char ?\C-r)
486 (store-match-data
487 (prog1 (match-data)
488 (save-excursion (recursive-edit))))
489 ;; Before we make the replacement,
490 ;; decide whether the search string
491 ;; can match again just after this match.
492 (if regexp-flag
493 (setq match-again (looking-at search-string))))
494 ((= char ?\C-w)
495 (delete-region (match-beginning 0) (match-end 0))
496 (store-match-data
497 (prog1 (match-data)
498 (save-excursion (recursive-edit))))
499 (setq replaced t))
500 (t
501 (setq keep-going nil)
502 (setq unread-command-events (list char))
503 (setq done t))))
504 ;; Record previous position for ^ when we move on.
505 ;; Change markers to numbers in the match data
506 ;; since lots of markers slow down editing.
507 (setq stack
508 (cons (cons (point)
509 (or replaced
510 (mapcar
511 (function (lambda (elt)
512 (and elt
513 (marker-position elt))))
514 (match-data))))
515 stack))
516 (if replaced (setq replace-count (1+ replace-count)))))
517 (setq lastrepl (point)))
518 (and keep-going stack)))
519
520 ;;; replace.el ends here