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