Initial revision
[bpt/emacs.git] / lisp / replace.el
CommitLineData
698e1804 1;; Replace commands for Emacs.
77176e73 2;; Copyright (C) 1985-1991 Free Software Foundation, Inc.
698e1804
RS
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
77176e73
RM
21;;;###autoload (defconst case-replace t "\
22;;;###autoload *Non-nil means query-replace should preserve case in replacements.")
23
da44e784
RM
24;;;###autoload
25(defun query-replace (from-string to-string &optional arg)
26 "Replace some occurrences of FROM-STRING with TO-STRING.
27As each match is found, the user must type a character saying
28what to do with it. For directions, type \\[help-command] at that time.
29
30Preserves case in each replacement if case-replace and case-fold-search
31are non-nil and FROM-STRING has no uppercase letters.
32Third arg DELIMITED (prefix arg if interactive) non-nil means replace
33only matches surrounded by word boundaries."
34 (interactive "sQuery replace: \nsQuery replace %s with: \nP")
35 (perform-replace from-string to-string t nil arg)
36 (message "Done"))
37;;;###autoload (define-key esc-map "%" 'query-replace)
38
39;;;###autoload
40(defun query-replace-regexp (regexp to-string &optional arg)
41 "Replace some things after point matching REGEXP with TO-STRING.
42As each match is found, the user must type a character saying
43what to do with it. For directions, type \\[help-command] at that time.
44
45Preserves case in each replacement if case-replace and case-fold-search
46are non-nil and REGEXP has no uppercase letters.
47Third arg DELIMITED (prefix arg if interactive) non-nil means replace
48only matches surrounded by word boundaries.
49In TO-STRING, \\& means insert what matched REGEXP,
50and \\=\\<n> means insert what matched <n>th \\(...\\) in REGEXP."
51 (interactive "sQuery replace regexp: \nsQuery replace regexp %s with: \nP")
52 (perform-replace regexp to-string t t arg)
53 (message "Done"))
54
55;;;###autoload
56(defun map-query-replace-regexp (regexp to-strings &optional arg)
57 "Replace some matches for REGEXP with various strings, in rotation.
58The second argument TO-STRINGS contains the replacement strings, separated
59by spaces. This command works like `query-replace-regexp' except
60that each successive replacement uses the next successive replacement string,
61wrapping around from the last such string to the first.
62
63Non-interactively, TO-STRINGS may be a list of replacement strings.
64
65A prefix argument N says to use each replacement string N times
66before rotating to the next."
67 (interactive "sMap query replace (regexp): \nsQuery replace %s with (space-separated strings): \nP")
68 (let (replacements)
69 (if (listp to-strings)
70 (setq replacements to-strings)
71 (while (/= (length to-strings) 0)
72 (if (string-match " " to-strings)
73 (setq replacements
74 (append replacements
75 (list (substring to-strings 0
76 (string-match " " to-strings))))
77 to-strings (substring to-strings
78 (1+ (string-match " " to-strings))))
79 (setq replacements (append replacements (list to-strings))
80 to-strings ""))))
81 (perform-replace regexp replacements t t nil arg))
82 (message "Done"))
83
84;;;###autoload
85(defun replace-string (from-string to-string &optional delimited)
86 "Replace occurrences of FROM-STRING with TO-STRING.
87Preserve case in each match if `case-replace' and `case-fold-search'
88are non-nil and FROM-STRING has no uppercase letters.
89Third arg DELIMITED (prefix arg if interactive) non-nil means replace
90only matches surrounded by word boundaries.
91
92This function is usually the wrong thing to use in a Lisp program.
93What you probably want is a loop like this:
94 (while (search-forward OLD-STRING nil t)
95 (replace-match REPLACEMENT nil t))
96which will run faster and will not set the mark or print anything."
97 (interactive "sReplace string: \nsReplace string %s with: \nP")
98 (perform-replace from-string to-string nil nil delimited)
99 (message "Done"))
100
101;;;###autoload
102(defun replace-regexp (regexp to-string &optional delimited)
103 "Replace things after point matching REGEXP with TO-STRING.
104Preserve case in each match if case-replace and case-fold-search
105are non-nil and REGEXP has no uppercase letters.
106Third arg DELIMITED (prefix arg if interactive) non-nil means replace
107only matches surrounded by word boundaries.
108In TO-STRING, \\& means insert what matched REGEXP,
109and \\=\\<n> means insert what matched <n>th \\(...\\) in REGEXP.
110
111This function is usually the wrong thing to use in a Lisp program.
112What you probably want is a loop like this:
113 (while (re-search-forward REGEXP nil t)
114 (replace-match REPLACEMENT nil nil))
115which 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"))
119
698e1804
RS
120(fset 'delete-non-matching-lines 'keep-lines)
121(defun keep-lines (regexp)
122 "Delete all lines except those containing matches for REGEXP.
123A match split across lines preserves all the lines it lies in.
124Applies 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))))))
144
145(fset 'delete-matching-lines 'flush-lines)
146(defun flush-lines (regexp)
147 "Delete lines containing matches for REGEXP.
148If a match is split across lines, all the lines it lies in are deleted.
149Applies 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))))))
158
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))))
172
173(defvar occur-mode-map ())
174(if occur-mode-map
175 ()
176 (setq occur-mode-map (make-sparse-keymap))
177 (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence))
178
179(defvar occur-buffer nil)
180(defvar occur-nlines nil)
181(defvar occur-pos-list nil)
f1c9e147 182(defvar occur-last-string "")
698e1804
RS
183
184(defun occur-mode ()
185 "Major mode for output from \\[occur].
186Move point to one of the occurrences in this buffer,
187then use \\[occur-mode-goto-occurrence] to go to the same occurrence
188in 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))
197
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))))
221
222(defvar list-matching-lines-default-context-lines 0
da44e784 223 "*Default number of context lines to include around a `list-matching-lines'
698e1804
RS
224match. A negative number means to include that many lines before the match.
225A positive number means to include that many lines both before and after.")
226
227(defvar occur-whole-buffer nil
228 "If t, occur operates on whole buffer, otherwise occur starts from point.
229default is nil.")
230
231(fset 'list-matching-lines 'occur)
232
233(defun occur (regexp &optional nlines)
f1c9e147 234 "Show lines containing a match for REGEXP. If the global variable
da44e784 235`occur-whole-buffer' is non-nil, the entire buffer is searched, otherwise
f1c9e147 236search begins at point. Interactively, REGEXP defaults to the last REGEXP
da44e784
RM
237used interactively with \\[occur].
238
239If a match spreads across multiple lines, all those lines are shown.
698e1804 240
da44e784
RM
241Each line is displayed with NLINES lines before and after, or -NLINES
242before if NLINES is negative.
243NLINES defaults to `list-matching-lines-default-context-lines'.
698e1804
RS
244Interactively it is the prefix arg.
245
246The lines are shown in a buffer named *Occur*.
247It serves as a menu to find any of the occurrences in this buffer.
248\\[describe-mode] in that buffer will explain how."
f1c9e147 249 (interactive (list (setq occur-last-string
250 (read-string "List lines matching regexp: "
251 occur-last-string))
252 current-prefix-arg))
698e1804
RS
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 (if (not occur-whole-buffer)
260 (save-excursion
261 (beginning-of-line)
262 (setq linenum (1+ (count-lines (point-min) (point))))
263 (setq prevpos (point))))
264 (with-output-to-temp-buffer "*Occur*"
265 (save-excursion
266 (set-buffer standard-output)
267 (insert "Lines matching ")
268 (prin1 regexp)
269 (insert " in buffer " (buffer-name buffer) ?. ?\n)
270 (occur-mode)
271 (setq occur-buffer buffer)
272 (setq occur-nlines nlines)
273 (setq occur-pos-list ()))
274 (if (eq buffer standard-output)
275 (goto-char (point-max)))
276 (save-excursion
277 (if occur-whole-buffer
278 (beginning-of-buffer))
279 ;; Find next match, but give up if prev match was at end of buffer.
280 (while (and (not (= prevpos (point-max)))
281 (re-search-forward regexp nil t))
da44e784 282 (goto-char (match-beginning 0))
698e1804
RS
283 (beginning-of-line)
284 (setq linenum (+ linenum (count-lines prevpos (point))))
285 (setq prevpos (point))
da44e784 286 (goto-char (match-end 0))
698e1804 287 (let* ((start (save-excursion
da44e784 288 (goto-char (match-beginning 0))
698e1804
RS
289 (forward-line (if (< nlines 0) nlines (- nlines)))
290 (point)))
291 (end (save-excursion
da44e784 292 (goto-char (match-end 0))
698e1804
RS
293 (if (> nlines 0)
294 (forward-line (1+ nlines))
295 (forward-line 1))
296 (point)))
297 (tag (format "%3d" linenum))
298 (empty (make-string (length tag) ?\ ))
299 tem)
300 (save-excursion
698e1804
RS
301 (set-buffer standard-output)
302 (setq occur-pos-list (cons tem occur-pos-list))
303 (or first (zerop nlines)
304 (insert "--------\n"))
305 (setq first nil)
306 (insert-buffer-substring buffer start end)
307 (backward-char (- end start))
da44e784 308 (setq tem nlines)
698e1804
RS
309 (while (> tem 0)
310 (insert empty ?:)
311 (forward-line 1)
312 (setq tem (1- tem)))
da44e784
RM
313 (let ((final-context-start (make-marker))
314 (this-linenum linenum))
315 (set-marker final-context-start
316 (+ (point) (- (match-end 0) (match-beginning 0))))
317 (while (< (point) final-context-start)
318 (if (null tag)
319 (setq tag (format "%3d" this-linenum)))
320 (insert tag ?:)
321 (setq tag nil)
322 (forward-line 1)
323 (setq this-linenum (1+ this-linenum))))
698e1804
RS
324 (while (< tem nlines)
325 (insert empty ?:)
326 (forward-line 1)
327 (setq tem (1+ tem))))
328 (forward-line 1)))
329 (set-buffer standard-output)
330 ;; Put positions in increasing order to go with buffer.
331 (setq occur-pos-list (nreverse occur-pos-list))
332 (if (interactive-p)
333 (message "%d matching lines." (length occur-pos-list)))))))
334\f
335(defconst query-replace-help
336 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
337ESC or `q' to exit, Period to replace one match and exit,
338Comma to replace but not move point immediately,
339C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
340C-w to delete match and recursive edit,
341C-l to clear the screen, redisplay, and offer same replacement again,
342! to replace all remaining matches with no more questions,
343^ to move point back to previous match."
344 "Help message while in query-replace")
345
da44e784 346;;;###autoload
698e1804
RS
347(defun perform-replace (from-string replacements
348 query-flag regexp-flag delimited-flag
349 &optional repeat-count)
350 "Subroutine of `query-replace'. Its complexity handles interactive queries.
351Don't use this in your own program unless you want to query and set the mark
352just as `query-replace' does. Instead, write a simple loop like this:
353 (while (re-search-forward \"foo[ \t]+bar\" nil t)
354 (replace-match \"foobar\" nil nil))
355which will run faster and do exactly what you probably want."
356 (let ((nocasify (not (and case-fold-search case-replace
357 (string-equal from-string
358 (downcase from-string)))))
359 (literal (not regexp-flag))
360 (search-function (if regexp-flag 're-search-forward 'search-forward))
361 (search-string from-string)
362 (next-replacement nil)
363 (replacement-index 0)
364 (keep-going t)
365 (stack nil)
366 (next-rotate-count 0)
367 (replace-count 0)
da44e784
RM
368 (lastrepl nil) ;Position after last match considered.
369 (match-after t))
698e1804
RS
370 (if (stringp replacements)
371 (setq next-replacement replacements)
372 (or repeat-count (setq repeat-count 1)))
373 (if delimited-flag
374 (setq search-function 're-search-forward
375 search-string (concat "\\b"
376 (if regexp-flag from-string
377 (regexp-quote from-string))
378 "\\b")))
379 (push-mark)
380 (undo-boundary)
381 (while (and keep-going
382 (not (eobp))
383 (funcall search-function search-string nil t)
da44e784
RM
384 ;; If the search string matches immediately after
385 ;; the previous match, but it did not match there
386 ;; before the replacement was done, ignore the match.
387 (if (or (eq lastrepl (point))
388 (and regexp-flag
389 (eq lastrepl (match-beginning 0))
390 (not match-again)))
391 (if (eobp)
392 nil
698e1804
RS
393 ;; Don't replace the null string
394 ;; right after end of previous replacement.
395 (forward-char 1)
396 (funcall search-function search-string nil t))
397 t))
da44e784
RM
398 ;; Before we make the replacement, decide whether the search string
399 ;; can match again just after this match.
400 (if regexp-flag
401 (setq match-again (looking-at search-string)))
698e1804
RS
402 ;; If time for a change, advance to next replacement string.
403 (if (and (listp replacements)
404 (= next-rotate-count replace-count))
405 (progn
406 (setq next-rotate-count
407 (+ next-rotate-count repeat-count))
408 (setq next-replacement (nth replacement-index replacements))
409 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
410 (if (not query-flag)
411 (progn
412 (replace-match next-replacement nocasify literal)
413 (setq replace-count (1+ replace-count)))
414 (undo-boundary)
415 (let (done replaced)
416 (while (not done)
417 ;; Preserve the match data. Process filters and sentinels
418 ;; could run inside read-char..
419 (let ((data (match-data))
420 (help-form
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 (store-match-data data))
432 (cond ((or (= char ?\e)
433 (= char ?q))
434 (setq keep-going nil)
435 (setq done t))
436 ((= char ?^)
437 (let ((elt (car stack)))
438 (goto-char (car elt))
439 (setq replaced (eq t (cdr elt)))
440 (or replaced
441 (store-match-data (cdr elt)))
442 (setq stack (cdr stack))))
443 ((or (= char ?\ )
444 (= char ?y))
445 (or replaced
446 (replace-match next-replacement nocasify literal))
447 (setq done t replaced t))
448 ((= char ?\.)
449 (or replaced
450 (replace-match next-replacement nocasify literal))
451 (setq keep-going nil)
452 (setq done t replaced t))
453 ((= char ?\,)
454 (if (not replaced)
455 (progn
456 (replace-match next-replacement nocasify literal)
457 (setq replaced t))))
458 ((= char ?!)
459 (or replaced
460 (replace-match next-replacement nocasify literal))
461 (setq done t query-flag nil replaced t))
462 ((or (= char ?\177)
463 (= char ?n))
464 (setq done t))
465 ((= char ?\C-l)
466 (recenter nil))
467 ((= char ?\C-r)
468 (store-match-data
469 (prog1 (match-data)
da44e784
RM
470 (save-excursion (recursive-edit))))
471 ;; Before we make the replacement,
472 ;; decide whether the search string
473 ;; can match again just after this match.
474 (if regexp-flag
475 (setq match-again (looking-at search-string))))
698e1804
RS
476 ((= char ?\C-w)
477 (delete-region (match-beginning 0) (match-end 0))
478 (store-match-data
479 (prog1 (match-data)
480 (save-excursion (recursive-edit))))
481 (setq replaced t))
482 (t
483 (setq keep-going nil)
484 (setq unread-command-char char)
485 (setq done t))))
486 ;; Record previous position for ^ when we move on.
487 ;; Change markers to numbers in the match data
488 ;; since lots of markers slow down editing.
489 (setq stack
490 (cons (cons (point)
491 (or replaced
492 (mapcar
493 (function (lambda (elt)
494 (and elt
495 (marker-position elt))))
496 (match-data))))
497 stack))
498 (if replaced (setq replace-count (1+ replace-count)))))
499 (setq lastrepl (point)))
500 (and keep-going stack)))
501\f
502(defun map-query-replace-regexp (regexp to-strings &optional arg)
503 "Replace some matches for REGEXP with various strings, in rotation.
504The second argument TO-STRINGS contains the replacement strings, separated
505by spaces. This command works like `query-replace-regexp' except
da44e784
RM
506that each successive replacement uses the next successive replacement
507string, wrapping around from the last such string to the first.
698e1804
RS
508
509Non-interactively, TO-STRINGS may be a list of replacement strings.
510
511A prefix argument N says to use each replacement string N times
512before rotating to the next."
513 (interactive "sMap query replace (regexp): \nsQuery replace %s with (space-separated strings): \nP")
514 (let (replacements)
515 (if (listp to-strings)
516 (setq replacements to-strings)
517 (while (/= (length to-strings) 0)
518 (if (string-match " " to-strings)
519 (setq replacements
520 (append replacements
521 (list (substring to-strings 0
522 (string-match " " to-strings))))
523 to-strings (substring to-strings
524 (1+ (string-match " " to-strings))))
525 (setq replacements (append replacements (list to-strings))
526 to-strings ""))))
527 (perform-replace regexp replacements t t nil arg))
528 (message "Done"))
529