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