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