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