Initial revision
[bpt/emacs.git] / lisp / replace.el
CommitLineData
698e1804
RS
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(fset 'delete-non-matching-lines 'keep-lines)
22(defun keep-lines (regexp)
23 "Delete all lines except those containing matches for REGEXP.
24A match split across lines preserves all the lines it lies in.
25Applies to all lines after point."
26 (interactive "sKeep lines (containing match for regexp): ")
27 (save-excursion
28 (or (bolp) (forward-line 1))
29 (let ((start (point)))
30 (while (not (eobp))
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))
35 (beginning-of-line)
36 (point))))
37 ;; Now end is first char preserved by the new match.
38 (if (< start end)
39 (delete-region start end))))
40 (setq start (save-excursion (forward-line 1)
41 (point)))
42 ;; If the match was empty, avoid matching again at same place.
43 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
44 (forward-char 1))))))
45
46(fset 'delete-matching-lines 'flush-lines)
47(defun flush-lines (regexp)
48 "Delete lines containing matches for REGEXP.
49If a match is split across lines, all the lines it lies in are deleted.
50Applies to lines after point."
51 (interactive "sFlush lines (containing match for regexp): ")
52 (save-excursion
53 (while (and (not (eobp))
54 (re-search-forward regexp nil t))
55 (delete-region (save-excursion (goto-char (match-beginning 0))
56 (beginning-of-line)
57 (point))
58 (progn (forward-line 1) (point))))))
59
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)
65 (save-excursion
66 (while (and (not (eobp))
67 (progn (setq opoint (point))
68 (re-search-forward regexp nil t)))
69 (if (= opoint (point))
70 (forward-char 1)
71 (setq count (1+ count))))
72 (message "%d occurrences" count))))
73
74(defvar occur-mode-map ())
75(if occur-mode-map
76 ()
77 (setq occur-mode-map (make-sparse-keymap))
78 (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence))
79
80(defvar occur-buffer nil)
81(defvar occur-nlines nil)
82(defvar occur-pos-list nil)
f1c9e147 83(defvar occur-last-string "")
698e1804
RS
84
85(defun occur-mode ()
86 "Major mode for output from \\[occur].
87Move point to one of the occurrences in this buffer,
88then use \\[occur-mode-goto-occurrence] to go to the same occurrence
89in the buffer that the occurrences were found in.
90\\{occur-mode-map}"
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))
98
99(defun occur-mode-goto-occurrence ()
100 "Go to the line this occurrence was found in, in the buffer it was found in."
101 (interactive)
102 (if (or (null occur-buffer)
103 (null (buffer-name occur-buffer)))
104 (progn
105 (setq occur-buffer nil
106 occur-pos-list nil)
107 (error "Buffer in which occurrences were found is deleted")))
108 (let* ((occur-number (save-excursion
109 (beginning-of-line)
110 (/ (1- (count-lines (point-min)
111 (save-excursion
112 (beginning-of-line)
113 (point))))
114 (cond ((< occur-nlines 0)
115 (- 2 occur-nlines))
116 ((> occur-nlines 0)
117 (+ 2 (* 2 occur-nlines)))
118 (t 1)))))
119 (pos (nth occur-number occur-pos-list)))
120 (pop-to-buffer occur-buffer)
121 (goto-char (marker-position pos))))
122
123(defvar list-matching-lines-default-context-lines 0
124 "*Default number of context lines to include around a list-matching-lines
125match. A negative number means to include that many lines before the match.
126A positive number means to include that many lines both before and after.")
127
128(defvar occur-whole-buffer nil
129 "If t, occur operates on whole buffer, otherwise occur starts from point.
130default is nil.")
131
132(fset 'list-matching-lines 'occur)
133
134(defun occur (regexp &optional nlines)
f1c9e147 135 "Show lines containing a match for REGEXP. If the global variable
698e1804 136occur-whole-buffer is non-nil, the entire buffer is searched, otherwise
f1c9e147 137search begins at point. Interactively, REGEXP defaults to the last REGEXP
138used interactively.
698e1804
RS
139
140Each line is displayed with NLINES lines before and after,
f1c9e147 141or -NLINES before if NLINES is negative.
698e1804
RS
142NLINES defaults to list-matching-lines-default-context-lines.
143Interactively it is the prefix arg.
144
145The lines are shown in a buffer named *Occur*.
146It serves as a menu to find any of the occurrences in this buffer.
147\\[describe-mode] in that buffer will explain how."
f1c9e147 148 (interactive (list (setq occur-last-string
149 (read-string "List lines matching regexp: "
150 occur-last-string))
151 current-prefix-arg))
698e1804
RS
152 (setq nlines (if nlines (prefix-numeric-value nlines)
153 list-matching-lines-default-context-lines))
154 (let ((first t)
155 (buffer (current-buffer))
156 (linenum 1)
157 (prevpos (point-min)))
158 (if (not occur-whole-buffer)
159 (save-excursion
160 (beginning-of-line)
161 (setq linenum (1+ (count-lines (point-min) (point))))
162 (setq prevpos (point))))
163 (with-output-to-temp-buffer "*Occur*"
164 (save-excursion
165 (set-buffer standard-output)
166 (insert "Lines matching ")
167 (prin1 regexp)
168 (insert " in buffer " (buffer-name buffer) ?. ?\n)
169 (occur-mode)
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)))
175 (save-excursion
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))
181 (beginning-of-line)
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)))
186 (point)))
187 (end (save-excursion
188 (if (> nlines 0)
189 (forward-line (1+ nlines))
190 (forward-line 1))
191 (point)))
192 (tag (format "%3d" linenum))
193 (empty (make-string (length tag) ?\ ))
194 tem)
195 (save-excursion
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"))
202 (setq first nil)
203 (insert-buffer-substring buffer start end)
204 (backward-char (- end start))
205 (setq tem (if (< nlines 0) (- nlines) nlines))
206 (while (> tem 0)
207 (insert empty ?:)
208 (forward-line 1)
209 (setq tem (1- tem)))
210 (insert tag ?:)
211 (forward-line 1)
212 (while (< tem nlines)
213 (insert empty ?:)
214 (forward-line 1)
215 (setq tem (1+ tem))))
216 (forward-line 1)))
217 (set-buffer standard-output)
218 ;; Put positions in increasing order to go with buffer.
219 (setq occur-pos-list (nreverse occur-pos-list))
220 (if (interactive-p)
221 (message "%d matching lines." (length occur-pos-list)))))))
222\f
223(defconst query-replace-help
224 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
225ESC or `q' to exit, Period to replace one match and exit,
226Comma to replace but not move point immediately,
227C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
228C-w to delete match and recursive edit,
229C-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")
233
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.
238Don't use this in your own program unless you want to query and set the mark
239just 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))
242which 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)
251 (keep-going t)
252 (stack nil)
253 (next-rotate-count 0)
254 (replace-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)))
259 (if delimited-flag
260 (setq search-function 're-search-forward
261 search-string (concat "\\b"
262 (if regexp-flag from-string
263 (regexp-quote from-string))
264 "\\b")))
265 (push-mark)
266 (undo-boundary)
267 (while (and keep-going
268 (not (eobp))
269 (funcall search-function search-string nil t)
270 (if (eq lastrepl (point))
271 (progn
272 ;; Don't replace the null string
273 ;; right after end of previous replacement.
274 (forward-char 1)
275 (funcall search-function search-string nil t))
276 t))
277 ;; If time for a change, advance to next replacement string.
278 (if (and (listp replacements)
279 (= next-rotate-count replace-count))
280 (progn
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)))))
285 (if (not query-flag)
286 (progn
287 (replace-match next-replacement nocasify literal)
288 (setq replace-count (1+ replace-count)))
289 (undo-boundary)
290 (let (done replaced)
291 (while (not done)
292 ;; Preserve the match data. Process filters and sentinels
293 ;; could run inside read-char..
294 (let ((data (match-data))
295 (help-form
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)
308 (= char ?q))
309 (setq keep-going nil)
310 (setq done t))
311 ((= char ?^)
312 (let ((elt (car stack)))
313 (goto-char (car elt))
314 (setq replaced (eq t (cdr elt)))
315 (or replaced
316 (store-match-data (cdr elt)))
317 (setq stack (cdr stack))))
318 ((or (= char ?\ )
319 (= char ?y))
320 (or replaced
321 (replace-match next-replacement nocasify literal))
322 (setq done t replaced t))
323 ((= char ?\.)
324 (or replaced
325 (replace-match next-replacement nocasify literal))
326 (setq keep-going nil)
327 (setq done t replaced t))
328 ((= char ?\,)
329 (if (not replaced)
330 (progn
331 (replace-match next-replacement nocasify literal)
332 (setq replaced t))))
333 ((= char ?!)
334 (or replaced
335 (replace-match next-replacement nocasify literal))
336 (setq done t query-flag nil replaced t))
337 ((or (= char ?\177)
338 (= char ?n))
339 (setq done t))
340 ((= char ?\C-l)
341 (recenter nil))
342 ((= char ?\C-r)
343 (store-match-data
344 (prog1 (match-data)
345 (save-excursion (recursive-edit)))))
346 ((= char ?\C-w)
347 (delete-region (match-beginning 0) (match-end 0))
348 (store-match-data
349 (prog1 (match-data)
350 (save-excursion (recursive-edit))))
351 (setq replaced t))
352 (t
353 (setq keep-going nil)
354 (setq unread-command-char char)
355 (setq done t))))
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.
359 (setq stack
360 (cons (cons (point)
361 (or replaced
362 (mapcar
363 (function (lambda (elt)
364 (and elt
365 (marker-position elt))))
366 (match-data))))
367 stack))
368 (if replaced (setq replace-count (1+ replace-count)))))
369 (setq lastrepl (point)))
370 (and keep-going stack)))
371\f
372(defun map-query-replace-regexp (regexp to-strings &optional arg)
373 "Replace some matches for REGEXP with various strings, in rotation.
374The second argument TO-STRINGS contains the replacement strings, separated
375by spaces. This command works like `query-replace-regexp' except
376that each successive replacement uses the next successive replacement string,
377wrapping around from the last such string to the first.
378
379Non-interactively, TO-STRINGS may be a list of replacement strings.
380
381A prefix argument N says to use each replacement string N times
382before rotating to the next."
383 (interactive "sMap query replace (regexp): \nsQuery replace %s with (space-separated strings): \nP")
384 (let (replacements)
385 (if (listp to-strings)
386 (setq replacements to-strings)
387 (while (/= (length to-strings) 0)
388 (if (string-match " " to-strings)
389 (setq replacements
390 (append replacements
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))
396 to-strings ""))))
397 (perform-replace regexp replacements t t nil arg))
398 (message "Done"))
399