1 ;; Replace commands for Emacs.
2 ;; Copyright (C) 1985-1991 Free Software Foundation, Inc.
4 ;; This file is part of GNU Emacs.
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)
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.
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.
22 (defconst case-replace t
"\
23 *Non-nil means query-replace should preserve case in replacements.")
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.
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
)
39 (define-key esc-map
"%" 'query-replace
)
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.
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
)
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.
65 Non-interactively, TO-STRINGS may be a list of replacement strings.
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")
71 (if (listp to-strings
)
72 (setq replacements to-strings
)
73 (while (/= (length to-strings
) 0)
74 (if (string-match " " to-strings
)
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
))
83 (perform-replace regexp replacements t t nil arg
))
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.
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
)
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.
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
)
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): ")
129 (or (bolp) (forward-line 1))
130 (let ((start (point)))
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))
138 ;; Now end is first char preserved by the new match.
140 (delete-region start end
))))
141 (setq start
(save-excursion (forward-line 1)
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))))))
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): ")
154 (while (and (not (eobp))
155 (re-search-forward regexp nil t
))
156 (delete-region (save-excursion (goto-char (match-beginning 0))
159 (progn (forward-line 1) (point))))))
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
)
167 (while (and (not (eobp))
168 (progn (setq opoint
(point))
169 (re-search-forward regexp nil t
)))
170 (if (= opoint
(point))
172 (setq count
(1+ count
))))
173 (message "%d occurrences" count
))))
175 (defvar occur-mode-map
())
178 (setq occur-mode-map
(make-sparse-keymap))
179 (define-key occur-mode-map
"\C-c\C-c" 'occur-mode-goto-occurrence
))
181 (defvar occur-buffer nil
)
182 (defvar occur-nlines nil
)
183 (defvar occur-pos-list nil
)
184 (defvar occur-last-string
"")
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.
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
))
200 (defun occur-mode-goto-occurrence ()
201 "Go to the line this occurrence was found in, in the buffer it was found in."
203 (if (or (null occur-buffer
)
204 (null (buffer-name occur-buffer
)))
206 (setq occur-buffer nil
208 (error "Buffer in which occurrences were found is deleted")))
209 (let* ((occur-number (save-excursion
211 (/ (1- (count-lines (point-min)
215 (cond ((< occur-nlines
0)
218 (+ 2 (* 2 occur-nlines
)))
220 (pos (nth occur-number occur-pos-list
)))
221 (pop-to-buffer occur-buffer
)
222 (goto-char (marker-position pos
))))
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.")
229 (defvar occur-whole-buffer nil
230 "If t, occur operates on whole buffer, otherwise occur starts from point.
233 (fset 'list-matching-lines
'occur
)
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].
241 If a match spreads across multiple lines, all those lines are shown.
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.
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: "
255 (setq nlines
(if nlines
(prefix-numeric-value nlines
)
256 list-matching-lines-default-context-lines
))
258 (buffer (current-buffer))
260 (prevpos (point-min))
261 (final-context-start (make-marker)))
262 (if (not occur-whole-buffer
)
265 (setq linenum
(1+ (count-lines (point-min) (point))))
266 (setq prevpos
(point))))
267 (with-output-to-temp-buffer "*Occur*"
269 (set-buffer standard-output
)
270 (insert "Lines matching ")
272 (insert " in buffer " (buffer-name buffer
) ?. ?
\n)
274 (setq occur-buffer buffer
)
275 (setq occur-nlines nlines
)
276 (setq occur-pos-list
()))
277 (if (eq buffer standard-output
)
278 (goto-char (point-max)))
280 (if occur-whole-buffer
281 (beginning-of-buffer))
282 ;; Find next match, but give up if prev match was at end of buffer.
283 (while (and (not (= prevpos
(point-max)))
284 (re-search-forward regexp nil t
))
285 (goto-char (match-beginning 0))
287 (setq linenum
(+ linenum
(count-lines prevpos
(point))))
288 (setq prevpos
(point))
289 (goto-char (match-end 0))
290 (let* ((start (save-excursion
291 (goto-char (match-beginning 0))
292 (forward-line (if (< nlines
0) nlines
(- nlines
)))
295 (goto-char (match-end 0))
297 (forward-line (1+ nlines
))
300 (tag (format "%3d" linenum
))
301 (empty (make-string (length tag
) ?\
))
304 (setq tem
(make-marker))
305 (set-marker tem
(point))
306 (set-buffer standard-output
)
307 (setq occur-pos-list
(cons tem occur-pos-list
))
308 (or first
(zerop nlines
)
309 (insert "--------\n"))
311 (insert-buffer-substring buffer start end
)
312 (backward-char (- end start
))
318 (let ((this-linenum linenum
))
319 (set-marker final-context-start
320 (+ (point) (- (match-end 0) (match-beginning 0))))
321 (while (< (point) final-context-start
)
323 (setq tag
(format "%3d" this-linenum
)))
327 (setq this-linenum
(1+ this-linenum
))))
328 (while (< tem nlines
)
331 (setq tem
(1+ tem
))))
333 (set-buffer standard-output
)
334 ;; Put positions in increasing order to go with buffer.
335 (setq occur-pos-list
(nreverse occur-pos-list
))
337 (message "%d matching lines." (length occur-pos-list
)))))))
339 (defconst query-replace-help
340 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
341 ESC or `q' to exit, Period to replace one match and exit,
342 Comma to replace but not move point immediately,
343 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
344 C-w to delete match and recursive edit,
345 C-l to clear the screen, redisplay, and offer same replacement again,
346 ! to replace all remaining matches with no more questions,
347 ^ to move point back to previous match."
348 "Help message while in query-replace")
351 (defun perform-replace (from-string replacements
352 query-flag regexp-flag delimited-flag
353 &optional repeat-count
)
354 "Subroutine of `query-replace'. Its complexity handles interactive queries.
355 Don't use this in your own program unless you want to query and set the mark
356 just as `query-replace' does. Instead, write a simple loop like this:
357 (while (re-search-forward \"foo[ \t]+bar\" nil t)
358 (replace-match \"foobar\" nil nil))
359 which will run faster and do exactly what you probably want."
360 (let ((nocasify (not (and case-fold-search case-replace
361 (string-equal from-string
362 (downcase from-string
)))))
363 (literal (not regexp-flag
))
364 (search-function (if regexp-flag
're-search-forward
'search-forward
))
365 (search-string from-string
)
366 (next-replacement nil
)
367 (replacement-index 0)
370 (next-rotate-count 0)
372 (lastrepl nil
) ;Position after last match considered.
374 (if (stringp replacements
)
375 (setq next-replacement replacements
)
376 (or repeat-count
(setq repeat-count
1)))
378 (setq search-function
're-search-forward
379 search-string
(concat "\\b"
380 (if regexp-flag from-string
381 (regexp-quote from-string
))
385 (while (and keep-going
387 (funcall search-function search-string nil t
)
388 ;; If the search string matches immediately after
389 ;; the previous match, but it did not match there
390 ;; before the replacement was done, ignore the match.
391 (if (or (eq lastrepl
(point))
393 (eq lastrepl
(match-beginning 0))
397 ;; Don't replace the null string
398 ;; right after end of previous replacement.
400 (funcall search-function search-string nil t
))
402 ;; Before we make the replacement, decide whether the search string
403 ;; can match again just after this match.
405 (setq match-again
(looking-at search-string
)))
406 ;; If time for a change, advance to next replacement string.
407 (if (and (listp replacements
)
408 (= next-rotate-count replace-count
))
410 (setq next-rotate-count
411 (+ next-rotate-count repeat-count
))
412 (setq next-replacement
(nth replacement-index replacements
))
413 (setq replacement-index
(%
(1+ replacement-index
) (length replacements
)))))
416 (replace-match next-replacement nocasify literal
)
417 (setq replace-count
(1+ replace-count
)))
421 ;; Preserve the match data. Process filters and sentinels
422 ;; could run inside read-char..
423 (let ((data (match-data))
425 '(concat "Query replacing "
426 (if regexp-flag
"regexp " "")
427 from-string
" with " next-replacement
".\n\n"
428 (substitute-command-keys query-replace-help
))))
429 (setq char help-char
)
430 (while (or (not (numberp char
)) (= char help-char
))
431 (message "Query replacing %s with %s: " from-string next-replacement
)
432 (setq char
(read-event))
433 (if (and (numberp char
) (= char ??
))
434 (setq unread-command-char help-char char help-char
)))
435 (store-match-data data
))
436 (cond ((or (= char ?\e
)
438 (setq keep-going nil
)
441 (let ((elt (car stack
)))
442 (goto-char (car elt
))
443 (setq replaced
(eq t
(cdr elt
)))
445 (store-match-data (cdr elt
)))
446 (setq stack
(cdr stack
))))
450 (replace-match next-replacement nocasify literal
))
451 (setq done t replaced t
))
454 (replace-match next-replacement nocasify literal
))
455 (setq keep-going nil
)
456 (setq done t replaced t
))
460 (replace-match next-replacement nocasify literal
)
464 (replace-match next-replacement nocasify literal
))
465 (setq done t query-flag nil replaced t
))
474 (save-excursion (recursive-edit))))
475 ;; Before we make the replacement,
476 ;; decide whether the search string
477 ;; can match again just after this match.
479 (setq match-again
(looking-at search-string
))))
481 (delete-region (match-beginning 0) (match-end 0))
484 (save-excursion (recursive-edit))))
487 (setq keep-going nil
)
488 (setq unread-command-char char
)
490 ;; Record previous position for ^ when we move on.
491 ;; Change markers to numbers in the match data
492 ;; since lots of markers slow down editing.
497 (function (lambda (elt)
499 (marker-position elt
))))
502 (if replaced
(setq replace-count
(1+ replace-count
)))))
503 (setq lastrepl
(point)))
504 (and keep-going stack
)))
506 (defun map-query-replace-regexp (regexp to-strings
&optional arg
)
507 "Replace some matches for REGEXP with various strings, in rotation.
508 The second argument TO-STRINGS contains the replacement strings, separated
509 by spaces. This command works like `query-replace-regexp' except
510 that each successive replacement uses the next successive replacement
511 string, wrapping around from the last such string to the first.
513 Non-interactively, TO-STRINGS may be a list of replacement strings.
515 A prefix argument N says to use each replacement string N times
516 before rotating to the next."
517 (interactive "sMap query replace (regexp): \nsQuery replace %s with (space-separated strings): \nP")
519 (if (listp to-strings
)
520 (setq replacements to-strings
)
521 (while (/= (length to-strings
) 0)
522 (if (string-match " " to-strings
)
525 (list (substring to-strings
0
526 (string-match " " to-strings
))))
527 to-strings
(substring to-strings
528 (1+ (string-match " " to-strings
))))
529 (setq replacements
(append replacements
(list to-strings
))
531 (perform-replace regexp replacements t t nil arg
))