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