(Qrange_error, Qdomain_error, Qsingularity_error):
[bpt/emacs.git] / lisp / replace.el
CommitLineData
c88ab9ce
ER
1;;; replace.el --- replace commands for Emacs.
2
ba343182 3;; Copyright (C) 1985, 1986, 1987, 1992 Free Software Foundation, Inc.
3a801d0c 4
698e1804
RS
5;; This file is part of GNU Emacs.
6
7;; GNU Emacs is free software; you can redistribute it and/or modify
8;; it under the terms of the GNU General Public License as published by
e5d77022 9;; the Free Software Foundation; either version 2, or (at your option)
698e1804
RS
10;; any later version.
11
12;; GNU Emacs is distributed in the hope that it will be useful,
13;; but WITHOUT ANY WARRANTY; without even the implied warranty of
14;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15;; GNU General Public License for more details.
16
17;; You should have received a copy of the GNU General Public License
18;; along with GNU Emacs; see the file COPYING. If not, write to
19;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
20
4f4b8eff 21;;; Code:
698e1804 22
73fa8346
BP
23(defconst case-replace t "\
24*Non-nil means query-replace should preserve case in replacements.")
77176e73 25
770970cb
RS
26(defvar query-replace-history nil)
27
28(defun query-replace-read-args (string)
29 (let (from to)
30 (setq from (read-from-minibuffer (format "%s: " string)
31 nil nil nil
32 'query-replace-history))
33 (setq to (read-from-minibuffer (format "%s %s with: " string from)
34 nil nil nil
35 'query-replace-history))
36 (list from to current-prefix-arg)))
37
da44e784
RM
38(defun query-replace (from-string to-string &optional arg)
39 "Replace some occurrences of FROM-STRING with TO-STRING.
40As each match is found, the user must type a character saying
41what to do with it. For directions, type \\[help-command] at that time.
42
43Preserves case in each replacement if case-replace and case-fold-search
44are non-nil and FROM-STRING has no uppercase letters.
45Third arg DELIMITED (prefix arg if interactive) non-nil means replace
81bdc14d
RS
46only matches surrounded by word boundaries.
47
48To customize possible responses, change the \"bindings\" in `query-replace-map'."
770970cb 49 (interactive (query-replace-read-args "Query replace"))
da44e784 50 (perform-replace from-string to-string t nil arg)
81bdc14d 51 (or unread-command-events (message "Done")))
73fa8346 52(define-key esc-map "%" 'query-replace)
da44e784 53
da44e784
RM
54(defun query-replace-regexp (regexp to-string &optional arg)
55 "Replace some things after point matching REGEXP with TO-STRING.
56As each match is found, the user must type a character saying
57what to do with it. For directions, type \\[help-command] at that time.
58
59Preserves case in each replacement if case-replace and case-fold-search
60are non-nil and REGEXP has no uppercase letters.
61Third arg DELIMITED (prefix arg if interactive) non-nil means replace
62only matches surrounded by word boundaries.
63In TO-STRING, \\& means insert what matched REGEXP,
64and \\=\\<n> means insert what matched <n>th \\(...\\) in REGEXP."
770970cb 65 (interactive (query-replace-read-args "Query replace regexp"))
da44e784 66 (perform-replace regexp to-string t t arg)
81bdc14d 67 (or unread-command-events (message "Done")))
da44e784 68
da44e784
RM
69(defun map-query-replace-regexp (regexp to-strings &optional arg)
70 "Replace some matches for REGEXP with various strings, in rotation.
71The second argument TO-STRINGS contains the replacement strings, separated
72by spaces. This command works like `query-replace-regexp' except
73that each successive replacement uses the next successive replacement string,
74wrapping around from the last such string to the first.
75
76Non-interactively, TO-STRINGS may be a list of replacement strings.
77
78A prefix argument N says to use each replacement string N times
79before rotating to the next."
770970cb
RS
80 (interactive
81 (let (from to)
82 (setq from (read-from-minibuffer "Map query replace (regexp): "
83 nil nil nil
84 'query-replace-history))
85 (setq to (read-from-minibuffer
86 (format "Query replace %s with (space-separated strings): "
87 from)
88 nil nil nil
89 'query-replace-history))
90 (list from to current-prefix-arg)))
da44e784
RM
91 (let (replacements)
92 (if (listp to-strings)
93 (setq replacements to-strings)
94 (while (/= (length to-strings) 0)
95 (if (string-match " " to-strings)
96 (setq replacements
97 (append replacements
98 (list (substring to-strings 0
99 (string-match " " to-strings))))
100 to-strings (substring to-strings
101 (1+ (string-match " " to-strings))))
102 (setq replacements (append replacements (list to-strings))
103 to-strings ""))))
104 (perform-replace regexp replacements t t nil arg))
81bdc14d 105 (or unread-command-events (message "Done")))
da44e784 106
da44e784
RM
107(defun replace-string (from-string to-string &optional delimited)
108 "Replace occurrences of FROM-STRING with TO-STRING.
109Preserve case in each match if `case-replace' and `case-fold-search'
110are non-nil and FROM-STRING has no uppercase letters.
111Third arg DELIMITED (prefix arg if interactive) non-nil means replace
112only matches surrounded by word boundaries.
113
114This function is usually the wrong thing to use in a Lisp program.
115What you probably want is a loop like this:
116 (while (search-forward OLD-STRING nil t)
117 (replace-match REPLACEMENT nil t))
118which will run faster and will not set the mark or print anything."
770970cb 119 (interactive (query-replace-read-args "Replace string"))
da44e784 120 (perform-replace from-string to-string nil nil delimited)
81bdc14d 121 (or unread-command-events (message "Done")))
da44e784 122
da44e784
RM
123(defun replace-regexp (regexp to-string &optional delimited)
124 "Replace things after point matching REGEXP with TO-STRING.
125Preserve case in each match if case-replace and case-fold-search
126are non-nil and REGEXP has no uppercase letters.
127Third arg DELIMITED (prefix arg if interactive) non-nil means replace
128only matches surrounded by word boundaries.
129In TO-STRING, \\& means insert what matched REGEXP,
130and \\=\\<n> means insert what matched <n>th \\(...\\) in REGEXP.
131
132This function is usually the wrong thing to use in a Lisp program.
133What you probably want is a loop like this:
134 (while (re-search-forward REGEXP nil t)
135 (replace-match REPLACEMENT nil nil))
136which will run faster and will not set the mark or print anything."
770970cb 137 (interactive (query-replace-read-args "Replace regexp"))
da44e784 138 (perform-replace regexp to-string nil t delimited)
81bdc14d 139 (or unread-command-events (message "Done")))
da44e784 140
698e1804
RS
141(fset 'delete-non-matching-lines 'keep-lines)
142(defun keep-lines (regexp)
143 "Delete all lines except those containing matches for REGEXP.
144A match split across lines preserves all the lines it lies in.
145Applies to all lines after point."
146 (interactive "sKeep lines (containing match for regexp): ")
147 (save-excursion
148 (or (bolp) (forward-line 1))
149 (let ((start (point)))
150 (while (not (eobp))
151 ;; Start is first char not preserved by previous match.
152 (if (not (re-search-forward regexp nil 'move))
153 (delete-region start (point-max))
154 (let ((end (save-excursion (goto-char (match-beginning 0))
155 (beginning-of-line)
156 (point))))
157 ;; Now end is first char preserved by the new match.
158 (if (< start end)
159 (delete-region start end))))
160 (setq start (save-excursion (forward-line 1)
161 (point)))
162 ;; If the match was empty, avoid matching again at same place.
163 (and (not (eobp)) (= (match-beginning 0) (match-end 0))
164 (forward-char 1))))))
165
166(fset 'delete-matching-lines 'flush-lines)
167(defun flush-lines (regexp)
168 "Delete lines containing matches for REGEXP.
169If a match is split across lines, all the lines it lies in are deleted.
170Applies to lines after point."
171 (interactive "sFlush lines (containing match for regexp): ")
172 (save-excursion
173 (while (and (not (eobp))
174 (re-search-forward regexp nil t))
175 (delete-region (save-excursion (goto-char (match-beginning 0))
176 (beginning-of-line)
177 (point))
178 (progn (forward-line 1) (point))))))
179
180(fset 'count-matches 'how-many)
181(defun how-many (regexp)
182 "Print number of matches for REGEXP following point."
183 (interactive "sHow many matches for (regexp): ")
184 (let ((count 0) opoint)
185 (save-excursion
186 (while (and (not (eobp))
187 (progn (setq opoint (point))
188 (re-search-forward regexp nil t)))
189 (if (= opoint (point))
190 (forward-char 1)
191 (setq count (1+ count))))
192 (message "%d occurrences" count))))
193
194(defvar occur-mode-map ())
195(if occur-mode-map
196 ()
197 (setq occur-mode-map (make-sparse-keymap))
198 (define-key occur-mode-map "\C-c\C-c" 'occur-mode-goto-occurrence))
199
200(defvar occur-buffer nil)
201(defvar occur-nlines nil)
202(defvar occur-pos-list nil)
f1c9e147 203(defvar occur-last-string "")
698e1804
RS
204
205(defun occur-mode ()
206 "Major mode for output from \\[occur].
207Move point to one of the occurrences in this buffer,
208then use \\[occur-mode-goto-occurrence] to go to the same occurrence
209in the buffer that the occurrences were found in.
210\\{occur-mode-map}"
211 (kill-all-local-variables)
212 (use-local-map occur-mode-map)
213 (setq major-mode 'occur-mode)
214 (setq mode-name "Occur")
215 (make-local-variable 'occur-buffer)
216 (make-local-variable 'occur-nlines)
217 (make-local-variable 'occur-pos-list))
218
219(defun occur-mode-goto-occurrence ()
220 "Go to the line this occurrence was found in, in the buffer it was found in."
221 (interactive)
222 (if (or (null occur-buffer)
223 (null (buffer-name occur-buffer)))
224 (progn
225 (setq occur-buffer nil
226 occur-pos-list nil)
227 (error "Buffer in which occurrences were found is deleted")))
228 (let* ((occur-number (save-excursion
229 (beginning-of-line)
230 (/ (1- (count-lines (point-min)
231 (save-excursion
232 (beginning-of-line)
233 (point))))
234 (cond ((< occur-nlines 0)
235 (- 2 occur-nlines))
236 ((> occur-nlines 0)
237 (+ 2 (* 2 occur-nlines)))
238 (t 1)))))
239 (pos (nth occur-number occur-pos-list)))
240 (pop-to-buffer occur-buffer)
241 (goto-char (marker-position pos))))
242
243(defvar list-matching-lines-default-context-lines 0
da44e784 244 "*Default number of context lines to include around a `list-matching-lines'
698e1804
RS
245match. A negative number means to include that many lines before the match.
246A positive number means to include that many lines both before and after.")
247
698e1804
RS
248(fset 'list-matching-lines 'occur)
249
250(defun occur (regexp &optional nlines)
99976f85
RS
251 "Show all lines in the current buffer containing a match for REGEXP.
252Interactively, REGEXP defaults to the last REGEXP
da44e784
RM
253used interactively with \\[occur].
254
255If a match spreads across multiple lines, all those lines are shown.
698e1804 256
da44e784
RM
257Each line is displayed with NLINES lines before and after, or -NLINES
258before if NLINES is negative.
259NLINES defaults to `list-matching-lines-default-context-lines'.
698e1804
RS
260Interactively it is the prefix arg.
261
262The lines are shown in a buffer named *Occur*.
263It serves as a menu to find any of the occurrences in this buffer.
264\\[describe-mode] in that buffer will explain how."
f1c9e147 265 (interactive (list (setq occur-last-string
266 (read-string "List lines matching regexp: "
267 occur-last-string))
268 current-prefix-arg))
698e1804
RS
269 (setq nlines (if nlines (prefix-numeric-value nlines)
270 list-matching-lines-default-context-lines))
271 (let ((first t)
272 (buffer (current-buffer))
273 (linenum 1)
79c2e52b
JB
274 (prevpos (point-min))
275 (final-context-start (make-marker)))
99976f85
RS
276;;; (save-excursion
277;;; (beginning-of-line)
278;;; (setq linenum (1+ (count-lines (point-min) (point))))
279;;; (setq prevpos (point)))
698e1804
RS
280 (with-output-to-temp-buffer "*Occur*"
281 (save-excursion
282 (set-buffer standard-output)
283 (insert "Lines matching ")
284 (prin1 regexp)
285 (insert " in buffer " (buffer-name buffer) ?. ?\n)
286 (occur-mode)
287 (setq occur-buffer buffer)
288 (setq occur-nlines nlines)
289 (setq occur-pos-list ()))
290 (if (eq buffer standard-output)
291 (goto-char (point-max)))
292 (save-excursion
99976f85 293 (beginning-of-buffer)
698e1804
RS
294 ;; Find next match, but give up if prev match was at end of buffer.
295 (while (and (not (= prevpos (point-max)))
296 (re-search-forward regexp nil t))
da44e784 297 (goto-char (match-beginning 0))
698e1804
RS
298 (beginning-of-line)
299 (setq linenum (+ linenum (count-lines prevpos (point))))
300 (setq prevpos (point))
da44e784 301 (goto-char (match-end 0))
698e1804 302 (let* ((start (save-excursion
da44e784 303 (goto-char (match-beginning 0))
698e1804
RS
304 (forward-line (if (< nlines 0) nlines (- nlines)))
305 (point)))
306 (end (save-excursion
da44e784 307 (goto-char (match-end 0))
698e1804
RS
308 (if (> nlines 0)
309 (forward-line (1+ nlines))
310 (forward-line 1))
311 (point)))
312 (tag (format "%3d" linenum))
313 (empty (make-string (length tag) ?\ ))
314 tem)
315 (save-excursion
79c2e52b
JB
316 (setq tem (make-marker))
317 (set-marker tem (point))
698e1804
RS
318 (set-buffer standard-output)
319 (setq occur-pos-list (cons tem occur-pos-list))
320 (or first (zerop nlines)
321 (insert "--------\n"))
322 (setq first nil)
323 (insert-buffer-substring buffer start end)
324 (backward-char (- end start))
da44e784 325 (setq tem nlines)
698e1804
RS
326 (while (> tem 0)
327 (insert empty ?:)
328 (forward-line 1)
329 (setq tem (1- tem)))
79c2e52b 330 (let ((this-linenum linenum))
da44e784
RM
331 (set-marker final-context-start
332 (+ (point) (- (match-end 0) (match-beginning 0))))
333 (while (< (point) final-context-start)
334 (if (null tag)
335 (setq tag (format "%3d" this-linenum)))
336 (insert tag ?:)
337 (setq tag nil)
338 (forward-line 1)
339 (setq this-linenum (1+ this-linenum))))
698e1804
RS
340 (while (< tem nlines)
341 (insert empty ?:)
342 (forward-line 1)
343 (setq tem (1+ tem))))
344 (forward-line 1)))
345 (set-buffer standard-output)
346 ;; Put positions in increasing order to go with buffer.
347 (setq occur-pos-list (nreverse occur-pos-list))
348 (if (interactive-p)
349 (message "%d matching lines." (length occur-pos-list)))))))
350\f
81bdc14d
RS
351;; It would be nice to use \\[...], but there is no reasonable way
352;; to make that display both SPC and Y.
698e1804
RS
353(defconst query-replace-help
354 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
355ESC or `q' to exit, Period to replace one match and exit,
356Comma to replace but not move point immediately,
357C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
358C-w to delete match and recursive edit,
359C-l to clear the screen, redisplay, and offer same replacement again,
360! to replace all remaining matches with no more questions,
361^ to move point back to previous match."
362 "Help message while in query-replace")
363
81bdc14d
RS
364(defvar query-replace-map (make-sparse-keymap)
365 "Keymap that defines the responses to questions in `query-replace'.
366The \"bindings\" in this map are not commands; they are answers.
367The valid answers include `act', `skip', `act-and-show',
368`exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
369`automatic', `backup', and `help'.")
370
371(define-key query-replace-map " " 'act)
372(define-key query-replace-map "\d" 'skip)
373(define-key query-replace-map [delete] 'skip)
374(define-key query-replace-map "y" 'act)
375(define-key query-replace-map "n" 'skip)
376(define-key query-replace-map "," 'act-and-show)
377(define-key query-replace-map "\e" 'exit)
378(define-key query-replace-map "q" 'exit)
379(define-key query-replace-map "." 'act-and-exit)
380(define-key query-replace-map "\C-r" 'edit)
381(define-key query-replace-map "\C-w" 'delete-and-edit)
382(define-key query-replace-map "\C-l" 'recenter)
383(define-key query-replace-map "!" 'automatic)
384(define-key query-replace-map "^" 'backup)
385(define-key query-replace-map "\C-h" 'help)
386(define-key query-replace-map "?" 'help)
bc6312e1
RS
387(define-key query-replace-map "\C-g" 'quit)
388(define-key query-replace-map "\C-]" 'quit)
81bdc14d 389
698e1804
RS
390(defun perform-replace (from-string replacements
391 query-flag regexp-flag delimited-flag
81bdc14d 392 &optional repeat-count map)
698e1804
RS
393 "Subroutine of `query-replace'. Its complexity handles interactive queries.
394Don't use this in your own program unless you want to query and set the mark
395just as `query-replace' does. Instead, write a simple loop like this:
396 (while (re-search-forward \"foo[ \t]+bar\" nil t)
397 (replace-match \"foobar\" nil nil))
398which will run faster and do exactly what you probably want."
81bdc14d 399 (or map (setq map query-replace-map))
698e1804
RS
400 (let ((nocasify (not (and case-fold-search case-replace
401 (string-equal from-string
402 (downcase from-string)))))
403 (literal (not regexp-flag))
404 (search-function (if regexp-flag 're-search-forward 'search-forward))
405 (search-string from-string)
e5d77022 406 (real-match-data nil) ; the match data for the current match
698e1804
RS
407 (next-replacement nil)
408 (replacement-index 0)
409 (keep-going t)
410 (stack nil)
411 (next-rotate-count 0)
412 (replace-count 0)
da44e784 413 (lastrepl nil) ;Position after last match considered.
ba343182 414 (match-again t))
698e1804
RS
415 (if (stringp replacements)
416 (setq next-replacement replacements)
417 (or repeat-count (setq repeat-count 1)))
418 (if delimited-flag
419 (setq search-function 're-search-forward
420 search-string (concat "\\b"
421 (if regexp-flag from-string
422 (regexp-quote from-string))
423 "\\b")))
424 (push-mark)
425 (undo-boundary)
81bdc14d 426 ;; Loop finding occurrences that perhaps should be replaced.
698e1804
RS
427 (while (and keep-going
428 (not (eobp))
429 (funcall search-function search-string nil t)
da44e784
RM
430 ;; If the search string matches immediately after
431 ;; the previous match, but it did not match there
432 ;; before the replacement was done, ignore the match.
433 (if (or (eq lastrepl (point))
434 (and regexp-flag
435 (eq lastrepl (match-beginning 0))
436 (not match-again)))
437 (if (eobp)
438 nil
698e1804
RS
439 ;; Don't replace the null string
440 ;; right after end of previous replacement.
441 (forward-char 1)
442 (funcall search-function search-string nil t))
443 t))
e5d77022
JB
444
445 ;; Save the data associated with the real match.
446 (setq real-match-data (match-data))
447
da44e784
RM
448 ;; Before we make the replacement, decide whether the search string
449 ;; can match again just after this match.
450 (if regexp-flag
451 (setq match-again (looking-at search-string)))
698e1804
RS
452 ;; If time for a change, advance to next replacement string.
453 (if (and (listp replacements)
454 (= next-rotate-count replace-count))
455 (progn
456 (setq next-rotate-count
457 (+ next-rotate-count repeat-count))
458 (setq next-replacement (nth replacement-index replacements))
459 (setq replacement-index (% (1+ replacement-index) (length replacements)))))
460 (if (not query-flag)
461 (progn
e5d77022 462 (store-match-data real-match-data)
698e1804
RS
463 (replace-match next-replacement nocasify literal)
464 (setq replace-count (1+ replace-count)))
465 (undo-boundary)
81bdc14d
RS
466 (let (done replaced key)
467 ;; Loop reading commands until one of them sets done,
468 ;; which means it has finished handling this occurrence.
698e1804 469 (while (not done)
81bdc14d
RS
470 (message "Query replacing %s with %s: "
471 from-string next-replacement)
472 (setq key (vector (read-event)))
473 (setq def (lookup-key map key))
e5d77022
JB
474 ;; Restore the match data while we process the command.
475 (store-match-data real-match-data)
81bdc14d
RS
476 (cond ((eq def 'help)
477 (with-output-to-temp-buffer "*Help*"
478 (princ
479 (concat "Query replacing "
480 (if regexp-flag "regexp " "")
481 from-string " with "
482 next-replacement ".\n\n"
483 (substitute-command-keys
484 query-replace-help)))))
485 ((eq def 'exit)
698e1804
RS
486 (setq keep-going nil)
487 (setq done t))
81bdc14d 488 ((eq def 'backup)
698e1804
RS
489 (let ((elt (car stack)))
490 (goto-char (car elt))
491 (setq replaced (eq t (cdr elt)))
492 (or replaced
493 (store-match-data (cdr elt)))
494 (setq stack (cdr stack))))
81bdc14d 495 ((eq def 'act)
698e1804
RS
496 (or replaced
497 (replace-match next-replacement nocasify literal))
498 (setq done t replaced t))
81bdc14d 499 ((eq def 'act-and-exit)
698e1804
RS
500 (or replaced
501 (replace-match next-replacement nocasify literal))
502 (setq keep-going nil)
503 (setq done t replaced t))
81bdc14d 504 ((eq def 'act-and-show)
698e1804
RS
505 (if (not replaced)
506 (progn
507 (replace-match next-replacement nocasify literal)
508 (setq replaced t))))
81bdc14d 509 ((eq def 'automatic)
698e1804
RS
510 (or replaced
511 (replace-match next-replacement nocasify literal))
512 (setq done t query-flag nil replaced t))
81bdc14d 513 ((eq def 'skip)
698e1804 514 (setq done t))
81bdc14d 515 ((eq def 'recenter)
698e1804 516 (recenter nil))
81bdc14d 517 ((eq def 'edit)
698e1804
RS
518 (store-match-data
519 (prog1 (match-data)
da44e784
RM
520 (save-excursion (recursive-edit))))
521 ;; Before we make the replacement,
522 ;; decide whether the search string
523 ;; can match again just after this match.
524 (if regexp-flag
525 (setq match-again (looking-at search-string))))
81bdc14d 526 ((eq def 'delete-and-edit)
698e1804
RS
527 (delete-region (match-beginning 0) (match-end 0))
528 (store-match-data
529 (prog1 (match-data)
530 (save-excursion (recursive-edit))))
531 (setq replaced t))
532 (t
533 (setq keep-going nil)
81bdc14d
RS
534 (setq unread-command-events
535 (append (listify-key-sequence key)
536 unread-command-events))
698e1804
RS
537 (setq done t))))
538 ;; Record previous position for ^ when we move on.
539 ;; Change markers to numbers in the match data
540 ;; since lots of markers slow down editing.
541 (setq stack
542 (cons (cons (point)
543 (or replaced
544 (mapcar
545 (function (lambda (elt)
546 (and elt
547 (marker-position elt))))
548 (match-data))))
549 stack))
550 (if replaced (setq replace-count (1+ replace-count)))))
551 (setq lastrepl (point)))
81bdc14d 552 (and keep-going stack)))
698e1804 553
c88ab9ce 554;;; replace.el ends here