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