* progmodes/cc-vars.el (defcustom-c-stylevar): Eval VAL.
[emacs.git] / lisp / replace.el
blob8bd3bec20a0a410ace63314360f44a5b98373e30
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 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.")
525 (defalias 'delete-non-matching-lines 'keep-lines)
526 (defalias 'delete-matching-lines 'flush-lines)
527 (defalias 'count-matches 'how-many)
530 (defun keep-lines-read-args (prompt)
531 "Read arguments for `keep-lines' and friends.
532 Prompt for a regexp with PROMPT.
533 Value is a list, (REGEXP)."
534 (let* ((default (list
535 (regexp-quote
536 (or (funcall (or find-tag-default-function
537 (get major-mode 'find-tag-default-function)
538 'find-tag-default))
539 ""))
540 (car regexp-search-ring)
541 (regexp-quote (or (car search-ring) ""))
542 (car (symbol-value
543 query-replace-from-history-variable))))
544 (default (delete-dups (delq nil (delete "" default)))))
545 (list (read-from-minibuffer prompt nil nil nil
546 'regexp-history default t)
547 nil nil t)))
549 (defun keep-lines (regexp &optional rstart rend interactive)
550 "Delete all lines except those containing matches for REGEXP.
551 A match split across lines preserves all the lines it lies in.
552 When called from Lisp (and usually interactively as well, see below)
553 applies to all lines starting after point.
555 If REGEXP contains upper case characters (excluding those preceded by `\\')
556 and `search-upper-case' is non-nil, the matching is case-sensitive.
558 Second and third arg RSTART and REND specify the region to operate on.
559 This command operates on (the accessible part of) all lines whose
560 accessible part is entirely contained in the region determined by RSTART
561 and REND. (A newline ending a line counts as part of that line.)
563 Interactively, in Transient Mark mode when the mark is active, operate
564 on all lines whose accessible part is entirely contained in the region.
565 Otherwise, the command applies to all lines starting after point.
566 When calling this function from Lisp, you can pretend that it was
567 called interactively by passing a non-nil INTERACTIVE argument.
569 This function starts looking for the next match from the end of
570 the previous match. Hence, it ignores matches that overlap
571 a previously found match."
573 (interactive
574 (progn
575 (barf-if-buffer-read-only)
576 (keep-lines-read-args "Keep lines (containing match for regexp): ")))
577 (if rstart
578 (progn
579 (goto-char (min rstart rend))
580 (setq rend
581 (progn
582 (save-excursion
583 (goto-char (max rstart rend))
584 (unless (or (bolp) (eobp))
585 (forward-line 0))
586 (point-marker)))))
587 (if (and interactive transient-mark-mode mark-active)
588 (setq rstart (region-beginning)
589 rend (progn
590 (goto-char (region-end))
591 (unless (or (bolp) (eobp))
592 (forward-line 0))
593 (point-marker)))
594 (setq rstart (point)
595 rend (point-max-marker)))
596 (goto-char rstart))
597 (save-excursion
598 (or (bolp) (forward-line 1))
599 (let ((start (point))
600 (case-fold-search
601 (if (and case-fold-search search-upper-case)
602 (isearch-no-upper-case-p regexp t)
603 case-fold-search)))
604 (while (< (point) rend)
605 ;; Start is first char not preserved by previous match.
606 (if (not (re-search-forward regexp rend 'move))
607 (delete-region start rend)
608 (let ((end (save-excursion (goto-char (match-beginning 0))
609 (forward-line 0)
610 (point))))
611 ;; Now end is first char preserved by the new match.
612 (if (< start end)
613 (delete-region start end))))
615 (setq start (save-excursion (forward-line 1) (point)))
616 ;; If the match was empty, avoid matching again at same place.
617 (and (< (point) rend)
618 (= (match-beginning 0) (match-end 0))
619 (forward-char 1)))))
620 (set-marker rend nil)
621 nil)
624 (defun flush-lines (regexp &optional rstart rend interactive)
625 "Delete lines containing matches for REGEXP.
626 When called from Lisp (and usually when called interactively as
627 well, see below), applies to the part of the buffer after point.
628 The line point is in is deleted if and only if it contains a
629 match for regexp starting after point.
631 If REGEXP contains upper case characters (excluding those preceded by `\\')
632 and `search-upper-case' is non-nil, the matching is case-sensitive.
634 Second and third arg RSTART and REND specify the region to operate on.
635 Lines partially contained in this region are deleted if and only if
636 they contain a match entirely contained in it.
638 Interactively, in Transient Mark mode when the mark is active, operate
639 on the contents of the region. Otherwise, operate from point to the
640 end of (the accessible portion of) the buffer. When calling this function
641 from Lisp, you can pretend that it was called interactively by passing
642 a non-nil INTERACTIVE argument.
644 If a match is split across lines, all the lines it lies in are deleted.
645 They are deleted _before_ looking for the next match. Hence, a match
646 starting on the same line at which another match ended is ignored."
648 (interactive
649 (progn
650 (barf-if-buffer-read-only)
651 (keep-lines-read-args "Flush lines (containing match for regexp): ")))
652 (if rstart
653 (progn
654 (goto-char (min rstart rend))
655 (setq rend (copy-marker (max rstart rend))))
656 (if (and interactive transient-mark-mode mark-active)
657 (setq rstart (region-beginning)
658 rend (copy-marker (region-end)))
659 (setq rstart (point)
660 rend (point-max-marker)))
661 (goto-char rstart))
662 (let ((case-fold-search
663 (if (and case-fold-search search-upper-case)
664 (isearch-no-upper-case-p regexp t)
665 case-fold-search)))
666 (save-excursion
667 (while (and (< (point) rend)
668 (re-search-forward regexp rend t))
669 (delete-region (save-excursion (goto-char (match-beginning 0))
670 (forward-line 0)
671 (point))
672 (progn (forward-line 1) (point))))))
673 (set-marker rend nil)
674 nil)
677 (defun how-many (regexp &optional rstart rend interactive)
678 "Print and return number of matches for REGEXP following point.
679 When called from Lisp and INTERACTIVE is omitted or nil, just return
680 the number, do not print it; if INTERACTIVE is t, the function behaves
681 in all respects has if it had been called interactively.
683 If REGEXP contains upper case characters (excluding those preceded by `\\')
684 and `search-upper-case' is non-nil, the matching is case-sensitive.
686 Second and third arg RSTART and REND specify the region to operate on.
688 Interactively, in Transient Mark mode when the mark is active, operate
689 on the contents of the region. Otherwise, operate from point to the
690 end of (the accessible portion of) the buffer.
692 This function starts looking for the next match from the end of
693 the previous match. Hence, it ignores matches that overlap
694 a previously found match."
696 (interactive
697 (keep-lines-read-args "How many matches for (regexp): "))
698 (save-excursion
699 (if rstart
700 (progn
701 (goto-char (min rstart rend))
702 (setq rend (max rstart rend)))
703 (if (and interactive transient-mark-mode mark-active)
704 (setq rstart (region-beginning)
705 rend (region-end))
706 (setq rstart (point)
707 rend (point-max)))
708 (goto-char rstart))
709 (let ((count 0)
710 opoint
711 (case-fold-search
712 (if (and case-fold-search search-upper-case)
713 (isearch-no-upper-case-p regexp t)
714 case-fold-search)))
715 (while (and (< (point) rend)
716 (progn (setq opoint (point))
717 (re-search-forward regexp rend t)))
718 (if (= opoint (point))
719 (forward-char 1)
720 (setq count (1+ count))))
721 (when interactive (message "%d occurrence%s"
722 count
723 (if (= count 1) "" "s")))
724 count)))
727 (defvar occur-mode-map
728 (let ((map (make-sparse-keymap)))
729 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
730 (define-key map [mouse-2] 'occur-mode-mouse-goto)
731 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
732 (define-key map "\C-m" 'occur-mode-goto-occurrence)
733 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
734 (define-key map "\C-o" 'occur-mode-display-occurrence)
735 (define-key map "\M-n" 'occur-next)
736 (define-key map "\M-p" 'occur-prev)
737 (define-key map "r" 'occur-rename-buffer)
738 (define-key map "c" 'clone-buffer)
739 (define-key map "g" 'revert-buffer)
740 (define-key map "q" 'quit-window)
741 (define-key map "z" 'kill-this-buffer)
742 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
743 (define-key map [menu-bar] (make-sparse-keymap))
744 (define-key map [menu-bar occur]
745 (cons "Occur" map))
746 (define-key map [next-error-follow-minor-mode]
747 (menu-bar-make-mm-toggle next-error-follow-minor-mode
748 "Auto Occurrence Display"
749 "Display another occurrence when moving the cursor"))
750 (define-key map [separator-1] '("--"))
751 (define-key map [kill-this-buffer]
752 '("Kill occur buffer" . kill-this-buffer))
753 (define-key map [quit-window]
754 '("Quit occur window" . quit-window))
755 (define-key map [revert-buffer]
756 '("Revert occur buffer" . revert-buffer))
757 (define-key map [clone-buffer]
758 '("Clone occur buffer" . clone-buffer))
759 (define-key map [occur-rename-buffer]
760 '("Rename occur buffer" . occur-rename-buffer))
761 (define-key map [separator-2] '("--"))
762 (define-key map [occur-mode-goto-occurrence-other-window]
763 '("Go To Occurrence Other Window" . occur-mode-goto-occurrence-other-window))
764 (define-key map [occur-mode-goto-occurrence]
765 '("Go To Occurrence" . occur-mode-goto-occurrence))
766 (define-key map [occur-mode-display-occurrence]
767 '("Display Occurrence" . occur-mode-display-occurrence))
768 (define-key map [occur-next]
769 '("Move to next match" . occur-next))
770 (define-key map [occur-prev]
771 '("Move to previous match" . occur-prev))
772 map)
773 "Keymap for `occur-mode'.")
775 (defvar occur-revert-arguments nil
776 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
777 See `occur-revert-function'.")
779 (defcustom occur-mode-hook '(turn-on-font-lock)
780 "Hook run when entering Occur mode."
781 :type 'hook
782 :group 'matching)
784 (defcustom occur-hook nil
785 "Hook run by Occur when there are any matches."
786 :type 'hook
787 :group 'matching)
789 (put 'occur-mode 'mode-class 'special)
790 (defun occur-mode ()
791 "Major mode for output from \\[occur].
792 \\<occur-mode-map>Move point to one of the items in this buffer, then use
793 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
794 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
796 \\{occur-mode-map}"
797 (interactive)
798 (kill-all-local-variables)
799 (use-local-map occur-mode-map)
800 (setq major-mode 'occur-mode)
801 (setq mode-name "Occur")
802 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
803 (make-local-variable 'occur-revert-arguments)
804 (add-hook 'change-major-mode-hook 'font-lock-defontify nil t)
805 (setq next-error-function 'occur-next-error)
806 (run-mode-hooks 'occur-mode-hook))
808 (defun occur-revert-function (ignore1 ignore2)
809 "Handle `revert-buffer' for Occur mode buffers."
810 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
812 (defun occur-mode-find-occurrence ()
813 (let ((pos (get-text-property (point) 'occur-target)))
814 (unless pos
815 (error "No occurrence on this line"))
816 (unless (buffer-live-p (marker-buffer pos))
817 (error "Buffer for this occurrence was killed"))
818 pos))
820 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
821 (defun occur-mode-goto-occurrence (&optional event)
822 "Go to the occurrence the current line describes."
823 (interactive (list last-nonmenu-event))
824 (let ((pos
825 (if (null event)
826 ;; Actually `event-end' works correctly with a nil argument as
827 ;; well, so we could dispense with this test, but let's not
828 ;; rely on this undocumented behavior.
829 (occur-mode-find-occurrence)
830 (with-current-buffer (window-buffer (posn-window (event-end event)))
831 (save-excursion
832 (goto-char (posn-point (event-end event)))
833 (occur-mode-find-occurrence)))))
834 same-window-buffer-names
835 same-window-regexps)
836 (pop-to-buffer (marker-buffer pos))
837 (goto-char pos)))
839 (defun occur-mode-goto-occurrence-other-window ()
840 "Go to the occurrence the current line describes, in another window."
841 (interactive)
842 (let ((pos (occur-mode-find-occurrence)))
843 (switch-to-buffer-other-window (marker-buffer pos))
844 (goto-char pos)))
846 (defun occur-mode-display-occurrence ()
847 "Display in another window the occurrence the current line describes."
848 (interactive)
849 (let ((pos (occur-mode-find-occurrence))
850 window
851 ;; Bind these to ensure `display-buffer' puts it in another window.
852 same-window-buffer-names
853 same-window-regexps)
854 (setq window (display-buffer (marker-buffer pos)))
855 ;; This is the way to set point in the proper window.
856 (save-selected-window
857 (select-window window)
858 (goto-char pos))))
860 (defun occur-find-match (n search message)
861 (if (not n) (setq n 1))
862 (let ((r))
863 (while (> n 0)
864 (setq r (funcall search (point) 'occur-match))
865 (and r
866 (get-text-property r 'occur-match)
867 (setq r (funcall search r 'occur-match)))
868 (if r
869 (goto-char r)
870 (error message))
871 (setq n (1- n)))))
873 (defun occur-next (&optional n)
874 "Move to the Nth (default 1) next match in an Occur mode buffer."
875 (interactive "p")
876 (occur-find-match n #'next-single-property-change "No more matches"))
878 (defun occur-prev (&optional n)
879 "Move to the Nth (default 1) previous match in an Occur mode buffer."
880 (interactive "p")
881 (occur-find-match n #'previous-single-property-change "No earlier matches"))
883 (defun occur-next-error (&optional argp reset)
884 "Move to the Nth (default 1) next match in an Occur mode buffer.
885 Compatibility function for \\[next-error] invocations."
886 (interactive "p")
887 ;; we need to run occur-find-match from within the Occur buffer
888 (with-current-buffer
889 ;; Choose the buffer and make it current.
890 (if (next-error-buffer-p (current-buffer))
891 (current-buffer)
892 (next-error-find-buffer nil nil
893 (lambda ()
894 (eq major-mode 'occur-mode))))
896 (goto-char (cond (reset (point-min))
897 ((< argp 0) (line-beginning-position))
898 ((> argp 0) (line-end-position))
899 ((point))))
900 (occur-find-match
901 (abs argp)
902 (if (> 0 argp)
903 #'previous-single-property-change
904 #'next-single-property-change)
905 "No more matches")
906 ;; In case the *Occur* buffer is visible in a nonselected window.
907 (let ((win (get-buffer-window (current-buffer) t)))
908 (if win (set-window-point win (point))))
909 (occur-mode-goto-occurrence)))
911 (defface match
912 '((((class color) (min-colors 88) (background light))
913 :background "yellow1")
914 (((class color) (min-colors 88) (background dark))
915 :background "RoyalBlue3")
916 (((class color) (min-colors 8) (background light))
917 :background "yellow" :foreground "black")
918 (((class color) (min-colors 8) (background dark))
919 :background "blue" :foreground "white")
920 (((type tty) (class mono))
921 :inverse-video t)
922 (t :background "gray"))
923 "Face used to highlight matches permanently."
924 :group 'matching
925 :version "22.1")
927 (defcustom list-matching-lines-default-context-lines 0
928 "*Default number of context lines included around `list-matching-lines' matches.
929 A negative number means to include that many lines before the match.
930 A positive number means to include that many lines both before and after."
931 :type 'integer
932 :group 'matching)
934 (defalias 'list-matching-lines 'occur)
936 (defcustom list-matching-lines-face 'match
937 "*Face used by \\[list-matching-lines] to show the text that matches.
938 If the value is nil, don't highlight the matching portions specially."
939 :type 'face
940 :group 'matching)
942 (defcustom list-matching-lines-buffer-name-face 'underline
943 "*Face used by \\[list-matching-lines] to show the names of buffers.
944 If the value is nil, don't highlight the buffer names specially."
945 :type 'face
946 :group 'matching)
948 (defcustom occur-excluded-properties
949 '(read-only invisible intangible field mouse-face help-echo local-map keymap
950 yank-handler follow-link)
951 "*Text properties to discard when copying lines to the *Occur* buffer.
952 The value should be a list of text properties to discard or t,
953 which means to discard all text properties."
954 :type '(choice (const :tag "All" t) (repeat symbol))
955 :group 'matching
956 :version "22.1")
958 (defun occur-accumulate-lines (count &optional keep-props)
959 (save-excursion
960 (let ((forwardp (> count 0))
961 result beg end)
962 (while (not (or (zerop count)
963 (if forwardp
964 (eobp)
965 (bobp))))
966 (setq count (+ count (if forwardp -1 1)))
967 (setq beg (line-beginning-position)
968 end (line-end-position))
969 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
970 (text-property-not-all beg end 'fontified t))
971 (if (fboundp 'jit-lock-fontify-now)
972 (jit-lock-fontify-now beg end)))
973 (push
974 (if (and keep-props (not (eq occur-excluded-properties t)))
975 (let ((str (buffer-substring beg end)))
976 (remove-list-of-text-properties
977 0 (length str) occur-excluded-properties str)
978 str)
979 (buffer-substring-no-properties beg end))
980 result)
981 (forward-line (if forwardp 1 -1)))
982 (nreverse result))))
984 (defun occur-read-primary-args ()
985 (let* ((default
986 (list (and transient-mark-mode mark-active
987 (regexp-quote
988 (buffer-substring-no-properties
989 (region-beginning) (region-end))))
990 (regexp-quote
991 (or (funcall
992 (or find-tag-default-function
993 (get major-mode 'find-tag-default-function)
994 'find-tag-default))
995 ""))
996 (car regexp-search-ring)
997 (regexp-quote (or (car search-ring) ""))
998 (car (symbol-value
999 query-replace-from-history-variable))))
1000 (default (delete-dups (delq nil (delete "" default))))
1001 (input
1002 (read-from-minibuffer
1003 "List lines matching regexp: "
1004 nil nil nil 'regexp-history default)))
1005 (list input
1006 (when current-prefix-arg
1007 (prefix-numeric-value current-prefix-arg)))))
1009 (defun occur-rename-buffer (&optional unique-p interactive-p)
1010 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1011 Here `original-buffer-name' is the buffer name were Occur was originally run.
1012 When given the prefix argument, or called non-interactively, the renaming
1013 will not clobber the existing buffer(s) of that name, but use
1014 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1015 if you always want a separate *Occur* buffer for each buffer where you
1016 invoke `occur'."
1017 (interactive "P\np")
1018 (with-current-buffer
1019 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1020 (rename-buffer (concat "*Occur: "
1021 (mapconcat #'buffer-name
1022 (car (cddr occur-revert-arguments)) "/")
1023 "*")
1024 (or unique-p (not interactive-p)))))
1026 (defun occur (regexp &optional nlines)
1027 "Show all lines in the current buffer containing a match for REGEXP.
1028 This function can not handle matches that span more than one line.
1030 Each line is displayed with NLINES lines before and after, or -NLINES
1031 before if NLINES is negative.
1032 NLINES defaults to `list-matching-lines-default-context-lines'.
1033 Interactively it is the prefix arg.
1035 The lines are shown in a buffer named `*Occur*'.
1036 It serves as a menu to find any of the occurrences in this buffer.
1037 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1039 If REGEXP contains upper case characters (excluding those preceded by `\\')
1040 and `search-upper-case' is non-nil, the matching is case-sensitive."
1041 (interactive (occur-read-primary-args))
1042 (occur-1 regexp nlines (list (current-buffer))))
1044 (defun multi-occur (bufs regexp &optional nlines)
1045 "Show all lines in buffers BUFS containing a match for REGEXP.
1046 This function acts on multiple buffers; otherwise, it is exactly like
1047 `occur'. When you invoke this command interactively, you must specify
1048 the buffer names that you want, one by one."
1049 (interactive
1050 (cons
1051 (let* ((bufs (list (read-buffer "First buffer to search: "
1052 (current-buffer) t)))
1053 (buf nil)
1054 (ido-ignore-item-temp-list bufs))
1055 (while (not (string-equal
1056 (setq buf (read-buffer
1057 (if (eq read-buffer-function 'ido-read-buffer)
1058 "Next buffer to search (C-j to end): "
1059 "Next buffer to search (RET to end): ")
1060 nil t))
1061 ""))
1062 (add-to-list 'bufs buf)
1063 (setq ido-ignore-item-temp-list bufs))
1064 (nreverse (mapcar #'get-buffer bufs)))
1065 (occur-read-primary-args)))
1066 (occur-1 regexp nlines bufs))
1068 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1069 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1070 Normally BUFREGEXP matches against each buffer's visited file name,
1071 but if you specify a prefix argument, it matches against the buffer name.
1072 See also `multi-occur'."
1073 (interactive
1074 (cons
1075 (let* ((default (car regexp-history))
1076 (input
1077 (read-from-minibuffer
1078 (if current-prefix-arg
1079 "List lines in buffers whose names match regexp: "
1080 "List lines in buffers whose filenames match regexp: ")
1084 'regexp-history)))
1085 (if (equal input "")
1086 default
1087 input))
1088 (occur-read-primary-args)))
1089 (when bufregexp
1090 (occur-1 regexp nil
1091 (delq nil
1092 (mapcar (lambda (buf)
1093 (when (if allbufs
1094 (string-match bufregexp
1095 (buffer-name buf))
1096 (and (buffer-file-name buf)
1097 (string-match bufregexp
1098 (buffer-file-name buf))))
1099 buf))
1100 (buffer-list))))))
1102 (defun occur-1 (regexp nlines bufs &optional buf-name)
1103 (unless buf-name
1104 (setq buf-name "*Occur*"))
1105 (let (occur-buf
1106 (active-bufs (delq nil (mapcar #'(lambda (buf)
1107 (when (buffer-live-p buf) buf))
1108 bufs))))
1109 ;; Handle the case where one of the buffers we're searching is the
1110 ;; output buffer. Just rename it.
1111 (when (member buf-name (mapcar 'buffer-name active-bufs))
1112 (with-current-buffer (get-buffer buf-name)
1113 (rename-uniquely)))
1115 ;; Now find or create the output buffer.
1116 ;; If we just renamed that buffer, we will make a new one here.
1117 (setq occur-buf (get-buffer-create buf-name))
1119 (with-current-buffer occur-buf
1120 (occur-mode)
1121 (let ((inhibit-read-only t)
1122 ;; Don't generate undo entries for creation of the initial contents.
1123 (buffer-undo-list t))
1124 (erase-buffer)
1125 (let ((count (occur-engine
1126 regexp active-bufs occur-buf
1127 (or nlines list-matching-lines-default-context-lines)
1128 (if (and case-fold-search search-upper-case)
1129 (isearch-no-upper-case-p regexp t)
1130 case-fold-search)
1131 list-matching-lines-buffer-name-face
1132 nil list-matching-lines-face
1133 (not (eq occur-excluded-properties t)))))
1134 (let* ((bufcount (length active-bufs))
1135 (diff (- (length bufs) bufcount)))
1136 (message "Searched %d buffer%s%s; %s match%s for `%s'"
1137 bufcount (if (= bufcount 1) "" "s")
1138 (if (zerop diff) "" (format " (%d killed)" diff))
1139 (if (zerop count) "no" (format "%d" count))
1140 (if (= count 1) "" "es")
1141 regexp))
1142 (setq occur-revert-arguments (list regexp nlines bufs))
1143 (if (= count 0)
1144 (kill-buffer occur-buf)
1145 (display-buffer occur-buf)
1146 (setq next-error-last-buffer occur-buf)
1147 (setq buffer-read-only t)
1148 (set-buffer-modified-p nil)
1149 (run-hooks 'occur-hook)))))))
1151 (defun occur-engine-add-prefix (lines)
1152 (mapcar
1153 #'(lambda (line)
1154 (concat " :" line "\n"))
1155 lines))
1157 (defun occur-engine (regexp buffers out-buf nlines case-fold-search
1158 title-face prefix-face match-face keep-props)
1159 (with-current-buffer out-buf
1160 (let ((globalcount 0)
1161 (coding nil))
1162 ;; Map over all the buffers
1163 (dolist (buf buffers)
1164 (when (buffer-live-p buf)
1165 (let ((matches 0) ;; count of matched lines
1166 (lines 1) ;; line count
1167 (matchbeg 0)
1168 (origpt nil)
1169 (begpt nil)
1170 (endpt nil)
1171 (marker nil)
1172 (curstring "")
1173 (inhibit-field-text-motion t)
1174 (headerpt (with-current-buffer out-buf (point))))
1175 (with-current-buffer buf
1176 (or coding
1177 ;; Set CODING only if the current buffer locally
1178 ;; binds buffer-file-coding-system.
1179 (not (local-variable-p 'buffer-file-coding-system))
1180 (setq coding buffer-file-coding-system))
1181 (save-excursion
1182 (goto-char (point-min)) ;; begin searching in the buffer
1183 (while (not (eobp))
1184 (setq origpt (point))
1185 (when (setq endpt (re-search-forward regexp nil t))
1186 (setq matches (1+ matches)) ;; increment match count
1187 (setq matchbeg (match-beginning 0))
1188 (setq lines (+ lines (1- (count-lines origpt endpt))))
1189 (save-excursion
1190 (goto-char matchbeg)
1191 (setq begpt (line-beginning-position)
1192 endpt (line-end-position)))
1193 (setq marker (make-marker))
1194 (set-marker marker matchbeg)
1195 (if (and keep-props
1196 (if (boundp 'jit-lock-mode) jit-lock-mode)
1197 (text-property-not-all begpt endpt 'fontified t))
1198 (if (fboundp 'jit-lock-fontify-now)
1199 (jit-lock-fontify-now begpt endpt)))
1200 (if (and keep-props (not (eq occur-excluded-properties t)))
1201 (progn
1202 (setq curstring (buffer-substring begpt endpt))
1203 (remove-list-of-text-properties
1204 0 (length curstring) occur-excluded-properties curstring))
1205 (setq curstring (buffer-substring-no-properties begpt endpt)))
1206 ;; Highlight the matches
1207 (let ((len (length curstring))
1208 (start 0))
1209 (while (and (< start len)
1210 (string-match regexp curstring start))
1211 (add-text-properties
1212 (match-beginning 0) (match-end 0)
1213 (append
1214 `(occur-match t)
1215 (when match-face
1216 ;; Use `face' rather than `font-lock-face' here
1217 ;; so as to override faces copied from the buffer.
1218 `(face ,match-face)))
1219 curstring)
1220 (setq start (match-end 0))))
1221 ;; Generate the string to insert for this match
1222 (let* ((out-line
1223 (concat
1224 ;; Using 7 digits aligns tabs properly.
1225 (apply #'propertize (format "%7d:" lines)
1226 (append
1227 (when prefix-face
1228 `(font-lock-face prefix-face))
1229 `(occur-prefix t mouse-face (highlight)
1230 occur-target ,marker follow-link t
1231 help-echo "mouse-2: go to this occurrence")))
1232 ;; We don't put `mouse-face' on the newline,
1233 ;; because that loses. And don't put it
1234 ;; on context lines to reduce flicker.
1235 (propertize curstring 'mouse-face (list 'highlight)
1236 'occur-target marker
1237 'follow-link t
1238 'help-echo
1239 "mouse-2: go to this occurrence")
1240 ;; Add marker at eol, but no mouse props.
1241 (propertize "\n" 'occur-target marker)))
1242 (data
1243 (if (= nlines 0)
1244 ;; The simple display style
1245 out-line
1246 ;; The complex multi-line display
1247 ;; style. Generate a list of lines,
1248 ;; concatenate them all together.
1249 (apply #'concat
1250 (nconc
1251 (occur-engine-add-prefix (nreverse (cdr (occur-accumulate-lines (- (1+ (abs nlines))) keep-props))))
1252 (list out-line)
1253 (if (> nlines 0)
1254 (occur-engine-add-prefix
1255 (cdr (occur-accumulate-lines (1+ nlines) keep-props)))))))))
1256 ;; Actually insert the match display data
1257 (with-current-buffer out-buf
1258 (let ((beg (point))
1259 (end (progn (insert data) (point))))
1260 (unless (= nlines 0)
1261 (insert "-------\n")))))
1262 (goto-char endpt))
1263 (if endpt
1264 (progn
1265 (setq lines (1+ lines))
1266 ;; On to the next match...
1267 (forward-line 1))
1268 (goto-char (point-max))))))
1269 (when (not (zerop matches)) ;; is the count zero?
1270 (setq globalcount (+ globalcount matches))
1271 (with-current-buffer out-buf
1272 (goto-char headerpt)
1273 (let ((beg (point))
1274 end)
1275 (insert (format "%d match%s for \"%s\" in buffer: %s\n"
1276 matches (if (= matches 1) "" "es")
1277 regexp (buffer-name buf)))
1278 (setq end (point))
1279 (add-text-properties beg end
1280 (append
1281 (when title-face
1282 `(font-lock-face ,title-face))
1283 `(occur-title ,buf))))
1284 (goto-char (point-min)))))))
1285 (if coding
1286 ;; CODING is buffer-file-coding-system of the first buffer
1287 ;; that locally binds it. Let's use it also for the output
1288 ;; buffer.
1289 (set-buffer-file-coding-system coding))
1290 ;; Return the number of matches
1291 globalcount)))
1294 ;; It would be nice to use \\[...], but there is no reasonable way
1295 ;; to make that display both SPC and Y.
1296 (defconst query-replace-help
1297 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1298 RET or `q' to exit, Period to replace one match and exit,
1299 Comma to replace but not move point immediately,
1300 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1301 C-w to delete match and recursive edit,
1302 C-l to clear the screen, redisplay, and offer same replacement again,
1303 ! to replace all remaining matches with no more questions,
1304 ^ to move point back to previous match,
1305 E to edit the replacement string"
1306 "Help message while in `query-replace'.")
1308 (defvar query-replace-map
1309 (let ((map (make-sparse-keymap)))
1310 (define-key map " " 'act)
1311 (define-key map "\d" 'skip)
1312 (define-key map [delete] 'skip)
1313 (define-key map [backspace] 'skip)
1314 (define-key map "y" 'act)
1315 (define-key map "n" 'skip)
1316 (define-key map "Y" 'act)
1317 (define-key map "N" 'skip)
1318 (define-key map "e" 'edit-replacement)
1319 (define-key map "E" 'edit-replacement)
1320 (define-key map "," 'act-and-show)
1321 (define-key map "q" 'exit)
1322 (define-key map "\r" 'exit)
1323 (define-key map [return] 'exit)
1324 (define-key map "." 'act-and-exit)
1325 (define-key map "\C-r" 'edit)
1326 (define-key map "\C-w" 'delete-and-edit)
1327 (define-key map "\C-l" 'recenter)
1328 (define-key map "!" 'automatic)
1329 (define-key map "^" 'backup)
1330 (define-key map "\C-h" 'help)
1331 (define-key map [f1] 'help)
1332 (define-key map [help] 'help)
1333 (define-key map "?" 'help)
1334 (define-key map "\C-g" 'quit)
1335 (define-key map "\C-]" 'quit)
1336 (define-key map "\e" 'exit-prefix)
1337 (define-key map [escape] 'exit-prefix)
1338 map)
1339 "Keymap that defines the responses to questions in `query-replace'.
1340 The \"bindings\" in this map are not commands; they are answers.
1341 The valid answers include `act', `skip', `act-and-show',
1342 `exit', `act-and-exit', `edit', `delete-and-edit', `recenter',
1343 `automatic', `backup', `exit-prefix', and `help'.")
1345 (defun replace-match-string-symbols (n)
1346 "Process a list (and any sub-lists), expanding certain symbols.
1347 Symbol Expands To
1348 N (match-string N) (where N is a string of digits)
1349 #N (string-to-number (match-string N))
1350 & (match-string 0)
1351 #& (string-to-number (match-string 0))
1352 # replace-count
1354 Note that these symbols must be preceeded by a backslash in order to
1355 type them using Lisp syntax."
1356 (while (consp n)
1357 (cond
1358 ((consp (car n))
1359 (replace-match-string-symbols (car n))) ;Process sub-list
1360 ((symbolp (car n))
1361 (let ((name (symbol-name (car n))))
1362 (cond
1363 ((string-match "^[0-9]+$" name)
1364 (setcar n (list 'match-string (string-to-number name))))
1365 ((string-match "^#[0-9]+$" name)
1366 (setcar n (list 'string-to-number
1367 (list 'match-string
1368 (string-to-number (substring name 1))))))
1369 ((string= "&" name)
1370 (setcar n '(match-string 0)))
1371 ((string= "#&" name)
1372 (setcar n '(string-to-number (match-string 0))))
1373 ((string= "#" name)
1374 (setcar n 'replace-count))))))
1375 (setq n (cdr n))))
1377 (defun replace-eval-replacement (expression replace-count)
1378 (let ((replacement (eval expression)))
1379 (if (stringp replacement)
1380 replacement
1381 (prin1-to-string replacement t))))
1383 (defun replace-quote (replacement)
1384 "Quote a replacement string.
1385 This just doubles all backslashes in REPLACEMENT and
1386 returns the resulting string. If REPLACEMENT is not
1387 a string, it is first passed through `prin1-to-string'
1388 with the `noescape' argument set.
1390 `match-data' is preserved across the call."
1391 (save-match-data
1392 (replace-regexp-in-string "\\\\" "\\\\"
1393 (if (stringp replacement)
1394 replacement
1395 (prin1-to-string replacement t))
1396 t t)))
1398 (defun replace-loop-through-replacements (data replace-count)
1399 ;; DATA is a vector contaning the following values:
1400 ;; 0 next-rotate-count
1401 ;; 1 repeat-count
1402 ;; 2 next-replacement
1403 ;; 3 replacements
1404 (if (= (aref data 0) replace-count)
1405 (progn
1406 (aset data 0 (+ replace-count (aref data 1)))
1407 (let ((next (cdr (aref data 2))))
1408 (aset data 2 (if (consp next) next (aref data 3))))))
1409 (car (aref data 2)))
1411 (defun replace-match-data (integers reuse &optional new)
1412 "Like `match-data', but markers in REUSE get invalidated.
1413 If NEW is non-nil, it is set and returned instead of fresh data,
1414 but coerced to the correct value of INTEGERS."
1415 (or (and new
1416 (progn
1417 (set-match-data new)
1418 (and (eq new reuse)
1419 (eq (null integers) (markerp (car reuse)))
1420 new)))
1421 (match-data integers reuse t)))
1423 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1424 "Make a replacement with `replace-match', editing `\\?'.
1425 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1426 check for `\\?' is made to save time. MATCH-DATA is used for the
1427 replacement. In case editing is done, it is changed to use markers.
1429 The return value is non-nil if there has been no `\\?' or NOEDIT was
1430 passed in. If LITERAL is set, no checking is done, anyway."
1431 (unless (or literal noedit)
1432 (setq noedit t)
1433 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1434 newtext)
1435 (setq newtext
1436 (read-string "Edit replacement string: "
1437 (prog1
1438 (cons
1439 (replace-match "" t t newtext 3)
1440 (1+ (match-beginning 3)))
1441 (setq match-data
1442 (replace-match-data
1443 nil match-data match-data))))
1444 noedit nil)))
1445 (set-match-data match-data)
1446 (replace-match newtext fixedcase literal)
1447 noedit)
1449 (defun perform-replace (from-string replacements
1450 query-flag regexp-flag delimited-flag
1451 &optional repeat-count map start end)
1452 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1453 Don't use this in your own program unless you want to query and set the mark
1454 just as `query-replace' does. Instead, write a simple loop like this:
1456 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1457 (replace-match \"foobar\" nil nil))
1459 which will run faster and probably do exactly what you want. Please
1460 see the documentation of `replace-match' to find out how to simulate
1461 `case-replace'.
1463 This function returns nil if and only if there were no matches to
1464 make, or the user didn't cancel the call."
1465 (or map (setq map query-replace-map))
1466 (and query-flag minibuffer-auto-raise
1467 (raise-frame (window-frame (minibuffer-window))))
1468 (let* ((case-fold-search
1469 (if (and case-fold-search search-upper-case)
1470 (isearch-no-upper-case-p from-string regexp-flag)
1471 case-fold-search))
1472 (nocasify (not (and case-replace case-fold-search)))
1473 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1474 (search-function (if regexp-flag 're-search-forward 'search-forward))
1475 (search-string from-string)
1476 (real-match-data nil) ; The match data for the current match.
1477 (next-replacement nil)
1478 ;; This is non-nil if we know there is nothing for the user
1479 ;; to edit in the replacement.
1480 (noedit nil)
1481 (keep-going t)
1482 (stack nil)
1483 (replace-count 0)
1484 (nonempty-match nil)
1486 ;; If non-nil, it is marker saying where in the buffer to stop.
1487 (limit nil)
1489 ;; Data for the next match. If a cons, it has the same format as
1490 ;; (match-data); otherwise it is t if a match is possible at point.
1491 (match-again t)
1493 (message
1494 (if query-flag
1495 (apply 'propertize
1496 (substitute-command-keys
1497 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1498 minibuffer-prompt-properties))))
1500 ;; If region is active, in Transient Mark mode, operate on region.
1501 (when start
1502 (setq limit (copy-marker (max start end)))
1503 (goto-char (min start end))
1504 (deactivate-mark))
1506 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1507 ;; containing a function and its first argument. The function is
1508 ;; called to generate each replacement like this:
1509 ;; (funcall (car replacements) (cdr replacements) replace-count)
1510 ;; It must return a string.
1511 (cond
1512 ((stringp replacements)
1513 (setq next-replacement replacements
1514 replacements nil))
1515 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1516 (or repeat-count (setq repeat-count 1))
1517 (setq replacements (cons 'replace-loop-through-replacements
1518 (vector repeat-count repeat-count
1519 replacements replacements)))))
1521 (if delimited-flag
1522 (setq search-function 're-search-forward
1523 search-string (concat "\\b"
1524 (if regexp-flag from-string
1525 (regexp-quote from-string))
1526 "\\b")))
1527 (when query-replace-lazy-highlight
1528 (setq isearch-lazy-highlight-last-string nil))
1530 (push-mark)
1531 (undo-boundary)
1532 (unwind-protect
1533 ;; Loop finding occurrences that perhaps should be replaced.
1534 (while (and keep-going
1535 (not (or (eobp) (and limit (>= (point) limit))))
1536 ;; Use the next match if it is already known;
1537 ;; otherwise, search for a match after moving forward
1538 ;; one char if progress is required.
1539 (setq real-match-data
1540 (cond ((consp match-again)
1541 (goto-char (nth 1 match-again))
1542 (replace-match-data
1543 t real-match-data match-again))
1544 ;; MATCH-AGAIN non-nil means accept an
1545 ;; adjacent match.
1546 (match-again
1547 (and
1548 (funcall search-function search-string
1549 limit t)
1550 ;; For speed, use only integers and
1551 ;; reuse the list used last time.
1552 (replace-match-data t real-match-data)))
1553 ((and (< (1+ (point)) (point-max))
1554 (or (null limit)
1555 (< (1+ (point)) limit)))
1556 ;; If not accepting adjacent matches,
1557 ;; move one char to the right before
1558 ;; searching again. Undo the motion
1559 ;; if the search fails.
1560 (let ((opoint (point)))
1561 (forward-char 1)
1562 (if (funcall
1563 search-function search-string
1564 limit t)
1565 (replace-match-data
1566 t real-match-data)
1567 (goto-char opoint)
1568 nil))))))
1570 ;; Record whether the match is nonempty, to avoid an infinite loop
1571 ;; repeatedly matching the same empty string.
1572 (setq nonempty-match
1573 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1575 ;; If the match is empty, record that the next one can't be
1576 ;; adjacent.
1578 ;; Otherwise, if matching a regular expression, do the next
1579 ;; match now, since the replacement for this match may
1580 ;; affect whether the next match is adjacent to this one.
1581 ;; If that match is empty, don't use it.
1582 (setq match-again
1583 (and nonempty-match
1584 (or (not regexp-flag)
1585 (and (looking-at search-string)
1586 (let ((match (match-data)))
1587 (and (/= (nth 0 match) (nth 1 match))
1588 match))))))
1590 ;; Optionally ignore matches that have a read-only property.
1591 (unless (and query-replace-skip-read-only
1592 (text-property-not-all
1593 (nth 0 real-match-data) (nth 1 real-match-data)
1594 'read-only nil))
1596 ;; Calculate the replacement string, if necessary.
1597 (when replacements
1598 (set-match-data real-match-data)
1599 (setq next-replacement
1600 (funcall (car replacements) (cdr replacements)
1601 replace-count)))
1602 (if (not query-flag)
1603 (let ((inhibit-read-only
1604 query-replace-skip-read-only))
1605 (unless (or literal noedit)
1606 (replace-highlight
1607 (nth 0 real-match-data) (nth 1 real-match-data)
1608 start end search-string
1609 (or delimited-flag regexp-flag) case-fold-search))
1610 (setq noedit
1611 (replace-match-maybe-edit
1612 next-replacement nocasify literal
1613 noedit real-match-data)
1614 replace-count (1+ replace-count)))
1615 (undo-boundary)
1616 (let (done replaced key def)
1617 ;; Loop reading commands until one of them sets done,
1618 ;; which means it has finished handling this
1619 ;; occurrence. Any command that sets `done' should
1620 ;; leave behind proper match data for the stack.
1621 ;; Commands not setting `done' need to adjust
1622 ;; `real-match-data'.
1623 (while (not done)
1624 (set-match-data real-match-data)
1625 (replace-highlight
1626 (match-beginning 0) (match-end 0)
1627 start end search-string
1628 (or delimited-flag regexp-flag) case-fold-search)
1629 ;; Bind message-log-max so we don't fill up the message log
1630 ;; with a bunch of identical messages.
1631 (let ((message-log-max nil)
1632 (replacement-presentation
1633 (if query-replace-show-replacement
1634 (save-match-data
1635 (set-match-data real-match-data)
1636 (match-substitute-replacement next-replacement
1637 nocasify literal))
1638 next-replacement)))
1639 (message message
1640 (query-replace-descr from-string)
1641 (query-replace-descr replacement-presentation)))
1642 (setq key (read-event))
1643 ;; Necessary in case something happens during read-event
1644 ;; that clobbers the match data.
1645 (set-match-data real-match-data)
1646 (setq key (vector key))
1647 (setq def (lookup-key map key))
1648 ;; Restore the match data while we process the command.
1649 (cond ((eq def 'help)
1650 (with-output-to-temp-buffer "*Help*"
1651 (princ
1652 (concat "Query replacing "
1653 (if regexp-flag "regexp " "")
1654 from-string " with "
1655 next-replacement ".\n\n"
1656 (substitute-command-keys
1657 query-replace-help)))
1658 (with-current-buffer standard-output
1659 (help-mode))))
1660 ((eq def 'exit)
1661 (setq keep-going nil)
1662 (setq done t))
1663 ((eq def 'backup)
1664 (if stack
1665 (let ((elt (pop stack)))
1666 (goto-char (nth 0 elt))
1667 (setq replaced (nth 1 elt)
1668 real-match-data
1669 (replace-match-data
1670 t real-match-data
1671 (nth 2 elt))))
1672 (message "No previous match")
1673 (ding 'no-terminate)
1674 (sit-for 1)))
1675 ((eq def 'act)
1676 (or replaced
1677 (setq noedit
1678 (replace-match-maybe-edit
1679 next-replacement nocasify literal
1680 noedit real-match-data)
1681 replace-count (1+ replace-count)))
1682 (setq done t replaced t))
1683 ((eq def 'act-and-exit)
1684 (or replaced
1685 (setq noedit
1686 (replace-match-maybe-edit
1687 next-replacement nocasify literal
1688 noedit real-match-data)
1689 replace-count (1+ replace-count)))
1690 (setq keep-going nil)
1691 (setq done t replaced t))
1692 ((eq def 'act-and-show)
1693 (if (not replaced)
1694 (setq noedit
1695 (replace-match-maybe-edit
1696 next-replacement nocasify literal
1697 noedit real-match-data)
1698 replace-count (1+ replace-count)
1699 real-match-data (replace-match-data
1700 t real-match-data)
1701 replaced t)))
1702 ((eq def 'automatic)
1703 (or replaced
1704 (setq noedit
1705 (replace-match-maybe-edit
1706 next-replacement nocasify literal
1707 noedit real-match-data)
1708 replace-count (1+ replace-count)))
1709 (setq done t query-flag nil replaced t))
1710 ((eq def 'skip)
1711 (setq done t))
1712 ((eq def 'recenter)
1713 (recenter nil))
1714 ((eq def 'edit)
1715 (let ((opos (point-marker)))
1716 (setq real-match-data (replace-match-data
1717 nil real-match-data
1718 real-match-data))
1719 (goto-char (match-beginning 0))
1720 (save-excursion
1721 (save-window-excursion
1722 (recursive-edit)))
1723 (goto-char opos)
1724 (set-marker opos nil))
1725 ;; Before we make the replacement,
1726 ;; decide whether the search string
1727 ;; can match again just after this match.
1728 (if (and regexp-flag nonempty-match)
1729 (setq match-again (and (looking-at search-string)
1730 (match-data)))))
1731 ;; Edit replacement.
1732 ((eq def 'edit-replacement)
1733 (setq real-match-data (replace-match-data
1734 nil real-match-data
1735 real-match-data)
1736 next-replacement
1737 (read-string "Edit replacement string: "
1738 next-replacement)
1739 noedit nil)
1740 (if replaced
1741 (set-match-data real-match-data)
1742 (setq noedit
1743 (replace-match-maybe-edit
1744 next-replacement nocasify literal noedit
1745 real-match-data)
1746 replaced t))
1747 (setq done t))
1749 ((eq def 'delete-and-edit)
1750 (replace-match "" t t)
1751 (setq real-match-data (replace-match-data
1752 nil real-match-data))
1753 (replace-dehighlight)
1754 (save-excursion (recursive-edit))
1755 (setq replaced t))
1756 ;; Note: we do not need to treat `exit-prefix'
1757 ;; specially here, since we reread
1758 ;; any unrecognized character.
1760 (setq this-command 'mode-exited)
1761 (setq keep-going nil)
1762 (setq unread-command-events
1763 (append (listify-key-sequence key)
1764 unread-command-events))
1765 (setq done t)))
1766 (when query-replace-lazy-highlight
1767 ;; Force lazy rehighlighting only after replacements
1768 (if (not (memq def '(skip backup)))
1769 (setq isearch-lazy-highlight-last-string nil))))
1770 ;; Record previous position for ^ when we move on.
1771 ;; Change markers to numbers in the match data
1772 ;; since lots of markers slow down editing.
1773 (push (list (point) replaced
1774 ;;; If the replacement has already happened, all we need is the
1775 ;;; current match start and end. We could get this with a trivial
1776 ;;; match like
1777 ;;; (save-excursion (goto-char (match-beginning 0))
1778 ;;; (search-forward (match-string 0))
1779 ;;; (match-data t))
1780 ;;; if we really wanted to avoid manually constructing match data.
1781 ;;; Adding current-buffer is necessary so that match-data calls can
1782 ;;; return markers which are appropriate for editing.
1783 (if replaced
1784 (list
1785 (match-beginning 0)
1786 (match-end 0)
1787 (current-buffer))
1788 (match-data t)))
1789 stack)))))
1791 (replace-dehighlight))
1792 (or unread-command-events
1793 (message "Replaced %d occurrence%s"
1794 replace-count
1795 (if (= replace-count 1) "" "s")))
1796 (and keep-going stack)))
1798 (defvar replace-overlay nil)
1800 (defun replace-highlight (match-beg match-end range-beg range-end
1801 string regexp case-fold)
1802 (if query-replace-highlight
1803 (if replace-overlay
1804 (move-overlay replace-overlay match-beg match-end (current-buffer))
1805 (setq replace-overlay (make-overlay match-beg match-end))
1806 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
1807 (overlay-put replace-overlay 'face 'query-replace)))
1808 (if query-replace-lazy-highlight
1809 (let ((isearch-string string)
1810 (isearch-regexp regexp)
1811 (search-whitespace-regexp nil)
1812 (isearch-case-fold-search case-fold))
1813 (isearch-lazy-highlight-new-loop range-beg range-end))))
1815 (defun replace-dehighlight ()
1816 (when replace-overlay
1817 (delete-overlay replace-overlay))
1818 (when query-replace-lazy-highlight
1819 (lazy-highlight-cleanup lazy-highlight-cleanup)
1820 (setq isearch-lazy-highlight-last-string nil)))
1822 ;; arch-tag: 16b4cd61-fd40-497b-b86f-b667c4cf88e4
1823 ;;; replace.el ends here