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