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)
83
84(defun occur-mode ()
85 "Major mode for output from \\[occur].
86Move point to one of the occurrences in this buffer,
87then use \\[occur-mode-goto-occurrence] to go to the same occurrence
88in the buffer that the occurrences were found in.
89\\{occur-mode-map}"
90 (kill-all-local-variables)
91 (use-local-map occur-mode-map)
92 (setq major-mode 'occur-mode)
93 (setq mode-name "Occur")
94 (make-local-variable 'occur-buffer)
95 (make-local-variable 'occur-nlines)
96 (make-local-variable 'occur-pos-list))
97
98(defun occur-mode-goto-occurrence ()
99 "Go to the line this occurrence was found in, in the buffer it was found in."
100 (interactive)
101 (if (or (null occur-buffer)
102 (null (buffer-name occur-buffer)))
103 (progn
104 (setq occur-buffer nil
105 occur-pos-list nil)
106 (error "Buffer in which occurrences were found is deleted")))
107 (let* ((occur-number (save-excursion
108 (beginning-of-line)
109 (/ (1- (count-lines (point-min)
110 (save-excursion
111 (beginning-of-line)
112 (point))))
113 (cond ((< occur-nlines 0)
114 (- 2 occur-nlines))
115 ((> occur-nlines 0)
116 (+ 2 (* 2 occur-nlines)))
117 (t 1)))))
118 (pos (nth occur-number occur-pos-list)))
119 (pop-to-buffer occur-buffer)
120 (goto-char (marker-position pos))))
121
122(defvar list-matching-lines-default-context-lines 0
123 "*Default number of context lines to include around a list-matching-lines
124match. A negative number means to include that many lines before the match.
125A positive number means to include that many lines both before and after.")
126
127(defvar occur-whole-buffer nil
128 "If t, occur operates on whole buffer, otherwise occur starts from point.
129default is nil.")
130
131(fset 'list-matching-lines 'occur)
132
133(defun occur (regexp &optional nlines)
134 "Show lines containing a match for REGEXP. If the global variable
135occur-whole-buffer is non-nil, the entire buffer is searched, otherwise
136search begins at point.
137
138Each line is displayed with NLINES lines before and after,
139 or -NLINES before if NLINES is negative.
140NLINES defaults to list-matching-lines-default-context-lines.
141Interactively it is the prefix arg.
142
143The lines are shown in a buffer named *Occur*.
144It serves as a menu to find any of the occurrences in this buffer.
145\\[describe-mode] in that buffer will explain how."
146 (interactive "sList lines matching regexp: \nP")
147 (setq nlines (if nlines (prefix-numeric-value nlines)
148 list-matching-lines-default-context-lines))
149 (let ((first t)
150 (buffer (current-buffer))
151 (linenum 1)
152 (prevpos (point-min)))
153 (if (not occur-whole-buffer)
154 (save-excursion
155 (beginning-of-line)
156 (setq linenum (1+ (count-lines (point-min) (point))))
157 (setq prevpos (point))))
158 (with-output-to-temp-buffer "*Occur*"
159 (save-excursion
160 (set-buffer standard-output)
161 (insert "Lines matching ")
162 (prin1 regexp)
163 (insert " in buffer " (buffer-name buffer) ?. ?\n)
164 (occur-mode)
165 (setq occur-buffer buffer)
166 (setq occur-nlines nlines)
167 (setq occur-pos-list ()))
168 (if (eq buffer standard-output)
169 (goto-char (point-max)))
170 (save-excursion
171 (if occur-whole-buffer
172 (beginning-of-buffer))
173 ;; Find next match, but give up if prev match was at end of buffer.
174 (while (and (not (= prevpos (point-max)))
175 (re-search-forward regexp nil t))
176 (beginning-of-line)
177 (setq linenum (+ linenum (count-lines prevpos (point))))
178 (setq prevpos (point))
179 (let* ((start (save-excursion
180 (forward-line (if (< nlines 0) nlines (- nlines)))
181 (point)))
182 (end (save-excursion
183 (if (> nlines 0)
184 (forward-line (1+ nlines))
185 (forward-line 1))
186 (point)))
187 (tag (format "%3d" linenum))
188 (empty (make-string (length tag) ?\ ))
189 tem)
190 (save-excursion
191 (setq tem (make-marker))
192 (set-marker tem (point))
193 (set-buffer standard-output)
194 (setq occur-pos-list (cons tem occur-pos-list))
195 (or first (zerop nlines)
196 (insert "--------\n"))
197 (setq first nil)
198 (insert-buffer-substring buffer start end)
199 (backward-char (- end start))
200 (setq tem (if (< nlines 0) (- nlines) nlines))
201 (while (> tem 0)
202 (insert empty ?:)
203 (forward-line 1)
204 (setq tem (1- tem)))
205 (insert tag ?:)
206 (forward-line 1)
207 (while (< tem nlines)
208 (insert empty ?:)
209 (forward-line 1)
210 (setq tem (1+ tem))))
211 (forward-line 1)))
212 (set-buffer standard-output)
213 ;; Put positions in increasing order to go with buffer.
214 (setq occur-pos-list (nreverse occur-pos-list))
215 (if (interactive-p)
216 (message "%d matching lines." (length occur-pos-list)))))))
217\f
218(defconst query-replace-help
219 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
220ESC or `q' to exit, Period to replace one match and exit,
221Comma to replace but not move point immediately,
222C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
223C-w to delete match and recursive edit,
224C-l to clear the screen, redisplay, and offer same replacement again,
225! to replace all remaining matches with no more questions,
226^ to move point back to previous match."
227 "Help message while in query-replace")
228
229(defun perform-replace (from-string replacements
230 query-flag regexp-flag delimited-flag
231 &optional repeat-count)
232 "Subroutine of `query-replace'. Its complexity handles interactive queries.
233Don't use this in your own program unless you want to query and set the mark
234just as `query-replace' does. Instead, write a simple loop like this:
235 (while (re-search-forward \"foo[ \t]+bar\" nil t)
236 (replace-match \"foobar\" nil nil))
237which will run faster and do exactly what you probably want."
238 (let ((nocasify (not (and case-fold-search case-replace
239 (string-equal from-string
240 (downcase from-string)))))
241 (literal (not regexp-flag))
242 (search-function (if regexp-flag 're-search-forward 'search-forward))
243 (search-string from-string)
244 (next-replacement nil)
245 (replacement-index 0)
246 (keep-going t)
247 (stack nil)
248 (next-rotate-count 0)
249 (replace-count 0)
250 (lastrepl nil)) ;Position after last match considered.
251 (if (stringp replacements)
252 (setq next-replacement replacements)
253 (or repeat-count (setq repeat-count 1)))
254 (if delimited-flag
255 (setq search-function 're-search-forward
256 search-string (concat "\\b"
257 (if regexp-flag from-string
258 (regexp-quote from-string))
259 "\\b")))
260 (push-mark)
261 (undo-boundary)
262 (while (and keep-going
263 (not (eobp))
264 (funcall search-function search-string nil t)
265 (if (eq lastrepl (point))
266 (progn
267 ;; Don't replace the null string
268 ;; right after end of previous replacement.
269 (forward-char 1)
270 (funcall search-function search-string nil t))
271 t))
272 ;; If time for a change, advance to next replacement string.
273 (if (and (listp replacements)
274 (= next-rotate-count replace-count))
275 (progn
276 (setq next-rotate-count
277 (+ next-rotate-count repeat-count))
278 (setq next-replacement (nth replacement-index replacements))
279 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
280 (if (not query-flag)
281 (progn
282 (replace-match next-replacement nocasify literal)
283 (setq replace-count (1+ replace-count)))
284 (undo-boundary)
285 (let (done replaced)
286 (while (not done)
287 ;; Preserve the match data. Process filters and sentinels
288 ;; could run inside read-char..
289 (let ((data (match-data))
290 (help-form
291 '(concat "Query replacing "
292 (if regexp-flag "regexp " "")
293 from-string " with " next-replacement ".\n\n"
294 (substitute-command-keys query-replace-help))))
295 (setq char help-char)
296 (while (or (not (numberp char)) (= char help-char))
297 (message "Query replacing %s with %s: " from-string next-replacement)
298 (setq char (read-event))
299 (if (and (numberp char) (= char ??))
300 (setq unread-command-char help-char char help-char)))
301 (store-match-data data))
302 (cond ((or (= char ?\e)
303 (= char ?q))
304 (setq keep-going nil)
305 (setq done t))
306 ((= char ?^)
307 (let ((elt (car stack)))
308 (goto-char (car elt))
309 (setq replaced (eq t (cdr elt)))
310 (or replaced
311 (store-match-data (cdr elt)))
312 (setq stack (cdr stack))))
313 ((or (= char ?\ )
314 (= char ?y))
315 (or replaced
316 (replace-match next-replacement nocasify literal))
317 (setq done t replaced t))
318 ((= char ?\.)
319 (or replaced
320 (replace-match next-replacement nocasify literal))
321 (setq keep-going nil)
322 (setq done t replaced t))
323 ((= char ?\,)
324 (if (not replaced)
325 (progn
326 (replace-match next-replacement nocasify literal)
327 (setq replaced t))))
328 ((= char ?!)
329 (or replaced
330 (replace-match next-replacement nocasify literal))
331 (setq done t query-flag nil replaced t))
332 ((or (= char ?\177)
333 (= char ?n))
334 (setq done t))
335 ((= char ?\C-l)
336 (recenter nil))
337 ((= char ?\C-r)
338 (store-match-data
339 (prog1 (match-data)
340 (save-excursion (recursive-edit)))))
341 ((= char ?\C-w)
342 (delete-region (match-beginning 0) (match-end 0))
343 (store-match-data
344 (prog1 (match-data)
345 (save-excursion (recursive-edit))))
346 (setq replaced t))
347 (t
348 (setq keep-going nil)
349 (setq unread-command-char char)
350 (setq done t))))
351 ;; Record previous position for ^ when we move on.
352 ;; Change markers to numbers in the match data
353 ;; since lots of markers slow down editing.
354 (setq stack
355 (cons (cons (point)
356 (or replaced
357 (mapcar
358 (function (lambda (elt)
359 (and elt
360 (marker-position elt))))
361 (match-data))))
362 stack))
363 (if replaced (setq replace-count (1+ replace-count)))))
364 (setq lastrepl (point)))
365 (and keep-going stack)))
366\f
367(defun map-query-replace-regexp (regexp to-strings &optional arg)
368 "Replace some matches for REGEXP with various strings, in rotation.
369The second argument TO-STRINGS contains the replacement strings, separated
370by spaces. This command works like `query-replace-regexp' except
371that each successive replacement uses the next successive replacement string,
372wrapping around from the last such string to the first.
373
374Non-interactively, TO-STRINGS may be a list of replacement strings.
375
376A prefix argument N says to use each replacement string N times
377before rotating to the next."
378 (interactive "sMap query replace (regexp): \nsQuery replace %s with (space-separated strings): \nP")
379 (let (replacements)
380 (if (listp to-strings)
381 (setq replacements to-strings)
382 (while (/= (length to-strings) 0)
383 (if (string-match " " to-strings)
384 (setq replacements
385 (append replacements
386 (list (substring to-strings 0
387 (string-match " " to-strings))))
388 to-strings (substring to-strings
389 (1+ (string-match " " to-strings))))
390 (setq replacements (append replacements (list to-strings))
391 to-strings ""))))
392 (perform-replace regexp replacements t t nil arg))
393 (message "Done"))
394