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