]> code.delx.au - gnu-emacs/blob - lisp/replace.el
Add a provide statement.
[gnu-emacs] / lisp / replace.el
1 ;;; replace.el --- replace commands for Emacs
2
3 ;; Copyright (C) 1985, 1986, 1987, 1992, 1994, 1996, 1997, 2000, 2001, 2002,
4 ;; 2003, 2004 Free Software Foundation, Inc.
5
6 ;; Maintainer: FSF
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; This package supplies the string and regular-expression replace functions
28 ;; documented in the Emacs user's manual.
29
30 ;;; Code:
31
32 (defcustom case-replace t
33 "*Non-nil means `query-replace' should preserve case in replacements."
34 :type 'boolean
35 :group 'matching)
36
37 (defvar query-replace-history nil)
38
39 (defvar query-replace-interactive nil
40 "Non-nil means `query-replace' uses the last search string.
41 That becomes the \"string to replace\".")
42
43 (defcustom query-replace-from-history-variable 'query-replace-history
44 "History list to use for the FROM argument of `query-replace' commands.
45 The value of this variable should be a symbol; that symbol
46 is used as a variable to hold a history list for the strings
47 or patterns to be replaced."
48 :group 'matching
49 :type 'symbol
50 :version "20.3")
51
52 (defcustom query-replace-to-history-variable 'query-replace-history
53 "History list to use for the TO argument of `query-replace' commands.
54 The value of this variable should be a symbol; that symbol
55 is used as a variable to hold a history list for replacement
56 strings or patterns."
57 :group 'matching
58 :type 'symbol
59 :version "20.3")
60
61 (defcustom query-replace-skip-read-only nil
62 "*Non-nil means `query-replace' and friends ignore read-only matches."
63 :type 'boolean
64 :group 'matching
65 :version "21.4")
66
67 (defun query-replace-descr (string)
68 (mapconcat 'isearch-text-char-description string ""))
69
70 (defun query-replace-read-from (string regexp-flag)
71 "Query and return the `from' argument of a query-replace operation.
72 The return value can also be a pair (FROM . TO) indicating that the user
73 wants to replace FROM with TO."
74 (if query-replace-interactive
75 (car (if regexp-flag regexp-search-ring search-ring))
76 (let* ((lastfrom (car (symbol-value query-replace-from-history-variable)))
77 (lastto (car (symbol-value query-replace-to-history-variable)))
78 (from
79 ;; The save-excursion here is in case the user marks and copies
80 ;; a region in order to specify the minibuffer input.
81 ;; That should not clobber the region for the query-replace itself.
82 (save-excursion
83 (when (equal lastfrom lastto)
84 ;; Typically, this is because the two histlists are shared.
85 (setq lastfrom (cadr (symbol-value
86 query-replace-from-history-variable))))
87 (read-from-minibuffer
88 (if (and lastto lastfrom)
89 (format "%s (default %s -> %s): " string
90 (query-replace-descr lastfrom)
91 (query-replace-descr lastto))
92 (format "%s: " string))
93 nil nil nil
94 query-replace-from-history-variable
95 nil t t))))
96 (if (and (zerop (length from)) lastto lastfrom)
97 (cons lastfrom
98 (query-replace-compile-replacement lastto regexp-flag))
99 ;; Warn if user types \n or \t, but don't reject the input.
100 (and regexp-flag
101 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
102 (let ((match (match-string 3 from)))
103 (cond
104 ((string= match "\\n")
105 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
106 ((string= match "\\t")
107 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
108 (sit-for 2)))
109 from))))
110
111 (defun query-replace-compile-replacement (to regexp-flag)
112 "Maybe convert a regexp replacement TO to Lisp.
113 Returns a list suitable for `perform-replace' if necessary,
114 the original string if not."
115 (if (and regexp-flag
116 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
117 (let (pos list char)
118 (while
119 (progn
120 (setq pos (match-end 0))
121 (push (substring to 0 (- pos 2)) list)
122 (setq char (aref to (1- pos))
123 to (substring to pos))
124 (cond ((eq char ?\#)
125 (push '(number-to-string replace-count) list))
126 ((eq char ?\,)
127 (setq pos (read-from-string to))
128 (push `(replace-quote ,(car pos)) list)
129 (let ((end
130 ;; Swallow a space after a symbol
131 ;; if there is a space.
132 (if (and (or (symbolp (car pos))
133 ;; Swallow a space after 'foo
134 ;; but not after (quote foo).
135 (and (eq (car-safe (car pos)) 'quote)
136 (not (= ?\( (aref to 0)))))
137 (eq (string-match " " to (cdr pos))
138 (cdr pos)))
139 (1+ (cdr pos))
140 (cdr pos))))
141 (setq to (substring to end)))))
142 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
143 (setq to (nreverse (delete "" (cons to list))))
144 (replace-match-string-symbols to)
145 (cons 'replace-eval-replacement
146 (if (cdr to)
147 (cons 'concat to)
148 (car to))))
149 to))
150
151
152 (defun query-replace-read-to (from string regexp-flag)
153 "Query and return the `to' argument of a query-replace operation."
154 (query-replace-compile-replacement
155 (save-excursion
156 (read-from-minibuffer
157 (format "%s %s with: " string (query-replace-descr from))
158 nil nil nil
159 query-replace-to-history-variable from t t))
160 regexp-flag))
161
162 (defun query-replace-read-args (string regexp-flag &optional noerror)
163 (unless noerror
164 (barf-if-buffer-read-only))
165 (let* ((from (query-replace-read-from string regexp-flag))
166 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
167 (query-replace-read-to from string regexp-flag))))
168 (list from to current-prefix-arg)))
169
170 (defun query-replace (from-string to-string &optional delimited start end)
171 "Replace some occurrences of FROM-STRING with TO-STRING.
172 As each match is found, the user must type a character saying
173 what to do with it. For directions, type \\[help-command] at that time.
174
175 In Transient Mark mode, if the mark is active, operate on the contents
176 of the region. Otherwise, operate from point to the end of the buffer.
177
178 If `query-replace-interactive' is non-nil, the last incremental search
179 string is used as FROM-STRING--you don't have to specify it with the
180 minibuffer.
181
182 Matching is independent of case if `case-fold-search' is non-nil and
183 FROM-STRING has no uppercase letters. Replacement transfers the case
184 pattern of the old text to the new text, if `case-replace' and
185 `case-fold-search' are non-nil and FROM-STRING has no uppercase
186 letters. \(Transferring the case pattern means that if the old text
187 matched is all caps, or capitalized, then its replacement is upcased
188 or capitalized.)
189
190 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
191 only matches surrounded by word boundaries.
192 Fourth and fifth arg START and END specify the region to operate on.
193
194 To customize possible responses, change the \"bindings\" in `query-replace-map'."
195 (interactive (let ((common
196 (query-replace-read-args "Query replace" nil)))
197 (list (nth 0 common) (nth 1 common) (nth 2 common)
198 ;; These are done separately here
199 ;; so that command-history will record these expressions
200 ;; rather than the values they had this time.
201 (if (and transient-mark-mode mark-active)
202 (region-beginning))
203 (if (and transient-mark-mode mark-active)
204 (region-end)))))
205 (perform-replace from-string to-string t nil delimited nil nil start end))
206
207 (define-key esc-map "%" 'query-replace)
208
209 (defun query-replace-regexp (regexp to-string &optional delimited start end)
210 "Replace some things after point matching REGEXP with TO-STRING.
211 As each match is found, the user must type a character saying
212 what to do with it. For directions, type \\[help-command] at that time.
213
214 In Transient Mark mode, if the mark is active, operate on the contents
215 of the region. Otherwise, operate from point to the end of the buffer.
216
217 If `query-replace-interactive' is non-nil, the last incremental search
218 regexp is used as REGEXP--you don't have to specify it with the
219 minibuffer.
220
221 Matching is independent of case if `case-fold-search' is non-nil and
222 REGEXP has no uppercase letters. Replacement transfers the case
223 pattern of the old text to the new text, if `case-replace' and
224 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
225 \(Transferring the case pattern means that if the old text matched is
226 all caps, or capitalized, then its replacement is upcased or
227 capitalized.)
228
229 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
230 only matches surrounded by word boundaries.
231 Fourth and fifth arg START and END specify the region to operate on.
232
233 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
234 and `\\=\\N' (where N is a digit) stands for
235 whatever what matched the Nth `\\(...\\)' in REGEXP.
236 `\\?' lets you edit the replacement text in the minibuffer
237 at the given position for each replacement.
238
239 In interactive calls, the replacement text can contain `\\,'
240 followed by a Lisp expression. Each
241 replacement evaluates that expression to compute the replacement
242 string. Inside of that expression, `\\&' is a string denoting the
243 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
244 for the whole or a partial match converted to a number with
245 `string-to-number', and `\\#' itself for the number of replacements
246 done so far (starting with zero).
247
248 If the replacement expression is a symbol, write a space after it
249 to terminate it. One space there, if any, will be discarded.
250
251 When using those Lisp features interactively in the replacement
252 text, TO-STRING is actually made a list instead of a string.
253 Use \\[repeat-complex-command] after this command for details."
254 (interactive
255 (let ((common
256 (query-replace-read-args "Query replace regexp" t)))
257 (list (nth 0 common) (nth 1 common) (nth 2 common)
258 ;; These are done separately here
259 ;; so that command-history will record these expressions
260 ;; rather than the values they had this time.
261 (if (and transient-mark-mode mark-active)
262 (region-beginning))
263 (if (and transient-mark-mode mark-active)
264 (region-end)))))
265 (perform-replace regexp to-string t t delimited nil nil start end))
266
267 (define-key esc-map [?\C-%] 'query-replace-regexp)
268
269 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
270 "Replace some things after point matching REGEXP with the result of TO-EXPR.
271 As each match is found, the user must type a character saying
272 what to do with it. For directions, type \\[help-command] at that time.
273
274 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
275 reference `replace-count' to get the number of replacements already made.
276 If the result of TO-EXPR is not a string, it is converted to one using
277 `prin1-to-string' with the NOESCAPE argument (which see).
278
279 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
280 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
281 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
282 Use `\\#&' or `\\#N' if you want a number instead of a string.
283 In interactive use, `\\#' in itself stands for `replace-count'.
284
285 In Transient Mark mode, if the mark is active, operate on the contents
286 of the region. Otherwise, operate from point to the end of the buffer.
287
288 If `query-replace-interactive' is non-nil, the last incremental search
289 regexp is used as REGEXP--you don't have to specify it with the
290 minibuffer.
291
292 Preserves case in each replacement if `case-replace' and `case-fold-search'
293 are non-nil and REGEXP has no uppercase letters.
294
295 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
296 only matches that are surrounded by word boundaries.
297 Fourth and fifth arg START and END specify the region to operate on."
298 (interactive
299 (progn
300 (barf-if-buffer-read-only)
301 (let* ((from
302 ;; Let-bind the history var to disable the "foo -> bar" default.
303 ;; Maybe we shouldn't disable this default, but for now I'll
304 ;; leave it off. --Stef
305 (let ((query-replace-to-history-variable nil))
306 (query-replace-read-from "Query replace regexp" t)))
307 (to (list (read-from-minibuffer
308 (format "Query replace regexp %s with eval: "
309 (query-replace-descr from))
310 nil nil t query-replace-to-history-variable from t))))
311 ;; We make TO a list because replace-match-string-symbols requires one,
312 ;; and the user might enter a single token.
313 (replace-match-string-symbols to)
314 (list from (car to) current-prefix-arg
315 (if (and transient-mark-mode mark-active)
316 (region-beginning))
317 (if (and transient-mark-mode mark-active)
318 (region-end))))))
319 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
320 t 'literal delimited nil nil start end))
321
322 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
323 "Replace some matches for REGEXP with various strings, in rotation.
324 The second argument TO-STRINGS contains the replacement strings,
325 separated by spaces. Third arg DELIMITED (prefix arg if interactive),
326 if non-nil, means replace only matches surrounded by word boundaries.
327 This command works like `query-replace-regexp' except that each
328 successive replacement uses the next successive replacement string,
329 wrapping around from the last such string to the first.
330
331 In Transient Mark mode, if the mark is active, operate on the contents
332 of the region. Otherwise, operate from point to the end of the buffer.
333
334 Non-interactively, TO-STRINGS may be a list of replacement strings.
335
336 If `query-replace-interactive' is non-nil, the last incremental search
337 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
338
339 A prefix argument N says to use each replacement string N times
340 before rotating to the next.
341 Fourth and fifth arg START and END specify the region to operate on."
342 (interactive
343 (let* ((from (if query-replace-interactive
344 (car regexp-search-ring)
345 (read-from-minibuffer "Map query replace (regexp): "
346 nil nil nil
347 'query-replace-history nil t)))
348 (to (read-from-minibuffer
349 (format "Query replace %s with (space-separated strings): "
350 (query-replace-descr from))
351 nil nil nil
352 'query-replace-history from t)))
353 (list from to
354 (and current-prefix-arg
355 (prefix-numeric-value current-prefix-arg))
356 (if (and transient-mark-mode mark-active)
357 (region-beginning))
358 (if (and transient-mark-mode mark-active)
359 (region-end)))))
360 (let (replacements)
361 (if (listp to-strings)
362 (setq replacements to-strings)
363 (while (/= (length to-strings) 0)
364 (if (string-match " " to-strings)
365 (setq replacements
366 (append replacements
367 (list (substring to-strings 0
368 (string-match " " to-strings))))
369 to-strings (substring to-strings
370 (1+ (string-match " " to-strings))))
371 (setq replacements (append replacements (list to-strings))
372 to-strings ""))))
373 (perform-replace regexp replacements t t nil n nil start end)))
374
375 (defun replace-string (from-string to-string &optional delimited start end)
376 "Replace occurrences of FROM-STRING with TO-STRING.
377 Preserve case in each match if `case-replace' and `case-fold-search'
378 are non-nil and FROM-STRING has no uppercase letters.
379 \(Preserving case means that if the string matched is all caps, or capitalized,
380 then its replacement is upcased or capitalized.)
381
382 In Transient Mark mode, if the mark is active, operate on the contents
383 of the region. Otherwise, operate from point to the end of the buffer.
384
385 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
386 only matches surrounded by word boundaries.
387 Fourth and fifth arg START and END specify the region to operate on.
388
389 If `query-replace-interactive' is non-nil, the last incremental search
390 string is used as FROM-STRING--you don't have to specify it with the
391 minibuffer.
392
393 This function is usually the wrong thing to use in a Lisp program.
394 What you probably want is a loop like this:
395 (while (search-forward FROM-STRING nil t)
396 (replace-match TO-STRING nil t))
397 which will run faster and will not set the mark or print anything.
398 \(You may need a more complex loop if FROM-STRING can match the null string
399 and TO-STRING is also null.)"
400 (interactive
401 (let ((common
402 (query-replace-read-args "Replace string" nil)))
403 (list (nth 0 common) (nth 1 common) (nth 2 common)
404 (if (and transient-mark-mode mark-active)
405 (region-beginning))
406 (if (and transient-mark-mode mark-active)
407 (region-end)))))
408 (perform-replace from-string to-string nil nil delimited nil nil start end))
409
410 (defun replace-regexp (regexp to-string &optional delimited start end)
411 "Replace things after point matching REGEXP with TO-STRING.
412 Preserve case in each match if `case-replace' and `case-fold-search'
413 are non-nil and REGEXP has no uppercase letters.
414
415 In Transient Mark mode, if the mark is active, operate on the contents
416 of the region. Otherwise, operate from point to the end of the buffer.
417
418 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
419 only matches surrounded by word boundaries.
420 Fourth and fifth arg START and END specify the region to operate on.
421
422 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
423 and `\\=\\N' (where N is a digit) stands for
424 whatever what matched the Nth `\\(...\\)' in REGEXP.
425 `\\?' lets you edit the replacement text in the minibuffer
426 at the given position for each replacement.
427
428 In interactive calls, the replacement text may contain `\\,'
429 followed by a Lisp expression used as part of the replacement
430 text. Inside of that expression, `\\&' is a string denoting the
431 whole match, `\\N' a partial matches, `\\#&' and `\\#N' the
432 respective numeric values from `string-to-number', and `\\#'
433 itself for `replace-count', the number of replacements occured so
434 far.
435
436 If your Lisp expression is an identifier and the next letter in
437 the replacement string would be interpreted as part of it, you
438 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
439 for this particular case you may also enter `\\#' in the
440 replacement text directly.
441
442 When using those Lisp features interactively in the replacement
443 text, TO-STRING is actually made a list instead of a string.
444 Use \\[repeat-complex-command] after this command for details.
445
446 If `query-replace-interactive' is non-nil, the last incremental search
447 regexp is used as REGEXP--you don't have to specify it with the minibuffer.
448
449 This function is usually the wrong thing to use in a Lisp program.
450 What you probably want is a loop like this:
451 (while (re-search-forward REGEXP nil t)
452 (replace-match TO-STRING nil nil))
453 which will run faster and will not set the mark or print anything."
454 (interactive
455 (let ((common
456 (query-replace-read-args "Replace regexp" t)))
457 (list (nth 0 common) (nth 1 common) (nth 2 common)
458 (if (and transient-mark-mode mark-active)
459 (region-beginning))
460 (if (and transient-mark-mode mark-active)
461 (region-end)))))
462 (perform-replace regexp to-string nil t delimited nil nil start end))
463
464 \f
465 (defvar regexp-history nil
466 "History list for some commands that read regular expressions.")
467
468
469 (defalias 'delete-non-matching-lines 'keep-lines)
470 (defalias 'delete-matching-lines 'flush-lines)
471 (defalias 'count-matches 'how-many)
472
473
474 (defun keep-lines-read-args (prompt)
475 "Read arguments for `keep-lines' and friends.
476 Prompt for a regexp with PROMPT.
477 Value is a list, (REGEXP)."
478 (list (read-from-minibuffer prompt nil nil nil
479 'regexp-history nil t)))
480
481 (defun keep-lines (regexp &optional rstart rend)
482 "Delete all lines except those containing matches for REGEXP.
483 A match split across lines preserves all the lines it lies in.
484 Applies to all lines after point.
485
486 If REGEXP contains upper case characters (excluding those preceded by `\\'),
487 the matching is case-sensitive.
488
489 Second and third arg RSTART and REND specify the region to operate on.
490
491 Interactively, in Transient Mark mode when the mark is active, operate
492 on the contents of the region. Otherwise, operate from point to the
493 end of the buffer."
494
495 (interactive
496 (progn
497 (barf-if-buffer-read-only)
498 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
499 (if rstart
500 (progn
501 (goto-char (min rstart rend))
502 (setq rend (copy-marker (max rstart rend))))
503 (if (and transient-mark-mode mark-active)
504 (setq rstart (region-beginning)
505 rend (copy-marker (region-end)))
506 (setq rstart (point)
507 rend (point-max-marker)))
508 (goto-char rstart))
509 (save-excursion
510 (or (bolp) (forward-line 1))
511 (let ((start (point))
512 (case-fold-search (and case-fold-search
513 (isearch-no-upper-case-p regexp t))))
514 (while (< (point) rend)
515 ;; Start is first char not preserved by previous match.
516 (if (not (re-search-forward regexp rend 'move))
517 (delete-region start rend)
518 (let ((end (save-excursion (goto-char (match-beginning 0))
519 (beginning-of-line)
520 (point))))
521 ;; Now end is first char preserved by the new match.
522 (if (< start end)
523 (delete-region start end))))
524
525 (setq start (save-excursion (forward-line 1) (point)))
526 ;; If the match was empty, avoid matching again at same place.
527 (and (< (point) rend)
528 (= (match-beginning 0) (match-end 0))
529 (forward-char 1))))))
530
531
532 (defun flush-lines (regexp &optional rstart rend)
533 "Delete lines containing matches for REGEXP.
534 If a match is split across lines, all the lines it lies in are deleted.
535 Applies to lines after point.
536
537 If REGEXP contains upper case characters (excluding those preceded by `\\'),
538 the matching is case-sensitive.
539
540 Second and third arg RSTART and REND specify the region to operate on.
541
542 Interactively, in Transient Mark mode when the mark is active, operate
543 on the contents of the region. Otherwise, operate from point to the
544 end of the buffer."
545
546 (interactive
547 (progn
548 (barf-if-buffer-read-only)
549 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
550 (if rstart
551 (progn
552 (goto-char (min rstart rend))
553 (setq rend (copy-marker (max rstart rend))))
554 (if (and transient-mark-mode mark-active)
555 (setq rstart (region-beginning)
556 rend (copy-marker (region-end)))
557 (setq rstart (point)
558 rend (point-max-marker)))
559 (goto-char rstart))
560 (let ((case-fold-search (and case-fold-search
561 (isearch-no-upper-case-p regexp t))))
562 (save-excursion
563 (while (and (< (point) rend)
564 (re-search-forward regexp rend t))
565 (delete-region (save-excursion (goto-char (match-beginning 0))
566 (beginning-of-line)
567 (point))
568 (progn (forward-line 1) (point)))))))
569
570
571 (defun how-many (regexp &optional rstart rend)
572 "Print number of matches for REGEXP following point.
573
574 If REGEXP contains upper case characters (excluding those preceded by `\\'),
575 the matching is case-sensitive.
576
577 Second and third arg RSTART and REND specify the region to operate on.
578
579 Interactively, in Transient Mark mode when the mark is active, operate
580 on the contents of the region. Otherwise, operate from point to the
581 end of the buffer."
582
583 (interactive
584 (keep-lines-read-args "How many matches for (regexp): "))
585 (save-excursion
586 (if rstart
587 (goto-char (min rstart rend))
588 (if (and transient-mark-mode mark-active)
589 (setq rstart (region-beginning)
590 rend (copy-marker (region-end)))
591 (setq rstart (point)
592 rend (point-max-marker)))
593 (goto-char rstart))
594 (let ((count 0)
595 opoint
596 (case-fold-search (and case-fold-search
597 (isearch-no-upper-case-p regexp t))))
598 (while (and (< (point) rend)
599 (progn (setq opoint (point))
600 (re-search-forward regexp rend t)))
601 (if (= opoint (point))
602 (forward-char 1)
603 (setq count (1+ count))))
604 (message "%d occurrences" count))))
605
606 \f
607 (defvar occur-mode-map
608 (let ((map (make-sparse-keymap)))
609 (define-key map [mouse-2] 'occur-mode-mouse-goto)
610 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
611 (define-key map "\C-m" 'occur-mode-goto-occurrence)
612 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
613 (define-key map "\C-o" 'occur-mode-display-occurrence)
614 (define-key map "\M-n" 'occur-next)
615 (define-key map "\M-p" 'occur-prev)
616 (define-key map "r" 'occur-rename-buffer)
617 (define-key map "c" 'clone-buffer)
618 (define-key map "g" 'revert-buffer)
619 (define-key map "q" 'quit-window)
620 (define-key map "z" 'kill-this-buffer)
621 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
622 map)
623 "Keymap for `occur-mode'.")
624
625 (defvar occur-revert-arguments nil
626 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
627 See `occur-revert-function'.")
628
629 (defcustom occur-mode-hook '(turn-on-font-lock)
630 "Hook run when entering Occur mode."
631 :type 'hook
632 :group 'matching)
633
634 (defcustom occur-hook nil
635 "Hook run when `occur' is called."
636 :type 'hook
637 :group 'matching)
638
639 (put 'occur-mode 'mode-class 'special)
640 (defun occur-mode ()
641 "Major mode for output from \\[occur].
642 \\<occur-mode-map>Move point to one of the items in this buffer, then use
643 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
644 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
645
646 \\{occur-mode-map}"
647 (interactive)
648 (kill-all-local-variables)
649 (use-local-map occur-mode-map)
650 (setq major-mode 'occur-mode)
651 (setq mode-name "Occur")
652 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
653 (make-local-variable 'occur-revert-arguments)
654 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
655 (setq next-error-function 'occur-next-error)
656 (run-hooks 'occur-mode-hook))
657
658 (defun occur-revert-function (ignore1 ignore2)
659 "Handle `revert-buffer' for Occur mode buffers."
660 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
661
662 (defun occur-mode-mouse-goto (event)
663 "In Occur mode, go to the occurrence whose line you click on."
664 (interactive "e")
665 (let (pos)
666 (save-excursion
667 (set-buffer (window-buffer (posn-window (event-end event))))
668 (save-excursion
669 (goto-char (posn-point (event-end event)))
670 (setq pos (occur-mode-find-occurrence))))
671 (pop-to-buffer (marker-buffer pos))
672 (goto-char pos)))
673
674 (defun occur-mode-find-occurrence ()
675 (let ((pos (get-text-property (point) 'occur-target)))
676 (unless pos
677 (error "No occurrence on this line"))
678 (unless (buffer-live-p (marker-buffer pos))
679 (error "Buffer for this occurrence was killed"))
680 pos))
681
682 (defun occur-mode-goto-occurrence ()
683 "Go to the occurrence the current line describes."
684 (interactive)
685 (let ((pos (occur-mode-find-occurrence)))
686 (pop-to-buffer (marker-buffer pos))
687 (goto-char pos)))
688
689 (defun occur-mode-goto-occurrence-other-window ()
690 "Go to the occurrence the current line describes, in another window."
691 (interactive)
692 (let ((pos (occur-mode-find-occurrence)))
693 (switch-to-buffer-other-window (marker-buffer pos))
694 (goto-char pos)))
695
696 (defun occur-mode-display-occurrence ()
697 "Display in another window the occurrence the current line describes."
698 (interactive)
699 (let ((pos (occur-mode-find-occurrence))
700 window
701 ;; Bind these to ensure `display-buffer' puts it in another window.
702 same-window-buffer-names
703 same-window-regexps)
704 (setq window (display-buffer (marker-buffer pos)))
705 ;; This is the way to set point in the proper window.
706 (save-selected-window
707 (select-window window)
708 (goto-char pos))))
709
710 (defun occur-find-match (n search message)
711 (if (not n) (setq n 1))
712 (let ((r))
713 (while (> n 0)
714 (setq r (funcall search (point) 'occur-match))
715 (and r
716 (get-text-property r 'occur-match)
717 (setq r (funcall search r 'occur-match)))
718 (if r
719 (goto-char r)
720 (error message))
721 (setq n (1- n)))))
722
723 (defun occur-next (&optional n)
724 "Move to the Nth (default 1) next match in an Occur mode buffer."
725 (interactive "p")
726 (occur-find-match n #'next-single-property-change "No more matches"))
727
728 (defun occur-prev (&optional n)
729 "Move to the Nth (default 1) previous match in an Occur mode buffer."
730 (interactive "p")
731 (occur-find-match n #'previous-single-property-change "No earlier matches"))
732
733 (defun occur-next-error (&optional argp reset)
734 "Move to the Nth (default 1) next match in an Occur mode buffer.
735 Compatibility function for \\[next-error] invocations."
736 (interactive "p")
737 ;; we need to run occur-find-match from within the Occur buffer
738 (with-current-buffer
739 (if (next-error-buffer-p (current-buffer))
740 (current-buffer)
741 (next-error-find-buffer nil nil (lambda() (eq major-mode 'occur-mode))))
742
743 (when reset
744 (goto-char (point-min)))
745 (occur-find-match
746 (abs (prefix-numeric-value argp))
747 (if (> 0 (prefix-numeric-value argp))
748 #'previous-single-property-change
749 #'next-single-property-change)
750 "No more matches")
751 ;; In case the *Occur* buffer is visible in a nonselected window.
752 (set-window-point (get-buffer-window (current-buffer)) (point))
753 (occur-mode-goto-occurrence)))
754
755 \f
756 (defcustom list-matching-lines-default-context-lines 0
757 "*Default number of context lines included around `list-matching-lines' matches.
758 A negative number means to include that many lines before the match.
759 A positive number means to include that many lines both before and after."
760 :type 'integer
761 :group 'matching)
762
763 (defalias 'list-matching-lines 'occur)
764
765 (defcustom list-matching-lines-face 'bold
766 "*Face used by \\[list-matching-lines] to show the text that matches.
767 If the value is nil, don't highlight the matching portions specially."
768 :type 'face
769 :group 'matching)
770
771 (defcustom list-matching-lines-buffer-name-face 'underline
772 "*Face used by \\[list-matching-lines] to show the names of buffers.
773 If the value is nil, don't highlight the buffer names specially."
774 :type 'face
775 :group 'matching)
776
777 (defun occur-accumulate-lines (count &optional no-props)
778 (save-excursion
779 (let ((forwardp (> count 0))
780 (result nil))
781 (while (not (or (zerop count)
782 (if forwardp
783 (eobp)
784 (bobp))))
785 (setq count (+ count (if forwardp -1 1)))
786 (push
787 (funcall (if no-props
788 #'buffer-substring-no-properties
789 #'buffer-substring)
790 (line-beginning-position)
791 (line-end-position))
792 result)
793 (forward-line (if forwardp 1 -1)))
794 (nreverse result))))
795
796 (defun occur-read-primary-args ()
797 (list (let* ((default (car regexp-history))
798 (input
799 (read-from-minibuffer
800 (if default
801 (format "List lines matching regexp (default `%s'): "
802 (query-replace-descr default))
803 "List lines matching regexp: ")
804 nil
805 nil
806 nil
807 'regexp-history
808 default)))
809 (if (equal input "")
810 default
811 input))
812 (when current-prefix-arg
813 (prefix-numeric-value current-prefix-arg))))
814
815 (defun occur-rename-buffer (&optional unique-p)
816 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
817 Here `original-buffer-name' is the buffer name were occur was originally run.
818 When given the prefix argument, the renaming will not clobber the existing
819 buffer(s) of that name, but use `generate-new-buffer-name' instead.
820 You can add this to `occur-hook' if you always want a separate *Occur*
821 buffer for each buffer where you invoke `occur'."
822 (interactive "P")
823 (with-current-buffer
824 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
825 (rename-buffer (concat "*Occur: "
826 (mapconcat #'buffer-name
827 (car (cddr occur-revert-arguments)) "/")
828 "*")
829 unique-p)))
830
831 (defun occur (regexp &optional nlines)
832 "Show all lines in the current buffer containing a match for REGEXP.
833
834 If a match spreads across multiple lines, all those lines are shown.
835
836 Each line is displayed with NLINES lines before and after, or -NLINES
837 before if NLINES is negative.
838 NLINES defaults to `list-matching-lines-default-context-lines'.
839 Interactively it is the prefix arg.
840
841 The lines are shown in a buffer named `*Occur*'.
842 It serves as a menu to find any of the occurrences in this buffer.
843 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
844
845 If REGEXP contains upper case characters (excluding those preceded by `\\'),
846 the matching is case-sensitive."
847 (interactive (occur-read-primary-args))
848 (occur-1 regexp nlines (list (current-buffer))))
849
850 (defun multi-occur (bufs regexp &optional nlines)
851 "Show all lines in buffers BUFS containing a match for REGEXP.
852 This function acts on multiple buffers; otherwise, it is exactly like
853 `occur'."
854 (interactive
855 (cons
856 (let* ((bufs (list (read-buffer "First buffer to search: "
857 (current-buffer) t)))
858 (buf nil)
859 (ido-ignore-item-temp-list bufs))
860 (while (not (string-equal
861 (setq buf (read-buffer
862 (if (eq read-buffer-function 'ido-read-buffer)
863 "Next buffer to search (C-j to end): "
864 "Next buffer to search (RET to end): ")
865 nil t))
866 ""))
867 (add-to-list 'bufs buf)
868 (setq ido-ignore-item-temp-list bufs))
869 (nreverse (mapcar #'get-buffer bufs)))
870 (occur-read-primary-args)))
871 (occur-1 regexp nlines bufs))
872
873 (defun multi-occur-by-filename-regexp (bufregexp regexp &optional nlines)
874 "Show all lines matching REGEXP in buffers named by BUFREGEXP.
875 See also `multi-occur'."
876 (interactive
877 (cons
878 (let* ((default (car regexp-history))
879 (input
880 (read-from-minibuffer
881 "List lines in buffers whose filename matches regexp: "
882 nil
883 nil
884 nil
885 'regexp-history)))
886 (if (equal input "")
887 default
888 input))
889 (occur-read-primary-args)))
890 (when bufregexp
891 (occur-1 regexp nlines
892 (delq nil
893 (mapcar (lambda (buf)
894 (when (and (buffer-file-name buf)
895 (string-match bufregexp
896 (buffer-file-name buf)))
897 buf))
898 (buffer-list))))))
899
900 (defun occur-1 (regexp nlines bufs &optional buf-name)
901 (unless buf-name
902 (setq buf-name "*Occur*"))
903 (let ((occur-buf (get-buffer-create buf-name))
904 (made-temp-buf nil)
905 (active-bufs (delq nil (mapcar #'(lambda (buf)
906 (when (buffer-live-p buf) buf))
907 bufs))))
908 ;; Handle the case where one of the buffers we're searching is the
909 ;; *Occur* buffer itself.
910 (when (memq occur-buf bufs)
911 (setq occur-buf (with-current-buffer occur-buf
912 (clone-buffer "*Occur-temp*"))
913 made-temp-buf t))
914 (with-current-buffer occur-buf
915 (setq buffer-read-only nil)
916 (occur-mode)
917 (erase-buffer)
918 (let ((count (occur-engine
919 regexp active-bufs occur-buf
920 (or nlines list-matching-lines-default-context-lines)
921 (and case-fold-search
922 (isearch-no-upper-case-p regexp t))
923 list-matching-lines-buffer-name-face
924 nil list-matching-lines-face nil)))
925 (let* ((bufcount (length active-bufs))
926 (diff (- (length bufs) bufcount)))
927 (message "Searched %d buffer%s%s; %s match%s for `%s'"
928 bufcount (if (= bufcount 1) "" "s")
929 (if (zerop diff) "" (format " (%d killed)" diff))
930 (if (zerop count) "no" (format "%d" count))
931 (if (= count 1) "" "es")
932 regexp))
933 ;; If we had to make a temporary buffer, make it the *Occur*
934 ;; buffer now.
935 (when made-temp-buf
936 (with-current-buffer (get-buffer buf-name)
937 (kill-buffer (current-buffer)))
938 (rename-buffer buf-name))
939 (setq occur-revert-arguments (list regexp nlines bufs)
940 buffer-read-only t)
941 (if (> count 0)
942 (progn
943 (display-buffer occur-buf)
944 (setq next-error-last-buffer occur-buf))
945 (kill-buffer occur-buf)))
946 (run-hooks 'occur-hook))))
947
948 (defun occur-engine-add-prefix (lines)
949 (mapcar
950 #'(lambda (line)
951 (concat " :" line "\n"))
952 lines))
953
954 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
955 title-face prefix-face match-face keep-props)
956 (with-current-buffer out-buf
957 (setq buffer-read-only nil)
958 (let ((globalcount 0)
959 (coding nil))
960 ;; Map over all the buffers
961 (dolist (buf buffers)
962 (when (buffer-live-p buf)
963 (let ((matches 0) ;; count of matched lines
964 (lines 1) ;; line count
965 (matchbeg 0)
966 (origpt nil)
967 (begpt nil)
968 (endpt nil)
969 (marker nil)
970 (curstring "")
971 (headerpt (with-current-buffer out-buf (point))))
972 (save-excursion
973 (set-buffer buf)
974 (or coding
975 ;; Set CODING only if the current buffer locally
976 ;; binds buffer-file-coding-system.
977 (not (local-variable-p 'buffer-file-coding-system))
978 (setq coding buffer-file-coding-system))
979 (save-excursion
980 (goto-char (point-min)) ;; begin searching in the buffer
981 (while (not (eobp))
982 (setq origpt (point))
983 (when (setq endpt (re-search-forward regexp nil t))
984 (setq matches (1+ matches)) ;; increment match count
985 (setq matchbeg (match-beginning 0))
986 (setq begpt (save-excursion
987 (goto-char matchbeg)
988 (line-beginning-position)))
989 (setq lines (+ lines (1- (count-lines origpt endpt))))
990 (setq marker (make-marker))
991 (set-marker marker matchbeg)
992 (setq curstring (buffer-substring begpt
993 (line-end-position)))
994 ;; Depropertize the string, and maybe
995 ;; highlight the matches
996 (let ((len (length curstring))
997 (start 0))
998 (unless keep-props
999 (set-text-properties 0 len nil curstring))
1000 (while (and (< start len)
1001 (string-match regexp curstring start))
1002 (add-text-properties (match-beginning 0)
1003 (match-end 0)
1004 (append
1005 `(occur-match t)
1006 (when match-face
1007 `(font-lock-face ,match-face)))
1008 curstring)
1009 (setq start (match-end 0))))
1010 ;; Generate the string to insert for this match
1011 (let* ((out-line
1012 (concat
1013 ;; Using 7 digits aligns tabs properly.
1014 (apply #'propertize (format "%7d:" lines)
1015 (append
1016 (when prefix-face
1017 `(font-lock-face prefix-face))
1018 '(occur-prefix t)))
1019 curstring
1020 "\n"))
1021 (data
1022 (if (= nlines 0)
1023 ;; The simple display style
1024 out-line
1025 ;; The complex multi-line display
1026 ;; style. Generate a list of lines,
1027 ;; concatenate them all together.
1028 (apply #'concat
1029 (nconc
1030 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ (abs nlines))) keep-props))))
1031 (list out-line)
1032 (if (> nlines 0)
1033 (occur-engine-add-prefix
1034 (cdr (occur-accumulate-lines (1+ nlines) keep-props)))))))))
1035 ;; Actually insert the match display data
1036 (with-current-buffer out-buf
1037 (let ((beg (point))
1038 (end (progn (insert data) (point))))
1039 (unless (= nlines 0)
1040 (insert "-------\n"))
1041 (add-text-properties
1042 beg end
1043 `(occur-target ,marker help-echo "mouse-2: go to this occurrence"))
1044 ;; We don't put `mouse-face' on the newline,
1045 ;; because that loses.
1046 (add-text-properties beg (1- end) '(mouse-face highlight)))))
1047 (goto-char endpt))
1048 (if endpt
1049 (progn
1050 (setq lines (1+ lines))
1051 ;; On to the next match...
1052 (forward-line 1))
1053 (goto-char (point-max))))))
1054 (when (not (zerop matches)) ;; is the count zero?
1055 (setq globalcount (+ globalcount matches))
1056 (with-current-buffer out-buf
1057 (goto-char headerpt)
1058 (let ((beg (point))
1059 end)
1060 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1061 matches (if (= matches 1) "" "es")
1062 regexp (buffer-name buf)))
1063 (setq end (point))
1064 (add-text-properties beg end
1065 (append
1066 (when title-face
1067 `(font-lock-face ,title-face))
1068 `(occur-title ,buf))))
1069 (goto-char (point-min)))))))
1070 (if coding
1071 ;; CODING is buffer-file-coding-system of the first buffer
1072 ;; that locally binds it. Let's use it also for the output
1073 ;; buffer.
1074 (set-buffer-file-coding-system coding))
1075 ;; Return the number of matches
1076 globalcount)))
1077
1078 \f
1079 ;; It would be nice to use \\[...], but there is no reasonable way
1080 ;; to make that display both SPC and Y.
1081 (defconst query-replace-help
1082 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1083 RET or `q' to exit, Period to replace one match and exit,
1084 Comma to replace but not move point immediately,
1085 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1086 C-w to delete match and recursive edit,
1087 C-l to clear the screen, redisplay, and offer same replacement again,
1088 ! to replace all remaining matches with no more questions,
1089 ^ to move point back to previous match,
1090 E to edit the replacement string"
1091 "Help message while in `query-replace'.")
1092
1093 (defvar query-replace-map (make-sparse-keymap)
1094 "Keymap that defines the responses to questions in `query-replace'.
1095 The \"bindings\" in this map are not commands; they are answers.
1096 The valid answers include `act', `skip', `act-and-show',
1097 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1098 `automatic', `backup', `exit-prefix', and `help'.")
1099
1100 (define-key query-replace-map " " 'act)
1101 (define-key query-replace-map "\d" 'skip)
1102 (define-key query-replace-map [delete] 'skip)
1103 (define-key query-replace-map [backspace] 'skip)
1104 (define-key query-replace-map "y" 'act)
1105 (define-key query-replace-map "n" 'skip)
1106 (define-key query-replace-map "Y" 'act)
1107 (define-key query-replace-map "N" 'skip)
1108 (define-key query-replace-map "e" 'edit-replacement)
1109 (define-key query-replace-map "E" 'edit-replacement)
1110 (define-key query-replace-map "," 'act-and-show)
1111 (define-key query-replace-map "q" 'exit)
1112 (define-key query-replace-map "\r" 'exit)
1113 (define-key query-replace-map [return] 'exit)
1114 (define-key query-replace-map "." 'act-and-exit)
1115 (define-key query-replace-map "\C-r" 'edit)
1116 (define-key query-replace-map "\C-w" 'delete-and-edit)
1117 (define-key query-replace-map "\C-l" 'recenter)
1118 (define-key query-replace-map "!" 'automatic)
1119 (define-key query-replace-map "^" 'backup)
1120 (define-key query-replace-map "\C-h" 'help)
1121 (define-key query-replace-map [f1] 'help)
1122 (define-key query-replace-map [help] 'help)
1123 (define-key query-replace-map "?" 'help)
1124 (define-key query-replace-map "\C-g" 'quit)
1125 (define-key query-replace-map "\C-]" 'quit)
1126 (define-key query-replace-map "\e" 'exit-prefix)
1127 (define-key query-replace-map [escape] 'exit-prefix)
1128
1129 (defun replace-match-string-symbols (n)
1130 "Process a list (and any sub-lists), expanding certain symbols.
1131 Symbol Expands To
1132 N (match-string N) (where N is a string of digits)
1133 #N (string-to-number (match-string N))
1134 & (match-string 0)
1135 #& (string-to-number (match-string 0))
1136 # replace-count
1137
1138 Note that these symbols must be preceeded by a backslash in order to
1139 type them."
1140 (while n
1141 (cond
1142 ((consp (car n))
1143 (replace-match-string-symbols (car n))) ;Process sub-list
1144 ((symbolp (car n))
1145 (let ((name (symbol-name (car n))))
1146 (cond
1147 ((string-match "^[0-9]+$" name)
1148 (setcar n (list 'match-string (string-to-number name))))
1149 ((string-match "^#[0-9]+$" name)
1150 (setcar n (list 'string-to-number
1151 (list 'match-string
1152 (string-to-number (substring name 1))))))
1153 ((string= "&" name)
1154 (setcar n '(match-string 0)))
1155 ((string= "#&" name)
1156 (setcar n '(string-to-number (match-string 0))))
1157 ((string= "#" name)
1158 (setcar n 'replace-count))))))
1159 (setq n (cdr n))))
1160
1161 (defun replace-eval-replacement (expression replace-count)
1162 (let ((replacement (eval expression)))
1163 (if (stringp replacement)
1164 replacement
1165 (prin1-to-string replacement t))))
1166
1167 (defun replace-quote (replacement)
1168 "Quote a replacement string.
1169 This just doubles all backslashes in REPLACEMENT and
1170 returns the resulting string. If REPLACEMENT is not
1171 a string, it is first passed through `prin1-to-string'
1172 with the `noescape' argument set.
1173
1174 `match-data' is preserved across the call."
1175 (save-match-data
1176 (replace-regexp-in-string "\\\\" "\\\\"
1177 (if (stringp replacement)
1178 replacement
1179 (prin1-to-string replacement t))
1180 t t)))
1181
1182 (defun replace-loop-through-replacements (data replace-count)
1183 ;; DATA is a vector contaning the following values:
1184 ;; 0 next-rotate-count
1185 ;; 1 repeat-count
1186 ;; 2 next-replacement
1187 ;; 3 replacements
1188 (if (= (aref data 0) replace-count)
1189 (progn
1190 (aset data 0 (+ replace-count (aref data 1)))
1191 (let ((next (cdr (aref data 2))))
1192 (aset data 2 (if (consp next) next (aref data 3))))))
1193 (car (aref data 2)))
1194
1195 (defun replace-match-data (integers reuse &optional new)
1196 "Like `match-data', but markers in REUSE get invalidated.
1197 If NEW is non-NIL, it is set and returned instead of fresh data,
1198 but coerced to the correct value of INTEGERS."
1199 (or (and new
1200 (progn
1201 (set-match-data new)
1202 (and (eq new reuse)
1203 (eq (null integers) (markerp (car reuse)))
1204 new)))
1205 (match-data integers
1206 (prog1 reuse
1207 (while reuse
1208 (if (markerp (car reuse))
1209 (set-marker (car reuse) nil))
1210 (setq reuse (cdr reuse)))))))
1211
1212 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1213 "Make a replacement with `replace-match', editing `\\?'.
1214 NEXTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1215 check for `\\?' is made to save time. MATCH-DATA is used for the
1216 replacement. In case editing is done, it is changed to use markers.
1217
1218 The return value is non-NIL if there has been no `\\?' or NOEDIT was
1219 passed in. If LITERAL is set, no checking is done, anyway."
1220 (unless (or literal noedit)
1221 (setq noedit t)
1222 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1223 newtext)
1224 (setq newtext
1225 (read-input "Edit replacement string: "
1226 (prog1
1227 (cons
1228 (replace-match "" t t newtext 3)
1229 (1+ (match-beginning 3)))
1230 (setq match-data
1231 (replace-match-data
1232 nil match-data match-data))))
1233 noedit nil)))
1234 (set-match-data match-data)
1235 (replace-match newtext fixedcase literal)
1236 noedit)
1237
1238 (defun perform-replace (from-string replacements
1239 query-flag regexp-flag delimited-flag
1240 &optional repeat-count map start end)
1241 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1242 Don't use this in your own program unless you want to query and set the mark
1243 just as `query-replace' does. Instead, write a simple loop like this:
1244
1245 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1246 (replace-match \"foobar\" nil nil))
1247
1248 which will run faster and probably do exactly what you want. Please
1249 see the documentation of `replace-match' to find out how to simulate
1250 `case-replace'.
1251
1252 This function returns nil if and only if there were no matches to
1253 make, or the user didn't cancel the call."
1254 (or map (setq map query-replace-map))
1255 (and query-flag minibuffer-auto-raise
1256 (raise-frame (window-frame (minibuffer-window))))
1257 (let ((nocasify (not (and case-fold-search case-replace
1258 (string-equal from-string
1259 (downcase from-string)))))
1260 (case-fold-search (and case-fold-search
1261 (string-equal from-string
1262 (downcase from-string))))
1263 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1264 (search-function (if regexp-flag 're-search-forward 'search-forward))
1265 (search-string from-string)
1266 (real-match-data nil) ; the match data for the current match
1267 (next-replacement nil)
1268 (noedit nil)
1269 (keep-going t)
1270 (stack nil)
1271 (replace-count 0)
1272 (nonempty-match nil)
1273
1274 ;; If non-nil, it is marker saying where in the buffer to stop.
1275 (limit nil)
1276
1277 ;; Data for the next match. If a cons, it has the same format as
1278 ;; (match-data); otherwise it is t if a match is possible at point.
1279 (match-again t)
1280
1281 (message
1282 (if query-flag
1283 (substitute-command-keys
1284 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) "))))
1285
1286 ;; If region is active, in Transient Mark mode, operate on region.
1287 (when start
1288 (setq limit (copy-marker (max start end)))
1289 (goto-char (min start end))
1290 (deactivate-mark))
1291
1292 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1293 ;; containing a function and its first argument. The function is
1294 ;; called to generate each replacement like this:
1295 ;; (funcall (car replacements) (cdr replacements) replace-count)
1296 ;; It must return a string.
1297 (cond
1298 ((stringp replacements)
1299 (setq next-replacement replacements
1300 replacements nil))
1301 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1302 (or repeat-count (setq repeat-count 1))
1303 (setq replacements (cons 'replace-loop-through-replacements
1304 (vector repeat-count repeat-count
1305 replacements replacements)))))
1306
1307 (if delimited-flag
1308 (setq search-function 're-search-forward
1309 search-string (concat "\\b"
1310 (if regexp-flag from-string
1311 (regexp-quote from-string))
1312 "\\b")))
1313 (push-mark)
1314 (undo-boundary)
1315 (unwind-protect
1316 ;; Loop finding occurrences that perhaps should be replaced.
1317 (while (and keep-going
1318 (not (or (eobp) (and limit (>= (point) limit))))
1319 ;; Use the next match if it is already known;
1320 ;; otherwise, search for a match after moving forward
1321 ;; one char if progress is required.
1322 (setq real-match-data
1323 (if (consp match-again)
1324 (progn (goto-char (nth 1 match-again))
1325 (replace-match-data t
1326 real-match-data
1327 match-again))
1328 (and (or match-again
1329 ;; MATCH-AGAIN non-nil means we
1330 ;; accept an adjacent match. If
1331 ;; we don't, move one char to the
1332 ;; right. This takes us a
1333 ;; character too far at the end,
1334 ;; but this is undone after the
1335 ;; while-loop.
1336 (progn
1337 (forward-char 1)
1338 (not (or (eobp)
1339 (and limit (>= (point) limit))))))
1340 (funcall search-function search-string limit t)
1341 ;; For speed, use only integers and
1342 ;; reuse the list used last time.
1343 (replace-match-data t real-match-data)))))
1344 ;; Optionally ignore matches that have a read-only property.
1345 (unless (and query-replace-skip-read-only
1346 (text-property-not-all
1347 (match-beginning 0) (match-end 0)
1348 'read-only nil))
1349
1350 ;; Record whether the match is nonempty, to avoid an infinite loop
1351 ;; repeatedly matching the same empty string.
1352 (setq nonempty-match
1353 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1354
1355 ;; If the match is empty, record that the next one can't be
1356 ;; adjacent.
1357
1358 ;; Otherwise, if matching a regular expression, do the next
1359 ;; match now, since the replacement for this match may
1360 ;; affect whether the next match is adjacent to this one.
1361 ;; If that match is empty, don't use it.
1362 (setq match-again
1363 (and nonempty-match
1364 (or (not regexp-flag)
1365 (and (looking-at search-string)
1366 (let ((match (match-data)))
1367 (and (/= (nth 0 match) (nth 1 match))
1368 match))))))
1369
1370 ;; Calculate the replacement string, if necessary.
1371 (when replacements
1372 (set-match-data real-match-data)
1373 (setq next-replacement
1374 (funcall (car replacements) (cdr replacements)
1375 replace-count)
1376 noedit nil))
1377 (if (not query-flag)
1378 (let ((inhibit-read-only
1379 query-replace-skip-read-only))
1380 (unless noedit
1381 (replace-highlight (nth 0 real-match-data)
1382 (nth 1 real-match-data)))
1383 (setq noedit
1384 (replace-match-maybe-edit
1385 next-replacement nocasify literal
1386 noedit real-match-data)
1387 replace-count (1+ replace-count)))
1388 (undo-boundary)
1389 (let (done replaced key def)
1390 ;; Loop reading commands until one of them sets done,
1391 ;; which means it has finished handling this
1392 ;; occurrence. Any command that sets `done' should
1393 ;; leave behind proper match data for the stack.
1394 ;; Commands not setting `done' need to adjust
1395 ;; `real-match-data'.
1396 (while (not done)
1397 (set-match-data real-match-data)
1398 (replace-highlight (match-beginning 0) (match-end 0))
1399 ;; Bind message-log-max so we don't fill up the message log
1400 ;; with a bunch of identical messages.
1401 (let ((message-log-max nil))
1402 (message message
1403 (query-replace-descr from-string)
1404 (query-replace-descr next-replacement)))
1405 (setq key (read-event))
1406 ;; Necessary in case something happens during read-event
1407 ;; that clobbers the match data.
1408 (set-match-data real-match-data)
1409 (setq key (vector key))
1410 (setq def (lookup-key map key))
1411 ;; Restore the match data while we process the command.
1412 (cond ((eq def 'help)
1413 (with-output-to-temp-buffer "*Help*"
1414 (princ
1415 (concat "Query replacing "
1416 (if regexp-flag "regexp " "")
1417 from-string " with "
1418 next-replacement ".\n\n"
1419 (substitute-command-keys
1420 query-replace-help)))
1421 (with-current-buffer standard-output
1422 (help-mode))))
1423 ((eq def 'exit)
1424 (setq keep-going nil)
1425 (setq done t))
1426 ((eq def 'backup)
1427 (if stack
1428 (let ((elt (pop stack)))
1429 (goto-char (nth 0 elt))
1430 (setq replaced (nth 1 elt)
1431 real-match-data
1432 (replace-match-data
1433 t real-match-data
1434 (nth 2 elt))))
1435 (message "No previous match")
1436 (ding 'no-terminate)
1437 (sit-for 1)))
1438 ((eq def 'act)
1439 (or replaced
1440 (setq noedit
1441 (replace-match-maybe-edit
1442 next-replacement nocasify literal
1443 noedit real-match-data)
1444 replace-count (1+ replace-count)))
1445 (setq done t replaced t))
1446 ((eq def 'act-and-exit)
1447 (or replaced
1448 (setq noedit
1449 (replace-match-maybe-edit
1450 next-replacement nocasify literal
1451 noedit real-match-data)
1452 replace-count (1+ replace-count)))
1453 (setq keep-going nil)
1454 (setq done t replaced t))
1455 ((eq def 'act-and-show)
1456 (if (not replaced)
1457 (setq noedit
1458 (replace-match-maybe-edit
1459 next-replacement nocasify literal
1460 noedit real-match-data)
1461 replace-count (1+ replace-count)
1462 real-match-data (replace-match-data
1463 t real-match-data)
1464 replaced t)))
1465 ((eq def 'automatic)
1466 (or replaced
1467 (setq noedit
1468 (replace-match-maybe-edit
1469 next-replacement nocasify literal
1470 noedit real-match-data)
1471 replace-count (1+ replace-count)))
1472 (setq done t query-flag nil replaced t))
1473 ((eq def 'skip)
1474 (setq done t))
1475 ((eq def 'recenter)
1476 (recenter nil))
1477 ((eq def 'edit)
1478 (let ((opos (point-marker)))
1479 (setq real-match-data (replace-match-data
1480 nil real-match-data
1481 real-match-data))
1482 (goto-char (match-beginning 0))
1483 (save-excursion
1484 (save-window-excursion
1485 (recursive-edit)))
1486 (goto-char opos)
1487 (set-marker opos nil))
1488 ;; Before we make the replacement,
1489 ;; decide whether the search string
1490 ;; can match again just after this match.
1491 (if (and regexp-flag nonempty-match)
1492 (setq match-again (and (looking-at search-string)
1493 (match-data)))))
1494 ;; Edit replacement.
1495 ((eq def 'edit-replacement)
1496 (setq real-match-data (replace-match-data
1497 nil real-match-data
1498 real-match-data)
1499 next-replacement
1500 (read-input "Edit replacement string: "
1501 next-replacement)
1502 noedit nil)
1503 (if replaced
1504 (set-match-data real-match-data)
1505 (setq noedit
1506 (replace-match-maybe-edit
1507 next-replacement nocasify literal noedit
1508 real-match-data)
1509 replaced t))
1510 (setq done t))
1511
1512 ((eq def 'delete-and-edit)
1513 (replace-match "" t t)
1514 (setq real-match-data (replace-match-data
1515 nil real-match-data))
1516 (replace-dehighlight)
1517 (save-excursion (recursive-edit))
1518 (setq replaced t))
1519 ;; Note: we do not need to treat `exit-prefix'
1520 ;; specially here, since we reread
1521 ;; any unrecognized character.
1522 (t
1523 (setq this-command 'mode-exited)
1524 (setq keep-going nil)
1525 (setq unread-command-events
1526 (append (listify-key-sequence key)
1527 unread-command-events))
1528 (setq done t))))
1529 ;; Record previous position for ^ when we move on.
1530 ;; Change markers to numbers in the match data
1531 ;; since lots of markers slow down editing.
1532 (push (list (point) replaced
1533 ;;; If the replacement has already happened, all we need is the
1534 ;;; current match start and end. We could get this with a trivial
1535 ;;; match like
1536 ;;; (save-excursion (goto-char (match-beginning 0))
1537 ;;; (search-forward (match-string 0))
1538 ;;; (match-data t))
1539 ;;; if we really wanted to avoid manually constructing match data.
1540 ;;; Adding current-buffer is necessary so that match-data calls can
1541 ;;; return markers which are appropriate for editing.
1542 (if replaced
1543 (list
1544 (match-beginning 0)
1545 (match-end 0)
1546 (current-buffer))
1547 (match-data t)))
1548 stack)))))
1549
1550 ;; The code preventing adjacent regexp matches in the condition
1551 ;; of the while-loop above will haven taken us one character
1552 ;; beyond the last replacement. Undo that.
1553 (when (and regexp-flag (not match-again) (> replace-count 0))
1554 (backward-char 1))
1555
1556 (replace-dehighlight))
1557 (or unread-command-events
1558 (message "Replaced %d occurrence%s"
1559 replace-count
1560 (if (= replace-count 1) "" "s")))
1561 (and keep-going stack)))
1562
1563 (defcustom query-replace-highlight t
1564 "*Non-nil means to highlight words during query replacement."
1565 :type 'boolean
1566 :group 'matching)
1567
1568 (defvar replace-overlay nil)
1569
1570 (defun replace-dehighlight ()
1571 (and replace-overlay
1572 (progn
1573 (delete-overlay replace-overlay)
1574 (setq replace-overlay nil))))
1575
1576 (defun replace-highlight (start end)
1577 (and query-replace-highlight
1578 (if replace-overlay
1579 (move-overlay replace-overlay start end (current-buffer))
1580 (setq replace-overlay (make-overlay start end))
1581 (overlay-put replace-overlay 'face
1582 (if (facep 'query-replace)
1583 'query-replace 'region)))))
1584
1585 ;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1586 ;;; replace.el ends here