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