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