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