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.
21 (fset 'delete-non-matching-lines 'keep-lines)
22 (defun keep-lines (regexp)
23 "Delete all lines except those containing matches for REGEXP.
24 A match split across lines preserves all the lines it lies in.
25 Applies to all lines after point."
26 (interactive "sKeep lines (containing match for regexp): ")
28 (or (bolp) (forward-line 1))
29 (let ((start (point)))
31 ;; Start is first char not preserved by previous match.
32 (if (not (re-search-forward regexp nil 'move))
33 (delete-region start (point-max))
34 (let ((end (save-excursion (goto-char (match-beginning 0))
37 ;; Now end is first char preserved by the new match.
39 (delete-region start end))))
40 (setq start (save-excursion (forward-line 1)
42 ;; If the match was empty, avoid matching again at same place.
43 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
46 (fset 'delete-matching-lines 'flush-lines)
47 (defun flush-lines (regexp)
48 "Delete lines containing matches for REGEXP.
49 If a match is split across lines, all the lines it lies in are deleted.
50 Applies to lines after point."
51 (interactive "sFlush lines (containing match for regexp): ")
53 (while (and (not (eobp))
54 (re-search-forward regexp nil t))
55 (delete-region (save-excursion (goto-char (match-beginning 0))
58 (progn (forward-line 1) (point))))))
60 (fset 'count-matches 'how-many)
61 (defun how-many (regexp)
62 "Print number of matches for REGEXP following point."
63 (interactive "sHow many matches for (regexp): ")
64 (let ((count 0) opoint)
66 (while (and (not (eobp))
67 (progn (setq opoint (point))
68 (re-search-forward regexp nil t)))
69 (if (= opoint (point))
71 (setq count (1+ count))))
72 (message "%d occurrences" count))))
74 (defvar occur-mode-map ())
77 (setq occur-mode-map (make-sparse-keymap))
78 (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence))
80 (defvar occur-buffer nil)
81 (defvar occur-nlines nil)
82 (defvar occur-pos-list nil)
83 (defvar occur-last-string "")
86 "Major mode for output from \\[occur].
87 Move point to one of the occurrences in this buffer,
88 then use \\[occur-mode-goto-occurrence] to go to the same occurrence
89 in the buffer that the occurrences were found in.
91 (kill-all-local-variables)
92 (use-local-map occur-mode-map)
93 (setq major-mode 'occur-mode)
94 (setq mode-name "Occur")
95 (make-local-variable 'occur-buffer)
96 (make-local-variable 'occur-nlines)
97 (make-local-variable 'occur-pos-list))
99 (defun occur-mode-goto-occurrence ()
100 "Go to the line this occurrence was found in, in the buffer it was found in."
102 (if (or (null occur-buffer)
103 (null (buffer-name occur-buffer)))
105 (setq occur-buffer nil
107 (error "Buffer in which occurrences were found is deleted")))
108 (let* ((occur-number (save-excursion
110 (/ (1- (count-lines (point-min)
114 (cond ((< occur-nlines 0)
117 (+ 2 (* 2 occur-nlines)))
119 (pos (nth occur-number occur-pos-list)))
120 (pop-to-buffer occur-buffer)
121 (goto-char (marker-position pos))))
123 (defvar list-matching-lines-default-context-lines 0
124 "*Default number of context lines to include around a list-matching-lines
125 match. A negative number means to include that many lines before the match.
126 A positive number means to include that many lines both before and after.")
128 (defvar occur-whole-buffer nil
129 "If t, occur operates on whole buffer, otherwise occur starts from point.
132 (fset 'list-matching-lines 'occur)
134 (defun occur (regexp &optional nlines)
135 "Show lines containing a match for REGEXP. If the global variable
136 occur-whole-buffer is non-nil, the entire buffer is searched, otherwise
137 search begins at point. Interactively, REGEXP defaults to the last REGEXP
140 Each line is displayed with NLINES lines before and after,
141 or -NLINES before if NLINES is negative.
142 NLINES defaults to list-matching-lines-default-context-lines.
143 Interactively it is the prefix arg.
145 The lines are shown in a buffer named *Occur*.
146 It serves as a menu to find any of the occurrences in this buffer.
147 \\[describe-mode] in that buffer will explain how."
148 (interactive (list (setq occur-last-string
149 (read-string "List lines matching regexp: "
152 (setq nlines (if nlines (prefix-numeric-value nlines)
153 list-matching-lines-default-context-lines))
155 (buffer (current-buffer))
157 (prevpos (point-min)))
158 (if (not occur-whole-buffer)
161 (setq linenum (1+ (count-lines (point-min) (point))))
162 (setq prevpos (point))))
163 (with-output-to-temp-buffer "*Occur*"
165 (set-buffer standard-output)
166 (insert "Lines matching ")
168 (insert " in buffer " (buffer-name buffer) ?. ?\n)
170 (setq occur-buffer buffer)
171 (setq occur-nlines nlines)
172 (setq occur-pos-list ()))
173 (if (eq buffer standard-output)
174 (goto-char (point-max)))
176 (if occur-whole-buffer
177 (beginning-of-buffer))
178 ;; Find next match, but give up if prev match was at end of buffer.
179 (while (and (not (= prevpos (point-max)))
180 (re-search-forward regexp nil t))
182 (setq linenum (+ linenum (count-lines prevpos (point))))
183 (setq prevpos (point))
184 (let* ((start (save-excursion
185 (forward-line (if (< nlines 0) nlines (- nlines)))
189 (forward-line (1+ nlines))
192 (tag (format "%3d" linenum))
193 (empty (make-string (length tag) ?\ ))
196 (setq tem (make-marker))
197 (set-marker tem (point))
198 (set-buffer standard-output)
199 (setq occur-pos-list (cons tem occur-pos-list))
200 (or first (zerop nlines)
201 (insert "--------\n"))
203 (insert-buffer-substring buffer start end)
204 (backward-char (- end start))
205 (setq tem (if (< nlines 0) (- nlines) nlines))
212 (while (< tem nlines)
215 (setq tem (1+ tem))))
217 (set-buffer standard-output)
218 ;; Put positions in increasing order to go with buffer.
219 (setq occur-pos-list (nreverse occur-pos-list))
221 (message "%d matching lines." (length occur-pos-list)))))))
223 (defconst query-replace-help
224 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
225 ESC or `q' to exit, Period to replace one match and exit,
226 Comma to replace but not move point immediately,
227 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
228 C-w to delete match and recursive edit,
229 C-l to clear the screen, redisplay, and offer same replacement again,
230 ! to replace all remaining matches with no more questions,
231 ^ to move point back to previous match."
232 "Help message while in query-replace")
234 (defun perform-replace (from-string replacements
235 query-flag regexp-flag delimited-flag
236 &optional repeat-count)
237 "Subroutine of `query-replace'. Its complexity handles interactive queries.
238 Don't use this in your own program unless you want to query and set the mark
239 just as `query-replace' does. Instead, write a simple loop like this:
240 (while (re-search-forward \"foo[ \t]+bar\" nil t)
241 (replace-match \"foobar\" nil nil))
242 which will run faster and do exactly what you probably want."
243 (let ((nocasify (not (and case-fold-search case-replace
244 (string-equal from-string
245 (downcase from-string)))))
246 (literal (not regexp-flag))
247 (search-function (if regexp-flag 're-search-forward 'search-forward))
248 (search-string from-string)
249 (next-replacement nil)
250 (replacement-index 0)
253 (next-rotate-count 0)
255 (lastrepl nil)) ;Position after last match considered.
256 (if (stringp replacements)
257 (setq next-replacement replacements)
258 (or repeat-count (setq repeat-count 1)))
260 (setq search-function 're-search-forward
261 search-string (concat "\\b"
262 (if regexp-flag from-string
263 (regexp-quote from-string))
267 (while (and keep-going
269 (funcall search-function search-string nil t)
270 (if (eq lastrepl (point))
272 ;; Don't replace the null string
273 ;; right after end of previous replacement.
275 (funcall search-function search-string nil t))
277 ;; If time for a change, advance to next replacement string.
278 (if (and (listp replacements)
279 (= next-rotate-count replace-count))
281 (setq next-rotate-count
282 (+ next-rotate-count repeat-count))
283 (setq next-replacement (nth replacement-index replacements))
284 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
287 (replace-match next-replacement nocasify literal)
288 (setq replace-count (1+ replace-count)))
292 ;; Preserve the match data. Process filters and sentinels
293 ;; could run inside read-char..
294 (let ((data (match-data))
296 '(concat "Query replacing "
297 (if regexp-flag "regexp " "")
298 from-string " with " next-replacement ".\n\n"
299 (substitute-command-keys query-replace-help))))
300 (setq char help-char)
301 (while (or (not (numberp char)) (= char help-char))
302 (message "Query replacing %s with %s: " from-string next-replacement)
303 (setq char (read-event))
304 (if (and (numberp char) (= char ??))
305 (setq unread-command-char help-char char help-char)))
306 (store-match-data data))
307 (cond ((or (= char ?\e)
309 (setq keep-going nil)
312 (let ((elt (car stack)))
313 (goto-char (car elt))
314 (setq replaced (eq t (cdr elt)))
316 (store-match-data (cdr elt)))
317 (setq stack (cdr stack))))
321 (replace-match next-replacement nocasify literal))
322 (setq done t replaced t))
325 (replace-match next-replacement nocasify literal))
326 (setq keep-going nil)
327 (setq done t replaced t))
331 (replace-match next-replacement nocasify literal)
335 (replace-match next-replacement nocasify literal))
336 (setq done t query-flag nil replaced t))
345 (save-excursion (recursive-edit)))))
347 (delete-region (match-beginning 0) (match-end 0))
350 (save-excursion (recursive-edit))))
353 (setq keep-going nil)
354 (setq unread-command-char char)
356 ;; Record previous position for ^ when we move on.
357 ;; Change markers to numbers in the match data
358 ;; since lots of markers slow down editing.
363 (function (lambda (elt)
365 (marker-position elt))))
368 (if replaced (setq replace-count (1+ replace-count)))))
369 (setq lastrepl (point)))
370 (and keep-going stack)))
372 (defun map-query-replace-regexp (regexp to-strings &optional arg)
373 "Replace some matches for REGEXP with various strings, in rotation.
374 The second argument TO-STRINGS contains the replacement strings, separated
375 by spaces. This command works like `query-replace-regexp' except
376 that each successive replacement uses the next successive replacement string,
377 wrapping around from the last such string to the first.
379 Non-interactively, TO-STRINGS may be a list of replacement strings.
381 A prefix argument N says to use each replacement string N times
382 before rotating to the next."
383 (interactive "sMap query replace (regexp): \nsQuery replace %s with (space-separated strings): \nP")
385 (if (listp to-strings)
386 (setq replacements to-strings)
387 (while (/= (length to-strings) 0)
388 (if (string-match " " to-strings)
391 (list (substring to-strings 0
392 (string-match " " to-strings))))
393 to-strings (substring to-strings
394 (1+ (string-match " " to-strings))))
395 (setq replacements (append replacements (list to-strings))
397 (perform-replace regexp replacements t t nil arg))