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