1 ;; Replace commands for Emacs.
2 ;; Copyright (C) 1985, 1986 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 (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.
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)
34 ;;;###autoload (define-key esc-map "%" 'query-replace)
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.
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)
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.
60 Non-interactively, TO-STRINGS may be a list of replacement strings.
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")
66 (if (listp to-strings)
67 (setq replacements to-strings)
68 (while (/= (length to-strings) 0)
69 (if (string-match " " to-strings)
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))
78 (perform-replace regexp replacements t t nil arg))
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.
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)
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.
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)
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): ")
124 (or (bolp) (forward-line 1))
125 (let ((start (point)))
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))
133 ;; Now end is first char preserved by the new match.
135 (delete-region start end))))
136 (setq start (save-excursion (forward-line 1)
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))))))
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): ")
149 (while (and (not (eobp))
150 (re-search-forward regexp nil t))
151 (delete-region (save-excursion (goto-char (match-beginning 0))
154 (progn (forward-line 1) (point))))))
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)
162 (while (and (not (eobp))
163 (progn (setq opoint (point))
164 (re-search-forward regexp nil t)))
165 (if (= opoint (point))
167 (setq count (1+ count))))
168 (message "%d occurrences" count))))
170 (defvar occur-mode-map ())
173 (setq occur-mode-map (make-sparse-keymap))
174 (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence))
176 (defvar occur-buffer nil)
177 (defvar occur-nlines nil)
178 (defvar occur-pos-list nil)
179 (defvar occur-last-string "")
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.
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))
195 (defun occur-mode-goto-occurrence ()
196 "Go to the line this occurrence was found in, in the buffer it was found in."
198 (if (or (null occur-buffer)
199 (null (buffer-name occur-buffer)))
201 (setq occur-buffer nil
203 (error "Buffer in which occurrences were found is deleted")))
204 (let* ((occur-number (save-excursion
206 (/ (1- (count-lines (point-min)
210 (cond ((< occur-nlines 0)
213 (+ 2 (* 2 occur-nlines)))
215 (pos (nth occur-number occur-pos-list)))
216 (pop-to-buffer occur-buffer)
217 (goto-char (marker-position pos))))
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.")
224 (defvar occur-whole-buffer nil
225 "If t, occur operates on whole buffer, otherwise occur starts from point.
228 (fset 'list-matching-lines 'occur)
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].
236 If a match spreads across multiple lines, all those lines are shown.
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.
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: "
250 (setq nlines (if nlines (prefix-numeric-value nlines)
251 list-matching-lines-default-context-lines))
253 (buffer (current-buffer))
255 (prevpos (point-min)))
256 (if (not occur-whole-buffer)
259 (setq linenum (1+ (count-lines (point-min) (point))))
260 (setq prevpos (point))))
261 (with-output-to-temp-buffer "*Occur*"
263 (set-buffer standard-output)
264 (insert "Lines matching ")
266 (insert " in buffer " (buffer-name buffer) ?. ?\n)
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)))
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))
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)))
289 (goto-char (match-end 0))
291 (forward-line (1+ nlines))
294 (tag (format "%3d" linenum))
295 (empty (make-string (length tag) ?\ ))
298 (set-buffer standard-output)
299 (setq occur-pos-list (cons tem occur-pos-list))
300 (or first (zerop nlines)
301 (insert "--------\n"))
303 (insert-buffer-substring buffer start end)
304 (backward-char (- end start))
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)
316 (setq tag (format "%3d" this-linenum)))
320 (setq this-linenum (1+ this-linenum))))
321 (while (< tem nlines)
324 (setq tem (1+ tem))))
326 (set-buffer standard-output)
327 ;; Put positions in increasing order to go with buffer.
328 (setq occur-pos-list (nreverse occur-pos-list))
330 (message "%d matching lines." (length occur-pos-list)))))))
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")
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)
363 (next-rotate-count 0)
365 (lastrepl nil) ;Position after last match considered.
367 (if (stringp replacements)
368 (setq next-replacement replacements)
369 (or repeat-count (setq repeat-count 1)))
371 (setq search-function 're-search-forward
372 search-string (concat "\\b"
373 (if regexp-flag from-string
374 (regexp-quote from-string))
378 (while (and keep-going
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))
386 (eq lastrepl (match-beginning 0))
390 ;; Don't replace the null string
391 ;; right after end of previous replacement.
393 (funcall search-function search-string nil t))
395 ;; Before we make the replacement, decide whether the search string
396 ;; can match again just after this match.
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))
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)))))
409 (replace-match next-replacement nocasify literal)
410 (setq replace-count (1+ replace-count)))
414 ;; Preserve the match data. Process filters and sentinels
415 ;; could run inside read-char..
416 (let ((data (match-data))
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)
431 (setq keep-going nil)
434 (let ((elt (car stack)))
435 (goto-char (car elt))
436 (setq replaced (eq t (cdr elt)))
438 (store-match-data (cdr elt)))
439 (setq stack (cdr stack))))
443 (replace-match next-replacement nocasify literal))
444 (setq done t replaced t))
447 (replace-match next-replacement nocasify literal))
448 (setq keep-going nil)
449 (setq done t replaced t))
453 (replace-match next-replacement nocasify literal)
457 (replace-match next-replacement nocasify literal))
458 (setq done t query-flag nil replaced t))
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.
472 (setq match-again (looking-at search-string))))
474 (delete-region (match-beginning 0) (match-end 0))
477 (save-excursion (recursive-edit))))
480 (setq keep-going nil)
481 (setq unread-command-char char)
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.
490 (function (lambda (elt)
492 (marker-position elt))))
495 (if replaced (setq replace-count (1+ replace-count)))))
496 (setq lastrepl (point)))
497 (and keep-going stack)))
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.
506 Non-interactively, TO-STRINGS may be a list of replacement strings.
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")
512 (if (listp to-strings)
513 (setq replacements to-strings)
514 (while (/= (length to-strings) 0)
515 (if (string-match " " to-strings)
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))
524 (perform-replace regexp replacements t t nil arg))