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