]> code.delx.au - gnu-emacs/blob - lisp/replace.el
*** empty log message ***
[gnu-emacs] / 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 (if (not occur-whole-buffer)
262 (save-excursion
263 (beginning-of-line)
264 (setq linenum (1+ (count-lines (point-min) (point))))
265 (setq prevpos (point))))
266 (with-output-to-temp-buffer "*Occur*"
267 (save-excursion
268 (set-buffer standard-output)
269 (insert "Lines matching ")
270 (prin1 regexp)
271 (insert " in buffer " (buffer-name buffer) ?. ?\n)
272 (occur-mode)
273 (setq occur-buffer buffer)
274 (setq occur-nlines nlines)
275 (setq occur-pos-list ()))
276 (if (eq buffer standard-output)
277 (goto-char (point-max)))
278 (save-excursion
279 (if occur-whole-buffer
280 (beginning-of-buffer))
281 ;; Find next match, but give up if prev match was at end of buffer.
282 (while (and (not (= prevpos (point-max)))
283 (re-search-forward regexp nil t))
284 (goto-char (match-beginning 0))
285 (beginning-of-line)
286 (setq linenum (+ linenum (count-lines prevpos (point))))
287 (setq prevpos (point))
288 (goto-char (match-end 0))
289 (let* ((start (save-excursion
290 (goto-char (match-beginning 0))
291 (forward-line (if (< nlines 0) nlines (- nlines)))
292 (point)))
293 (end (save-excursion
294 (goto-char (match-end 0))
295 (if (> nlines 0)
296 (forward-line (1+ nlines))
297 (forward-line 1))
298 (point)))
299 (tag (format "%3d" linenum))
300 (empty (make-string (length tag) ?\ ))
301 tem)
302 (save-excursion
303 (set-buffer standard-output)
304 (setq occur-pos-list (cons tem occur-pos-list))
305 (or first (zerop nlines)
306 (insert "--------\n"))
307 (setq first nil)
308 (insert-buffer-substring buffer start end)
309 (backward-char (- end start))
310 (setq tem nlines)
311 (while (> tem 0)
312 (insert empty ?:)
313 (forward-line 1)
314 (setq tem (1- tem)))
315 (let ((final-context-start (make-marker))
316 (this-linenum linenum))
317 (set-marker final-context-start
318 (+ (point) (- (match-end 0) (match-beginning 0))))
319 (while (< (point) final-context-start)
320 (if (null tag)
321 (setq tag (format "%3d" this-linenum)))
322 (insert tag ?:)
323 (setq tag nil)
324 (forward-line 1)
325 (setq this-linenum (1+ this-linenum))))
326 (while (< tem nlines)
327 (insert empty ?:)
328 (forward-line 1)
329 (setq tem (1+ tem))))
330 (forward-line 1)))
331 (set-buffer standard-output)
332 ;; Put positions in increasing order to go with buffer.
333 (setq occur-pos-list (nreverse occur-pos-list))
334 (if (interactive-p)
335 (message "%d matching lines." (length occur-pos-list)))))))
336 \f
337 (defconst query-replace-help
338 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
339 ESC or `q' to exit, Period to replace one match and exit,
340 Comma to replace but not move point immediately,
341 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
342 C-w to delete match and recursive edit,
343 C-l to clear the screen, redisplay, and offer same replacement again,
344 ! to replace all remaining matches with no more questions,
345 ^ to move point back to previous match."
346 "Help message while in query-replace")
347
348 ;;;###autoload
349 (defun perform-replace (from-string replacements
350 query-flag regexp-flag delimited-flag
351 &optional repeat-count)
352 "Subroutine of `query-replace'. Its complexity handles interactive queries.
353 Don't use this in your own program unless you want to query and set the mark
354 just as `query-replace' does. Instead, write a simple loop like this:
355 (while (re-search-forward \"foo[ \t]+bar\" nil t)
356 (replace-match \"foobar\" nil nil))
357 which will run faster and do exactly what you probably want."
358 (let ((nocasify (not (and case-fold-search case-replace
359 (string-equal from-string
360 (downcase from-string)))))
361 (literal (not regexp-flag))
362 (search-function (if regexp-flag 're-search-forward 'search-forward))
363 (search-string from-string)
364 (next-replacement nil)
365 (replacement-index 0)
366 (keep-going t)
367 (stack nil)
368 (next-rotate-count 0)
369 (replace-count 0)
370 (lastrepl nil) ;Position after last match considered.
371 (match-after t))
372 (if (stringp replacements)
373 (setq next-replacement replacements)
374 (or repeat-count (setq repeat-count 1)))
375 (if delimited-flag
376 (setq search-function 're-search-forward
377 search-string (concat "\\b"
378 (if regexp-flag from-string
379 (regexp-quote from-string))
380 "\\b")))
381 (push-mark)
382 (undo-boundary)
383 (while (and keep-going
384 (not (eobp))
385 (funcall search-function search-string nil t)
386 ;; If the search string matches immediately after
387 ;; the previous match, but it did not match there
388 ;; before the replacement was done, ignore the match.
389 (if (or (eq lastrepl (point))
390 (and regexp-flag
391 (eq lastrepl (match-beginning 0))
392 (not match-again)))
393 (if (eobp)
394 nil
395 ;; Don't replace the null string
396 ;; right after end of previous replacement.
397 (forward-char 1)
398 (funcall search-function search-string nil t))
399 t))
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)))
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
414 (replace-match next-replacement nocasify literal)
415 (setq replace-count (1+ replace-count)))
416 (undo-boundary)
417 (let (done replaced)
418 (while (not done)
419 ;; Preserve the match data. Process filters and sentinels
420 ;; could run inside read-char..
421 (let ((data (match-data))
422 (help-form
423 '(concat "Query replacing "
424 (if regexp-flag "regexp " "")
425 from-string " with " next-replacement ".\n\n"
426 (substitute-command-keys query-replace-help))))
427 (setq char help-char)
428 (while (or (not (numberp char)) (= char help-char))
429 (message "Query replacing %s with %s: " from-string next-replacement)
430 (setq char (read-event))
431 (if (and (numberp char) (= char ??))
432 (setq unread-command-char help-char char help-char)))
433 (store-match-data data))
434 (cond ((or (= char ?\e)
435 (= char ?q))
436 (setq keep-going nil)
437 (setq done t))
438 ((= char ?^)
439 (let ((elt (car stack)))
440 (goto-char (car elt))
441 (setq replaced (eq t (cdr elt)))
442 (or replaced
443 (store-match-data (cdr elt)))
444 (setq stack (cdr stack))))
445 ((or (= char ?\ )
446 (= char ?y))
447 (or replaced
448 (replace-match next-replacement nocasify literal))
449 (setq done t replaced t))
450 ((= char ?\.)
451 (or replaced
452 (replace-match next-replacement nocasify literal))
453 (setq keep-going nil)
454 (setq done t replaced t))
455 ((= char ?\,)
456 (if (not replaced)
457 (progn
458 (replace-match next-replacement nocasify literal)
459 (setq replaced t))))
460 ((= char ?!)
461 (or replaced
462 (replace-match next-replacement nocasify literal))
463 (setq done t query-flag nil replaced t))
464 ((or (= char ?\177)
465 (= char ?n))
466 (setq done t))
467 ((= char ?\C-l)
468 (recenter nil))
469 ((= char ?\C-r)
470 (store-match-data
471 (prog1 (match-data)
472 (save-excursion (recursive-edit))))
473 ;; Before we make the replacement,
474 ;; decide whether the search string
475 ;; can match again just after this match.
476 (if regexp-flag
477 (setq match-again (looking-at search-string))))
478 ((= char ?\C-w)
479 (delete-region (match-beginning 0) (match-end 0))
480 (store-match-data
481 (prog1 (match-data)
482 (save-excursion (recursive-edit))))
483 (setq replaced t))
484 (t
485 (setq keep-going nil)
486 (setq unread-command-char char)
487 (setq done t))))
488 ;; Record previous position for ^ when we move on.
489 ;; Change markers to numbers in the match data
490 ;; since lots of markers slow down editing.
491 (setq stack
492 (cons (cons (point)
493 (or replaced
494 (mapcar
495 (function (lambda (elt)
496 (and elt
497 (marker-position elt))))
498 (match-data))))
499 stack))
500 (if replaced (setq replace-count (1+ replace-count)))))
501 (setq lastrepl (point)))
502 (and keep-going stack)))
503 \f
504 (defun map-query-replace-regexp (regexp to-strings &optional arg)
505 "Replace some matches for REGEXP with various strings, in rotation.
506 The second argument TO-STRINGS contains the replacement strings, separated
507 by spaces. This command works like `query-replace-regexp' except
508 that each successive replacement uses the next successive replacement
509 string, wrapping around from the last such string to the first.
510
511 Non-interactively, TO-STRINGS may be a list of replacement strings.
512
513 A prefix argument N says to use each replacement string N times
514 before rotating to the next."
515 (interactive "sMap query replace (regexp): \nsQuery replace %s with (space-separated strings): \nP")
516 (let (replacements)
517 (if (listp to-strings)
518 (setq replacements to-strings)
519 (while (/= (length to-strings) 0)
520 (if (string-match " " to-strings)
521 (setq replacements
522 (append replacements
523 (list (substring to-strings 0
524 (string-match " " to-strings))))
525 to-strings (substring to-strings
526 (1+ (string-match " " to-strings))))
527 (setq replacements (append replacements (list to-strings))
528 to-strings ""))))
529 (perform-replace regexp replacements t t nil arg))
530 (message "Done"))
531