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