Update copyright year to 2014 by running admin/update-copyright.
[emacs.git] / lisp / replace.el
blobcce431f024835b69fec54d73d4c61b2cfa20a027
1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2014 Free
4 ;; Software Foundation, Inc.
6 ;; Maintainer: FSF
7 ;; Package: emacs
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;; Commentary:
26 ;; This package supplies the string and regular-expression replace functions
27 ;; documented in the Emacs user's manual.
29 ;;; Code:
31 (defcustom case-replace t
32 "Non-nil means `query-replace' should preserve case in replacements."
33 :type 'boolean
34 :group 'matching)
36 (defcustom replace-lax-whitespace nil
37 "Non-nil means `query-replace' matches a sequence of whitespace chars.
38 When you enter a space or spaces in the strings to be replaced,
39 it will match any sequence matched by the regexp `search-whitespace-regexp'."
40 :type 'boolean
41 :group 'matching
42 :version "24.3")
44 (defcustom replace-regexp-lax-whitespace nil
45 "Non-nil means `query-replace-regexp' matches a sequence of whitespace chars.
46 When you enter a space or spaces in the regexps to be replaced,
47 it will match any sequence matched by the regexp `search-whitespace-regexp'."
48 :type 'boolean
49 :group 'matching
50 :version "24.3")
52 (defvar query-replace-history nil
53 "Default history list for query-replace commands.
54 See `query-replace-from-history-variable' and
55 `query-replace-to-history-variable'.")
57 (defvar query-replace-defaults nil
58 "Default values of FROM-STRING and TO-STRING for `query-replace'.
59 This is a cons cell (FROM-STRING . TO-STRING), or nil if there is
60 no default value.")
62 (defvar query-replace-interactive nil
63 "Non-nil means `query-replace' uses the last search string.
64 That becomes the \"string to replace\".")
65 (make-obsolete-variable 'query-replace-interactive
66 "use `M-n' to pull the last incremental search string
67 to the minibuffer that reads the string to replace, or invoke replacements
68 from Isearch by using a key sequence like `C-s C-s M-%'." "24.3")
70 (defcustom query-replace-from-history-variable 'query-replace-history
71 "History list to use for the FROM argument of `query-replace' commands.
72 The value of this variable should be a symbol; that symbol
73 is used as a variable to hold a history list for the strings
74 or patterns to be replaced."
75 :group 'matching
76 :type 'symbol
77 :version "20.3")
79 (defcustom query-replace-to-history-variable 'query-replace-history
80 "History list to use for the TO argument of `query-replace' commands.
81 The value of this variable should be a symbol; that symbol
82 is used as a variable to hold a history list for replacement
83 strings or patterns."
84 :group 'matching
85 :type 'symbol
86 :version "20.3")
88 (defcustom query-replace-skip-read-only nil
89 "Non-nil means `query-replace' and friends ignore read-only matches."
90 :type 'boolean
91 :group 'matching
92 :version "22.1")
94 (defcustom query-replace-show-replacement t
95 "Non-nil means to show what actual replacement text will be."
96 :type 'boolean
97 :group 'matching
98 :version "23.1")
100 (defcustom query-replace-highlight t
101 "Non-nil means to highlight matches during query replacement."
102 :type 'boolean
103 :group 'matching)
105 (defcustom query-replace-lazy-highlight t
106 "Controls the lazy-highlighting during query replacements.
107 When non-nil, all text in the buffer matching the current match
108 is highlighted lazily using isearch lazy highlighting (see
109 `lazy-highlight-initial-delay' and `lazy-highlight-interval')."
110 :type 'boolean
111 :group 'lazy-highlight
112 :group 'matching
113 :version "22.1")
115 (defface query-replace
116 '((t (:inherit isearch)))
117 "Face for highlighting query replacement matches."
118 :group 'matching
119 :version "22.1")
121 (defvar replace-count 0
122 "Number of replacements done so far.
123 See `replace-regexp' and `query-replace-regexp-eval'.")
125 (defun query-replace-descr (string)
126 (mapconcat 'isearch-text-char-description string ""))
128 (defun query-replace-read-from (prompt regexp-flag)
129 "Query and return the `from' argument of a query-replace operation.
130 The return value can also be a pair (FROM . TO) indicating that the user
131 wants to replace FROM with TO."
132 (if query-replace-interactive
133 (car (if regexp-flag regexp-search-ring search-ring))
134 (let* ((history-add-new-input nil)
135 (prompt
136 (if query-replace-defaults
137 (format "%s (default %s -> %s): " prompt
138 (query-replace-descr (car query-replace-defaults))
139 (query-replace-descr (cdr query-replace-defaults)))
140 (format "%s: " prompt)))
141 (from
142 ;; The save-excursion here is in case the user marks and copies
143 ;; a region in order to specify the minibuffer input.
144 ;; That should not clobber the region for the query-replace itself.
145 (save-excursion
146 (if regexp-flag
147 (read-regexp prompt nil query-replace-from-history-variable)
148 (read-from-minibuffer
149 prompt nil nil nil query-replace-from-history-variable
150 (car (if regexp-flag regexp-search-ring search-ring)) t)))))
151 (if (and (zerop (length from)) query-replace-defaults)
152 (cons (car query-replace-defaults)
153 (query-replace-compile-replacement
154 (cdr query-replace-defaults) regexp-flag))
155 (add-to-history query-replace-from-history-variable from nil t)
156 ;; Warn if user types \n or \t, but don't reject the input.
157 (and regexp-flag
158 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\[nt]\\)" from)
159 (let ((match (match-string 3 from)))
160 (cond
161 ((string= match "\\n")
162 (message "Note: `\\n' here doesn't match a newline; to do that, type C-q C-j instead"))
163 ((string= match "\\t")
164 (message "Note: `\\t' here doesn't match a tab; to do that, just type TAB")))
165 (sit-for 2)))
166 from))))
168 (defun query-replace-compile-replacement (to regexp-flag)
169 "Maybe convert a regexp replacement TO to Lisp.
170 Returns a list suitable for `perform-replace' if necessary,
171 the original string if not."
172 (if (and regexp-flag
173 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to))
174 (let (pos list char)
175 (while
176 (progn
177 (setq pos (match-end 0))
178 (push (substring to 0 (- pos 2)) list)
179 (setq char (aref to (1- pos))
180 to (substring to pos))
181 (cond ((eq char ?\#)
182 (push '(number-to-string replace-count) list))
183 ((eq char ?\,)
184 (setq pos (read-from-string to))
185 (push `(replace-quote ,(car pos)) list)
186 (let ((end
187 ;; Swallow a space after a symbol
188 ;; if there is a space.
189 (if (and (or (symbolp (car pos))
190 ;; Swallow a space after 'foo
191 ;; but not after (quote foo).
192 (and (eq (car-safe (car pos)) 'quote)
193 (not (= ?\( (aref to 0)))))
194 (eq (string-match " " to (cdr pos))
195 (cdr pos)))
196 (1+ (cdr pos))
197 (cdr pos))))
198 (setq to (substring to end)))))
199 (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\\\[,#]" to)))
200 (setq to (nreverse (delete "" (cons to list))))
201 (replace-match-string-symbols to)
202 (cons 'replace-eval-replacement
203 (if (cdr to)
204 (cons 'concat to)
205 (car to))))
206 to))
209 (defun query-replace-read-to (from prompt regexp-flag)
210 "Query and return the `to' argument of a query-replace operation."
211 (query-replace-compile-replacement
212 (save-excursion
213 (let* ((history-add-new-input nil)
214 (to (read-from-minibuffer
215 (format "%s %s with: " prompt (query-replace-descr from))
216 nil nil nil
217 query-replace-to-history-variable from t)))
218 (add-to-history query-replace-to-history-variable to nil t)
219 (setq query-replace-defaults (cons from to))
220 to))
221 regexp-flag))
223 (defun query-replace-read-args (prompt regexp-flag &optional noerror)
224 (unless noerror
225 (barf-if-buffer-read-only))
226 (let* ((from (query-replace-read-from prompt regexp-flag))
227 (to (if (consp from) (prog1 (cdr from) (setq from (car from)))
228 (query-replace-read-to from prompt regexp-flag))))
229 (list from to
230 (and current-prefix-arg (not (eq current-prefix-arg '-)))
231 (and current-prefix-arg (eq current-prefix-arg '-)))))
233 (defun query-replace (from-string to-string &optional delimited start end backward)
234 "Replace some occurrences of FROM-STRING with TO-STRING.
235 As each match is found, the user must type a character saying
236 what to do with it. For directions, type \\[help-command] at that time.
238 In Transient Mark mode, if the mark is active, operate on the contents
239 of the region. Otherwise, operate from point to the end of the buffer.
241 Use \\<minibuffer-local-map>\\[next-history-element] \
242 to pull the last incremental search string to the minibuffer
243 that reads FROM-STRING, or invoke replacements from
244 incremental search with a key sequence like `C-s C-s M-%'
245 to use its current search string as the string to replace.
247 Matching is independent of case if `case-fold-search' is non-nil and
248 FROM-STRING has no uppercase letters. Replacement transfers the case
249 pattern of the old text to the new text, if `case-replace' and
250 `case-fold-search' are non-nil and FROM-STRING has no uppercase
251 letters. (Transferring the case pattern means that if the old text
252 matched is all caps, or capitalized, then its replacement is upcased
253 or capitalized.)
255 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
256 ignore hidden matches if `search-invisible' is nil, and ignore more
257 matches using `isearch-filter-predicate'.
259 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
260 to be replaced will match a sequence of whitespace chars defined by the
261 regexp in `search-whitespace-regexp'.
263 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
264 only matches surrounded by word boundaries. A negative prefix arg means
265 replace backward.
267 Fourth and fifth arg START and END specify the region to operate on.
269 To customize possible responses, change the \"bindings\" in `query-replace-map'."
270 (interactive
271 (let ((common
272 (query-replace-read-args
273 (concat "Query replace"
274 (if current-prefix-arg
275 (if (eq current-prefix-arg '-) " backward" " word")
277 (if (and transient-mark-mode mark-active) " in region" ""))
278 nil)))
279 (list (nth 0 common) (nth 1 common) (nth 2 common)
280 ;; These are done separately here
281 ;; so that command-history will record these expressions
282 ;; rather than the values they had this time.
283 (if (and transient-mark-mode mark-active)
284 (region-beginning))
285 (if (and transient-mark-mode mark-active)
286 (region-end))
287 (nth 3 common))))
288 (perform-replace from-string to-string t nil delimited nil nil start end backward))
290 (define-key esc-map "%" 'query-replace)
292 (defun query-replace-regexp (regexp to-string &optional delimited start end backward)
293 "Replace some things after point matching REGEXP with TO-STRING.
294 As each match is found, the user must type a character saying
295 what to do with it. For directions, type \\[help-command] at that time.
297 In Transient Mark mode, if the mark is active, operate on the contents
298 of the region. Otherwise, operate from point to the end of the buffer.
300 Use \\<minibuffer-local-map>\\[next-history-element] \
301 to pull the last incremental search regexp to the minibuffer
302 that reads REGEXP, or invoke replacements from
303 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
304 to use its current search regexp as the regexp to replace.
306 Matching is independent of case if `case-fold-search' is non-nil and
307 REGEXP has no uppercase letters. Replacement transfers the case
308 pattern of the old text to the new text, if `case-replace' and
309 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
310 \(Transferring the case pattern means that if the old text matched is
311 all caps, or capitalized, then its replacement is upcased or
312 capitalized.)
314 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
315 ignore hidden matches if `search-invisible' is nil, and ignore more
316 matches using `isearch-filter-predicate'.
318 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
319 to be replaced will match a sequence of whitespace chars defined by the
320 regexp in `search-whitespace-regexp'.
322 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
323 only matches surrounded by word boundaries. A negative prefix arg means
324 replace backward.
326 Fourth and fifth arg START and END specify the region to operate on.
328 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
329 and `\\=\\N' (where N is a digit) stands for
330 whatever what matched the Nth `\\(...\\)' in REGEXP.
331 `\\?' lets you edit the replacement text in the minibuffer
332 at the given position for each replacement.
334 In interactive calls, the replacement text can contain `\\,'
335 followed by a Lisp expression. Each
336 replacement evaluates that expression to compute the replacement
337 string. Inside of that expression, `\\&' is a string denoting the
338 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
339 for the whole or a partial match converted to a number with
340 `string-to-number', and `\\#' itself for the number of replacements
341 done so far (starting with zero).
343 If the replacement expression is a symbol, write a space after it
344 to terminate it. One space there, if any, will be discarded.
346 When using those Lisp features interactively in the replacement
347 text, TO-STRING is actually made a list instead of a string.
348 Use \\[repeat-complex-command] after this command for details."
349 (interactive
350 (let ((common
351 (query-replace-read-args
352 (concat "Query replace"
353 (if current-prefix-arg
354 (if (eq current-prefix-arg '-) " backward" " word")
356 " regexp"
357 (if (and transient-mark-mode mark-active) " in region" ""))
358 t)))
359 (list (nth 0 common) (nth 1 common) (nth 2 common)
360 ;; These are done separately here
361 ;; so that command-history will record these expressions
362 ;; rather than the values they had this time.
363 (if (and transient-mark-mode mark-active)
364 (region-beginning))
365 (if (and transient-mark-mode mark-active)
366 (region-end))
367 (nth 3 common))))
368 (perform-replace regexp to-string t t delimited nil nil start end backward))
370 (define-key esc-map [?\C-%] 'query-replace-regexp)
372 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
373 "Replace some things after point matching REGEXP with the result of TO-EXPR.
375 Interactive use of this function is deprecated in favor of the
376 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
377 using `search-forward-regexp' and `replace-match' is preferred.
379 As each match is found, the user must type a character saying
380 what to do with it. For directions, type \\[help-command] at that time.
382 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
383 reference `replace-count' to get the number of replacements already made.
384 If the result of TO-EXPR is not a string, it is converted to one using
385 `prin1-to-string' with the NOESCAPE argument (which see).
387 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
388 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
389 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
390 Use `\\#&' or `\\#N' if you want a number instead of a string.
391 In interactive use, `\\#' in itself stands for `replace-count'.
393 In Transient Mark mode, if the mark is active, operate on the contents
394 of the region. Otherwise, operate from point to the end of the buffer.
396 Use \\<minibuffer-local-map>\\[next-history-element] \
397 to pull the last incremental search regexp to the minibuffer
398 that reads REGEXP.
400 Preserves case in each replacement if `case-replace' and `case-fold-search'
401 are non-nil and REGEXP has no uppercase letters.
403 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
404 ignore hidden matches if `search-invisible' is nil, and ignore more
405 matches using `isearch-filter-predicate'.
407 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
408 to be replaced will match a sequence of whitespace chars defined by the
409 regexp in `search-whitespace-regexp'.
411 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
412 only matches that are surrounded by word boundaries.
413 Fourth and fifth arg START and END specify the region to operate on."
414 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
415 for interactive calls, and `search-forward-regexp'/`replace-match'
416 for Lisp calls." "22.1"))
417 (interactive
418 (progn
419 (barf-if-buffer-read-only)
420 (let* ((from
421 ;; Let-bind the history var to disable the "foo -> bar"
422 ;; default. Maybe we shouldn't disable this default, but
423 ;; for now I'll leave it off. --Stef
424 (let ((query-replace-to-history-variable nil))
425 (query-replace-read-from "Query replace regexp" t)))
426 (to (list (read-from-minibuffer
427 (format "Query replace regexp %s with eval: "
428 (query-replace-descr from))
429 nil nil t query-replace-to-history-variable from t))))
430 ;; We make TO a list because replace-match-string-symbols requires one,
431 ;; and the user might enter a single token.
432 (replace-match-string-symbols to)
433 (list from (car to) current-prefix-arg
434 (if (and transient-mark-mode mark-active)
435 (region-beginning))
436 (if (and transient-mark-mode mark-active)
437 (region-end))))))
438 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
439 t 'literal delimited nil nil start end))
441 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
442 "Replace some matches for REGEXP with various strings, in rotation.
443 The second argument TO-STRINGS contains the replacement strings, separated
444 by spaces. This command works like `query-replace-regexp' except that
445 each successive replacement uses the next successive replacement string,
446 wrapping around from the last such string to the first.
448 In Transient Mark mode, if the mark is active, operate on the contents
449 of the region. Otherwise, operate from point to the end of the buffer.
451 Non-interactively, TO-STRINGS may be a list of replacement strings.
453 Use \\<minibuffer-local-map>\\[next-history-element] \
454 to pull the last incremental search regexp to the minibuffer
455 that reads REGEXP.
457 A prefix argument N says to use each replacement string N times
458 before rotating to the next.
459 Fourth and fifth arg START and END specify the region to operate on."
460 (interactive
461 (let* ((from (read-regexp "Map query replace (regexp): " nil
462 query-replace-from-history-variable))
463 (to (read-from-minibuffer
464 (format "Query replace %s with (space-separated strings): "
465 (query-replace-descr from))
466 nil nil nil
467 query-replace-to-history-variable from t)))
468 (list from to
469 (and current-prefix-arg
470 (prefix-numeric-value current-prefix-arg))
471 (if (and transient-mark-mode mark-active)
472 (region-beginning))
473 (if (and transient-mark-mode mark-active)
474 (region-end)))))
475 (let (replacements)
476 (if (listp to-strings)
477 (setq replacements to-strings)
478 (while (/= (length to-strings) 0)
479 (if (string-match " " to-strings)
480 (setq replacements
481 (append replacements
482 (list (substring to-strings 0
483 (string-match " " to-strings))))
484 to-strings (substring to-strings
485 (1+ (string-match " " to-strings))))
486 (setq replacements (append replacements (list to-strings))
487 to-strings ""))))
488 (perform-replace regexp replacements t t nil n nil start end)))
490 (defun replace-string (from-string to-string &optional delimited start end backward)
491 "Replace occurrences of FROM-STRING with TO-STRING.
492 Preserve case in each match if `case-replace' and `case-fold-search'
493 are non-nil and FROM-STRING has no uppercase letters.
494 \(Preserving case means that if the string matched is all caps, or capitalized,
495 then its replacement is upcased or capitalized.)
497 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
498 ignore hidden matches if `search-invisible' is nil, and ignore more
499 matches using `isearch-filter-predicate'.
501 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
502 to be replaced will match a sequence of whitespace chars defined by the
503 regexp in `search-whitespace-regexp'.
505 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
506 only matches surrounded by word boundaries. A negative prefix arg means
507 replace backward.
509 Operates on the region between START and END (if both are nil, from point
510 to the end of the buffer). Interactively, if Transient Mark mode is
511 enabled and the mark is active, operates on the contents of the region;
512 otherwise from point to the end of the buffer.
514 Use \\<minibuffer-local-map>\\[next-history-element] \
515 to pull the last incremental search string to the minibuffer
516 that reads FROM-STRING.
518 This function is usually the wrong thing to use in a Lisp program.
519 What you probably want is a loop like this:
520 (while (search-forward FROM-STRING nil t)
521 (replace-match TO-STRING nil t))
522 which will run faster and will not set the mark or print anything.
523 \(You may need a more complex loop if FROM-STRING can match the null string
524 and TO-STRING is also null.)"
525 (interactive
526 (let ((common
527 (query-replace-read-args
528 (concat "Replace"
529 (if current-prefix-arg
530 (if (eq current-prefix-arg '-) " backward" " word")
532 " string"
533 (if (and transient-mark-mode mark-active) " in region" ""))
534 nil)))
535 (list (nth 0 common) (nth 1 common) (nth 2 common)
536 (if (and transient-mark-mode mark-active)
537 (region-beginning))
538 (if (and transient-mark-mode mark-active)
539 (region-end))
540 (nth 3 common))))
541 (perform-replace from-string to-string nil nil delimited nil nil start end backward))
542 (put 'replace-string 'interactive-only
543 "use `search-forward' and `replace-match' instead.")
545 (defun replace-regexp (regexp to-string &optional delimited start end backward)
546 "Replace things after point matching REGEXP with TO-STRING.
547 Preserve case in each match if `case-replace' and `case-fold-search'
548 are non-nil and REGEXP has no uppercase letters.
550 Ignore read-only matches if `query-replace-skip-read-only' is non-nil,
551 ignore hidden matches if `search-invisible' is nil, and ignore more
552 matches using `isearch-filter-predicate'.
554 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
555 to be replaced will match a sequence of whitespace chars defined by the
556 regexp in `search-whitespace-regexp'.
558 In Transient Mark mode, if the mark is active, operate on the contents
559 of the region. Otherwise, operate from point to the end of the buffer.
561 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
562 only matches surrounded by word boundaries. A negative prefix arg means
563 replace backward.
565 Fourth and fifth arg START and END specify the region to operate on.
567 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
568 and `\\=\\N' (where N is a digit) stands for
569 whatever what matched the Nth `\\(...\\)' in REGEXP.
570 `\\?' lets you edit the replacement text in the minibuffer
571 at the given position for each replacement.
573 In interactive calls, the replacement text may contain `\\,'
574 followed by a Lisp expression used as part of the replacement
575 text. Inside of that expression, `\\&' is a string denoting the
576 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
577 numeric values from `string-to-number', and `\\#' itself for
578 `replace-count', the number of replacements occurred so far.
580 If your Lisp expression is an identifier and the next letter in
581 the replacement string would be interpreted as part of it, you
582 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
583 for this particular case you may also enter `\\#' in the
584 replacement text directly.
586 When using those Lisp features interactively in the replacement
587 text, TO-STRING is actually made a list instead of a string.
588 Use \\[repeat-complex-command] after this command for details.
590 Use \\<minibuffer-local-map>\\[next-history-element] \
591 to pull the last incremental search regexp to the minibuffer
592 that reads REGEXP.
594 This function is usually the wrong thing to use in a Lisp program.
595 What you probably want is a loop like this:
596 (while (re-search-forward REGEXP nil t)
597 (replace-match TO-STRING nil nil))
598 which will run faster and will not set the mark or print anything."
599 (interactive
600 (let ((common
601 (query-replace-read-args
602 (concat "Replace"
603 (if current-prefix-arg
604 (if (eq current-prefix-arg '-) " backward" " word")
606 " regexp"
607 (if (and transient-mark-mode mark-active) " in region" ""))
608 t)))
609 (list (nth 0 common) (nth 1 common) (nth 2 common)
610 (if (and transient-mark-mode mark-active)
611 (region-beginning))
612 (if (and transient-mark-mode mark-active)
613 (region-end))
614 (nth 3 common))))
615 (perform-replace regexp to-string nil t delimited nil nil start end backward))
616 (put 'replace-regexp 'interactive-only
617 "use `re-search-forward' and `replace-match' instead.")
620 (defvar regexp-history nil
621 "History list for some commands that read regular expressions.
623 Maximum length of the history list is determined by the value
624 of `history-length', which see.")
626 (defvar occur-collect-regexp-history '("\\1")
627 "History of regexp for occur's collect operation")
629 (defcustom read-regexp-defaults-function nil
630 "Function that provides default regexp(s) for regexp reading commands.
631 This function should take no arguments and return one of nil, a
632 regexp or a list of regexps. The return value of this function is used
633 as DEFAULTS param of `read-regexp'. This function is called only during
634 interactive use.
636 If you need different defaults for different commands,
637 use `this-command' to identify the command under execution.
639 You can customize `read-regexp-defaults-function' to the value
640 `find-tag-default-as-regexp' to highlight a symbol at point."
641 :type '(choice
642 (const :tag "No default regexp reading function" nil)
643 (const :tag "Latest regexp history" regexp-history-last)
644 (function-item :tag "Tag at point"
645 find-tag-default)
646 (function-item :tag "Tag at point as regexp"
647 find-tag-default-as-regexp)
648 (function-item :tag "Tag at point as symbol regexp"
649 find-tag-default-as-symbol-regexp)
650 (function :tag "Function to provide default for read-regexp"))
651 :group 'matching
652 :version "24.4")
654 (defun read-regexp-suggestions ()
655 "Return a list of standard suggestions for `read-regexp'.
656 By default, the list includes the tag at point, the last isearch regexp,
657 the last isearch string, and the last replacement regexp. `read-regexp'
658 appends the list returned by this function to the end of values available
659 via \\<minibuffer-local-map>\\[next-history-element]."
660 (list
661 (find-tag-default-as-regexp)
662 (find-tag-default-as-symbol-regexp)
663 (car regexp-search-ring)
664 (regexp-quote (or (car search-ring) ""))
665 (car (symbol-value query-replace-from-history-variable))))
667 (defun read-regexp (prompt &optional defaults history)
668 "Read and return a regular expression as a string.
669 When PROMPT doesn't end with a colon and space, it adds a final \": \".
670 If the first element of DEFAULTS is non-nil, it's added to the prompt.
672 Optional arg DEFAULTS has the form (DEFAULT . SUGGESTIONS)
673 or simply DEFAULT where DEFAULT, if non-nil, should be a string that
674 is returned as the default value when the user enters empty input.
675 SUGGESTIONS is a list of strings that can be inserted into
676 the minibuffer using \\<minibuffer-local-map>\\[next-history-element]. \
677 The values supplied in SUGGESTIONS
678 are prepended to the list of standard suggestions returned by
679 `read-regexp-suggestions'. The default values can be customized
680 by `read-regexp-defaults-function'.
682 Optional arg HISTORY is a symbol to use for the history list.
683 If HISTORY is nil, `regexp-history' is used."
684 (let* ((defaults
685 (if (and defaults (symbolp defaults))
686 (cond
687 ((eq (or read-regexp-defaults-function defaults)
688 'regexp-history-last)
689 (car (symbol-value (or history 'regexp-history))))
690 ((functionp (or read-regexp-defaults-function defaults))
691 (funcall (or read-regexp-defaults-function defaults))))
692 defaults))
693 (default (if (consp defaults) (car defaults) defaults))
694 (suggestions (if (listp defaults) defaults (list defaults)))
695 (suggestions (append suggestions (read-regexp-suggestions)))
696 (suggestions (delete-dups (delq nil (delete "" suggestions))))
697 ;; Do not automatically add default to the history for empty input.
698 (history-add-new-input nil)
699 (input (read-from-minibuffer
700 (cond ((string-match-p ":[ \t]*\\'" prompt)
701 prompt)
702 ((and default (> (length default) 0))
703 (format "%s (default %s): " prompt
704 (query-replace-descr default)))
706 (format "%s: " prompt)))
707 nil nil nil (or history 'regexp-history) suggestions t)))
708 (if (equal input "")
709 ;; Return the default value when the user enters empty input.
710 (prog1 (or default input)
711 (when default
712 (add-to-history (or history 'regexp-history) default)))
713 ;; Otherwise, add non-empty input to the history and return input.
714 (prog1 input
715 (add-to-history (or history 'regexp-history) input)))))
718 (defalias 'delete-non-matching-lines 'keep-lines)
719 (defalias 'delete-matching-lines 'flush-lines)
720 (defalias 'count-matches 'how-many)
723 (defun keep-lines-read-args (prompt)
724 "Read arguments for `keep-lines' and friends.
725 Prompt for a regexp with PROMPT.
726 Value is a list, (REGEXP)."
727 (list (read-regexp prompt) nil nil t))
729 (defun keep-lines (regexp &optional rstart rend interactive)
730 "Delete all lines except those containing matches for REGEXP.
731 A match split across lines preserves all the lines it lies in.
732 When called from Lisp (and usually interactively as well, see below)
733 applies to all lines starting after point.
735 If REGEXP contains upper case characters (excluding those preceded by `\\')
736 and `search-upper-case' is non-nil, the matching is case-sensitive.
738 Second and third arg RSTART and REND specify the region to operate on.
739 This command operates on (the accessible part of) all lines whose
740 accessible part is entirely contained in the region determined by RSTART
741 and REND. (A newline ending a line counts as part of that line.)
743 Interactively, in Transient Mark mode when the mark is active, operate
744 on all lines whose accessible part is entirely contained in the region.
745 Otherwise, the command applies to all lines starting after point.
746 When calling this function from Lisp, you can pretend that it was
747 called interactively by passing a non-nil INTERACTIVE argument.
749 This function starts looking for the next match from the end of
750 the previous match. Hence, it ignores matches that overlap
751 a previously found match."
753 (interactive
754 (progn
755 (barf-if-buffer-read-only)
756 (keep-lines-read-args "Keep lines containing match for regexp")))
757 (if rstart
758 (progn
759 (goto-char (min rstart rend))
760 (setq rend
761 (progn
762 (save-excursion
763 (goto-char (max rstart rend))
764 (unless (or (bolp) (eobp))
765 (forward-line 0))
766 (point-marker)))))
767 (if (and interactive transient-mark-mode mark-active)
768 (setq rstart (region-beginning)
769 rend (progn
770 (goto-char (region-end))
771 (unless (or (bolp) (eobp))
772 (forward-line 0))
773 (point-marker)))
774 (setq rstart (point)
775 rend (point-max-marker)))
776 (goto-char rstart))
777 (save-excursion
778 (or (bolp) (forward-line 1))
779 (let ((start (point))
780 (case-fold-search
781 (if (and case-fold-search search-upper-case)
782 (isearch-no-upper-case-p regexp t)
783 case-fold-search)))
784 (while (< (point) rend)
785 ;; Start is first char not preserved by previous match.
786 (if (not (re-search-forward regexp rend 'move))
787 (delete-region start rend)
788 (let ((end (save-excursion (goto-char (match-beginning 0))
789 (forward-line 0)
790 (point))))
791 ;; Now end is first char preserved by the new match.
792 (if (< start end)
793 (delete-region start end))))
795 (setq start (save-excursion (forward-line 1) (point)))
796 ;; If the match was empty, avoid matching again at same place.
797 (and (< (point) rend)
798 (= (match-beginning 0) (match-end 0))
799 (forward-char 1)))))
800 (set-marker rend nil)
801 nil)
804 (defun flush-lines (regexp &optional rstart rend interactive)
805 "Delete lines containing matches for REGEXP.
806 When called from Lisp (and usually when called interactively as
807 well, see below), applies to the part of the buffer after point.
808 The line point is in is deleted if and only if it contains a
809 match for regexp starting after point.
811 If REGEXP contains upper case characters (excluding those preceded by `\\')
812 and `search-upper-case' is non-nil, the matching is case-sensitive.
814 Second and third arg RSTART and REND specify the region to operate on.
815 Lines partially contained in this region are deleted if and only if
816 they contain a match entirely contained in it.
818 Interactively, in Transient Mark mode when the mark is active, operate
819 on the contents of the region. Otherwise, operate from point to the
820 end of (the accessible portion of) the buffer. When calling this function
821 from Lisp, you can pretend that it was called interactively by passing
822 a non-nil INTERACTIVE argument.
824 If a match is split across lines, all the lines it lies in are deleted.
825 They are deleted _before_ looking for the next match. Hence, a match
826 starting on the same line at which another match ended is ignored."
828 (interactive
829 (progn
830 (barf-if-buffer-read-only)
831 (keep-lines-read-args "Flush lines containing match for regexp")))
832 (if rstart
833 (progn
834 (goto-char (min rstart rend))
835 (setq rend (copy-marker (max rstart rend))))
836 (if (and interactive transient-mark-mode mark-active)
837 (setq rstart (region-beginning)
838 rend (copy-marker (region-end)))
839 (setq rstart (point)
840 rend (point-max-marker)))
841 (goto-char rstart))
842 (let ((case-fold-search
843 (if (and case-fold-search search-upper-case)
844 (isearch-no-upper-case-p regexp t)
845 case-fold-search)))
846 (save-excursion
847 (while (and (< (point) rend)
848 (re-search-forward regexp rend t))
849 (delete-region (save-excursion (goto-char (match-beginning 0))
850 (forward-line 0)
851 (point))
852 (progn (forward-line 1) (point))))))
853 (set-marker rend nil)
854 nil)
857 (defun how-many (regexp &optional rstart rend interactive)
858 "Print and return number of matches for REGEXP following point.
859 When called from Lisp and INTERACTIVE is omitted or nil, just return
860 the number, do not print it; if INTERACTIVE is t, the function behaves
861 in all respects as if it had been called interactively.
863 If REGEXP contains upper case characters (excluding those preceded by `\\')
864 and `search-upper-case' is non-nil, the matching is case-sensitive.
866 Second and third arg RSTART and REND specify the region to operate on.
868 Interactively, in Transient Mark mode when the mark is active, operate
869 on the contents of the region. Otherwise, operate from point to the
870 end of (the accessible portion of) the buffer.
872 This function starts looking for the next match from the end of
873 the previous match. Hence, it ignores matches that overlap
874 a previously found match."
876 (interactive
877 (keep-lines-read-args "How many matches for regexp"))
878 (save-excursion
879 (if rstart
880 (if rend
881 (progn
882 (goto-char (min rstart rend))
883 (setq rend (max rstart rend)))
884 (goto-char rstart)
885 (setq rend (point-max)))
886 (if (and interactive transient-mark-mode mark-active)
887 (setq rstart (region-beginning)
888 rend (region-end))
889 (setq rstart (point)
890 rend (point-max)))
891 (goto-char rstart))
892 (let ((count 0)
893 opoint
894 (case-fold-search
895 (if (and case-fold-search search-upper-case)
896 (isearch-no-upper-case-p regexp t)
897 case-fold-search)))
898 (while (and (< (point) rend)
899 (progn (setq opoint (point))
900 (re-search-forward regexp rend t)))
901 (if (= opoint (point))
902 (forward-char 1)
903 (setq count (1+ count))))
904 (when interactive (message "%d occurrence%s"
905 count
906 (if (= count 1) "" "s")))
907 count)))
910 (defvar occur-menu-map
911 (let ((map (make-sparse-keymap)))
912 (bindings--define-key map [next-error-follow-minor-mode]
913 '(menu-item "Auto Occurrence Display"
914 next-error-follow-minor-mode
915 :help "Display another occurrence when moving the cursor"
916 :button (:toggle . (and (boundp 'next-error-follow-minor-mode)
917 next-error-follow-minor-mode))))
918 (bindings--define-key map [separator-1] menu-bar-separator)
919 (bindings--define-key map [kill-this-buffer]
920 '(menu-item "Kill Occur Buffer" kill-this-buffer
921 :help "Kill the current *Occur* buffer"))
922 (bindings--define-key map [quit-window]
923 '(menu-item "Quit Occur Window" quit-window
924 :help "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
925 (bindings--define-key map [revert-buffer]
926 '(menu-item "Revert Occur Buffer" revert-buffer
927 :help "Replace the text in the *Occur* buffer with the results of rerunning occur"))
928 (bindings--define-key map [clone-buffer]
929 '(menu-item "Clone Occur Buffer" clone-buffer
930 :help "Create and return a twin copy of the current *Occur* buffer"))
931 (bindings--define-key map [occur-rename-buffer]
932 '(menu-item "Rename Occur Buffer" occur-rename-buffer
933 :help "Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
934 (bindings--define-key map [occur-edit-buffer]
935 '(menu-item "Edit Occur Buffer" occur-edit-mode
936 :help "Edit the *Occur* buffer and apply changes to the original buffers."))
937 (bindings--define-key map [separator-2] menu-bar-separator)
938 (bindings--define-key map [occur-mode-goto-occurrence-other-window]
939 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
940 :help "Go to the occurrence the current line describes, in another window"))
941 (bindings--define-key map [occur-mode-goto-occurrence]
942 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
943 :help "Go to the occurrence the current line describes"))
944 (bindings--define-key map [occur-mode-display-occurrence]
945 '(menu-item "Display Occurrence" occur-mode-display-occurrence
946 :help "Display in another window the occurrence the current line describes"))
947 (bindings--define-key map [occur-next]
948 '(menu-item "Move to Next Match" occur-next
949 :help "Move to the Nth (default 1) next match in an Occur mode buffer"))
950 (bindings--define-key map [occur-prev]
951 '(menu-item "Move to Previous Match" occur-prev
952 :help "Move to the Nth (default 1) previous match in an Occur mode buffer"))
953 map)
954 "Menu keymap for `occur-mode'.")
956 (defvar occur-mode-map
957 (let ((map (make-sparse-keymap)))
958 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
959 (define-key map [mouse-2] 'occur-mode-mouse-goto)
960 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
961 (define-key map "e" 'occur-edit-mode)
962 (define-key map "\C-m" 'occur-mode-goto-occurrence)
963 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
964 (define-key map "\C-o" 'occur-mode-display-occurrence)
965 (define-key map "\M-n" 'occur-next)
966 (define-key map "\M-p" 'occur-prev)
967 (define-key map "r" 'occur-rename-buffer)
968 (define-key map "c" 'clone-buffer)
969 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
970 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
971 map)
972 "Keymap for `occur-mode'.")
974 (defvar occur-revert-arguments nil
975 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
976 See `occur-revert-function'.")
977 (make-variable-buffer-local 'occur-revert-arguments)
978 (put 'occur-revert-arguments 'permanent-local t)
980 (defcustom occur-mode-hook '(turn-on-font-lock)
981 "Hook run when entering Occur mode."
982 :type 'hook
983 :group 'matching)
985 (defcustom occur-hook nil
986 "Hook run by Occur when there are any matches."
987 :type 'hook
988 :group 'matching)
990 (defcustom occur-mode-find-occurrence-hook nil
991 "Hook run by Occur after locating an occurrence.
992 This will be called with the cursor position at the occurrence. An application
993 for this is to reveal context in an outline-mode when the occurrence is hidden."
994 :type 'hook
995 :group 'matching)
997 (put 'occur-mode 'mode-class 'special)
998 (define-derived-mode occur-mode special-mode "Occur"
999 "Major mode for output from \\[occur].
1000 \\<occur-mode-map>Move point to one of the items in this buffer, then use
1001 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
1002 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
1004 \\{occur-mode-map}"
1005 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
1006 (setq next-error-function 'occur-next-error))
1009 ;;; Occur Edit mode
1011 (defvar occur-edit-mode-map
1012 (let ((map (make-sparse-keymap)))
1013 (set-keymap-parent map text-mode-map)
1014 (define-key map [mouse-2] 'occur-mode-mouse-goto)
1015 (define-key map "\C-c\C-c" 'occur-cease-edit)
1016 (define-key map "\C-o" 'occur-mode-display-occurrence)
1017 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
1018 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
1019 map)
1020 "Keymap for `occur-edit-mode'.")
1022 (define-derived-mode occur-edit-mode occur-mode "Occur-Edit"
1023 "Major mode for editing *Occur* buffers.
1024 In this mode, changes to the *Occur* buffer are also applied to
1025 the originating buffer.
1027 To return to ordinary Occur mode, use \\[occur-cease-edit]."
1028 (setq buffer-read-only nil)
1029 (add-hook 'after-change-functions 'occur-after-change-function nil t)
1030 (message (substitute-command-keys
1031 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
1033 (defun occur-cease-edit ()
1034 "Switch from Occur Edit mode to Occur mode."
1035 (interactive)
1036 (when (derived-mode-p 'occur-edit-mode)
1037 (occur-mode)
1038 (message "Switching to Occur mode.")))
1040 (defun occur-after-change-function (beg end length)
1041 (save-excursion
1042 (goto-char beg)
1043 (let* ((line-beg (line-beginning-position))
1044 (m (get-text-property line-beg 'occur-target))
1045 (buf (marker-buffer m))
1046 col)
1047 (when (and (get-text-property line-beg 'occur-prefix)
1048 (not (get-text-property end 'occur-prefix)))
1049 (when (= length 0)
1050 ;; Apply occur-target property to inserted (e.g. yanked) text.
1051 (put-text-property beg end 'occur-target m)
1052 ;; Did we insert a newline? Occur Edit mode can't create new
1053 ;; Occur entries; just discard everything after the newline.
1054 (save-excursion
1055 (and (search-forward "\n" end t)
1056 (delete-region (1- (point)) end))))
1057 (let* ((line (- (line-number-at-pos)
1058 (line-number-at-pos (window-start))))
1059 (readonly (with-current-buffer buf buffer-read-only))
1060 (win (or (get-buffer-window buf)
1061 (display-buffer buf
1062 '(nil (inhibit-same-window . t)
1063 (inhibit-switch-frame . t)))))
1064 (line-end (line-end-position))
1065 (text (save-excursion
1066 (goto-char (next-single-property-change
1067 line-beg 'occur-prefix nil
1068 line-end))
1069 (setq col (- (point) line-beg))
1070 (buffer-substring-no-properties (point) line-end))))
1071 (with-selected-window win
1072 (goto-char m)
1073 (recenter line)
1074 (if readonly
1075 (message "Buffer `%s' is read only." buf)
1076 (delete-region (line-beginning-position) (line-end-position))
1077 (insert text))
1078 (move-to-column col)))))))
1081 (defun occur-revert-function (_ignore1 _ignore2)
1082 "Handle `revert-buffer' for Occur mode buffers."
1083 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
1085 (defun occur-mode-find-occurrence ()
1086 (let ((pos (get-text-property (point) 'occur-target)))
1087 (unless pos
1088 (error "No occurrence on this line"))
1089 (unless (buffer-live-p (marker-buffer pos))
1090 (error "Buffer for this occurrence was killed"))
1091 pos))
1093 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
1094 (defun occur-mode-goto-occurrence (&optional event)
1095 "Go to the occurrence on the current line."
1096 (interactive (list last-nonmenu-event))
1097 (let ((pos
1098 (if (null event)
1099 ;; Actually `event-end' works correctly with a nil argument as
1100 ;; well, so we could dispense with this test, but let's not
1101 ;; rely on this undocumented behavior.
1102 (occur-mode-find-occurrence)
1103 (with-current-buffer (window-buffer (posn-window (event-end event)))
1104 (save-excursion
1105 (goto-char (posn-point (event-end event)))
1106 (occur-mode-find-occurrence))))))
1107 (pop-to-buffer (marker-buffer pos))
1108 (goto-char pos)
1109 (run-hooks 'occur-mode-find-occurrence-hook)))
1111 (defun occur-mode-goto-occurrence-other-window ()
1112 "Go to the occurrence the current line describes, in another window."
1113 (interactive)
1114 (let ((pos (occur-mode-find-occurrence)))
1115 (switch-to-buffer-other-window (marker-buffer pos))
1116 (goto-char pos)
1117 (run-hooks 'occur-mode-find-occurrence-hook)))
1119 (defun occur-mode-display-occurrence ()
1120 "Display in another window the occurrence the current line describes."
1121 (interactive)
1122 (let ((pos (occur-mode-find-occurrence))
1123 window)
1124 (setq window (display-buffer (marker-buffer pos) t))
1125 ;; This is the way to set point in the proper window.
1126 (save-selected-window
1127 (select-window window)
1128 (goto-char pos)
1129 (run-hooks 'occur-mode-find-occurrence-hook))))
1131 (defun occur-find-match (n search message)
1132 (if (not n) (setq n 1))
1133 (let ((r))
1134 (while (> n 0)
1135 (setq r (funcall search (point) 'occur-match))
1136 (and r
1137 (get-text-property r 'occur-match)
1138 (setq r (funcall search r 'occur-match)))
1139 (if r
1140 (goto-char r)
1141 (error message))
1142 (setq n (1- n)))))
1144 (defun occur-next (&optional n)
1145 "Move to the Nth (default 1) next match in an Occur mode buffer."
1146 (interactive "p")
1147 (occur-find-match n #'next-single-property-change "No more matches"))
1149 (defun occur-prev (&optional n)
1150 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1151 (interactive "p")
1152 (occur-find-match n #'previous-single-property-change "No earlier matches"))
1154 (defun occur-next-error (&optional argp reset)
1155 "Move to the Nth (default 1) next match in an Occur mode buffer.
1156 Compatibility function for \\[next-error] invocations."
1157 (interactive "p")
1158 ;; we need to run occur-find-match from within the Occur buffer
1159 (with-current-buffer
1160 ;; Choose the buffer and make it current.
1161 (if (next-error-buffer-p (current-buffer))
1162 (current-buffer)
1163 (next-error-find-buffer nil nil
1164 (lambda ()
1165 (eq major-mode 'occur-mode))))
1167 (goto-char (cond (reset (point-min))
1168 ((< argp 0) (line-beginning-position))
1169 ((> argp 0) (line-end-position))
1170 ((point))))
1171 (occur-find-match
1172 (abs argp)
1173 (if (> 0 argp)
1174 #'previous-single-property-change
1175 #'next-single-property-change)
1176 "No more matches")
1177 ;; In case the *Occur* buffer is visible in a nonselected window.
1178 (let ((win (get-buffer-window (current-buffer) t)))
1179 (if win (set-window-point win (point))))
1180 (occur-mode-goto-occurrence)))
1182 (defface match
1183 '((((class color) (min-colors 88) (background light))
1184 :background "yellow1")
1185 (((class color) (min-colors 88) (background dark))
1186 :background "RoyalBlue3")
1187 (((class color) (min-colors 8) (background light))
1188 :background "yellow" :foreground "black")
1189 (((class color) (min-colors 8) (background dark))
1190 :background "blue" :foreground "white")
1191 (((type tty) (class mono))
1192 :inverse-video t)
1193 (t :background "gray"))
1194 "Face used to highlight matches permanently."
1195 :group 'matching
1196 :version "22.1")
1198 (defcustom list-matching-lines-default-context-lines 0
1199 "Default number of context lines included around `list-matching-lines' matches.
1200 A negative number means to include that many lines before the match.
1201 A positive number means to include that many lines both before and after."
1202 :type 'integer
1203 :group 'matching)
1205 (defalias 'list-matching-lines 'occur)
1207 (defcustom list-matching-lines-face 'match
1208 "Face used by \\[list-matching-lines] to show the text that matches.
1209 If the value is nil, don't highlight the matching portions specially."
1210 :type 'face
1211 :group 'matching)
1213 (defcustom list-matching-lines-buffer-name-face 'underline
1214 "Face used by \\[list-matching-lines] to show the names of buffers.
1215 If the value is nil, don't highlight the buffer names specially."
1216 :type 'face
1217 :group 'matching)
1219 (defcustom list-matching-lines-prefix-face 'shadow
1220 "Face used by \\[list-matching-lines] to show the prefix column.
1221 If the face doesn't differ from the default face,
1222 don't highlight the prefix with line numbers specially."
1223 :type 'face
1224 :group 'matching
1225 :version "24.4")
1227 (defcustom occur-excluded-properties
1228 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1229 yank-handler follow-link)
1230 "Text properties to discard when copying lines to the *Occur* buffer.
1231 The value should be a list of text properties to discard or t,
1232 which means to discard all text properties."
1233 :type '(choice (const :tag "All" t) (repeat symbol))
1234 :group 'matching
1235 :version "22.1")
1237 (defun occur-read-primary-args ()
1238 (let* ((perform-collect (consp current-prefix-arg))
1239 (regexp (read-regexp (if perform-collect
1240 "Collect strings matching regexp"
1241 "List lines matching regexp")
1242 'regexp-history-last)))
1243 (list regexp
1244 (if perform-collect
1245 ;; Perform collect operation
1246 (if (zerop (regexp-opt-depth regexp))
1247 ;; No subexpression so collect the entire match.
1248 "\\&"
1249 ;; Get the regexp for collection pattern.
1250 (let ((default (car occur-collect-regexp-history)))
1251 (read-regexp
1252 (format "Regexp to collect (default %s): " default)
1253 default 'occur-collect-regexp-history)))
1254 ;; Otherwise normal occur takes numerical prefix argument.
1255 (when current-prefix-arg
1256 (prefix-numeric-value current-prefix-arg))))))
1258 (defun occur-rename-buffer (&optional unique-p interactive-p)
1259 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1260 Here `original-buffer-name' is the buffer name where Occur was originally run.
1261 When given the prefix argument, or called non-interactively, the renaming
1262 will not clobber the existing buffer(s) of that name, but use
1263 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1264 if you always want a separate *Occur* buffer for each buffer where you
1265 invoke `occur'."
1266 (interactive "P\np")
1267 (with-current-buffer
1268 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1269 (rename-buffer (concat "*Occur: "
1270 (mapconcat #'buffer-name
1271 (car (cddr occur-revert-arguments)) "/")
1272 "*")
1273 (or unique-p (not interactive-p)))))
1275 (defun occur (regexp &optional nlines)
1276 "Show all lines in the current buffer containing a match for REGEXP.
1277 If a match spreads across multiple lines, all those lines are shown.
1279 Each line is displayed with NLINES lines before and after, or -NLINES
1280 before if NLINES is negative.
1281 NLINES defaults to `list-matching-lines-default-context-lines'.
1282 Interactively it is the prefix arg.
1284 The lines are shown in a buffer named `*Occur*'.
1285 It serves as a menu to find any of the occurrences in this buffer.
1286 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1288 If REGEXP contains upper case characters (excluding those preceded by `\\')
1289 and `search-upper-case' is non-nil, the matching is case-sensitive.
1291 When NLINES is a string or when the function is called
1292 interactively with prefix argument without a number (`C-u' alone
1293 as prefix) the matching strings are collected into the `*Occur*'
1294 buffer by using NLINES as a replacement regexp. NLINES may
1295 contain \\& and \\N which convention follows `replace-match'.
1296 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1297 \"\\1\" for NLINES collects all the function names in a lisp
1298 program. When there is no parenthesized subexpressions in REGEXP
1299 the entire match is collected. In any case the searched buffer
1300 is not modified."
1301 (interactive (occur-read-primary-args))
1302 (occur-1 regexp nlines (list (current-buffer))))
1304 (defvar ido-ignore-item-temp-list)
1306 (defun multi-occur (bufs regexp &optional nlines)
1307 "Show all lines in buffers BUFS containing a match for REGEXP.
1308 This function acts on multiple buffers; otherwise, it is exactly like
1309 `occur'. When you invoke this command interactively, you must specify
1310 the buffer names that you want, one by one.
1311 See also `multi-occur-in-matching-buffers'."
1312 (interactive
1313 (cons
1314 (let* ((bufs (list (read-buffer "First buffer to search: "
1315 (current-buffer) t)))
1316 (buf nil)
1317 (ido-ignore-item-temp-list bufs))
1318 (while (not (string-equal
1319 (setq buf (read-buffer
1320 (if (eq read-buffer-function 'ido-read-buffer)
1321 "Next buffer to search (C-j to end): "
1322 "Next buffer to search (RET to end): ")
1323 nil t))
1324 ""))
1325 (add-to-list 'bufs buf)
1326 (setq ido-ignore-item-temp-list bufs))
1327 (nreverse (mapcar #'get-buffer bufs)))
1328 (occur-read-primary-args)))
1329 (occur-1 regexp nlines bufs))
1331 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1332 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1333 Normally BUFREGEXP matches against each buffer's visited file name,
1334 but if you specify a prefix argument, it matches against the buffer name.
1335 See also `multi-occur'."
1336 (interactive
1337 (cons
1338 (let* ((default (car regexp-history))
1339 (input
1340 (read-regexp
1341 (if current-prefix-arg
1342 "List lines in buffers whose names match regexp: "
1343 "List lines in buffers whose filenames match regexp: "))))
1344 (if (equal input "")
1345 default
1346 input))
1347 (occur-read-primary-args)))
1348 (when bufregexp
1349 (occur-1 regexp nil
1350 (delq nil
1351 (mapcar (lambda (buf)
1352 (when (if allbufs
1353 (string-match bufregexp
1354 (buffer-name buf))
1355 (and (buffer-file-name buf)
1356 (string-match bufregexp
1357 (buffer-file-name buf))))
1358 buf))
1359 (buffer-list))))))
1361 (defun occur-1 (regexp nlines bufs &optional buf-name)
1362 (unless (and regexp (not (equal regexp "")))
1363 (error "Occur doesn't work with the empty regexp"))
1364 (unless buf-name
1365 (setq buf-name "*Occur*"))
1366 (let (occur-buf
1367 (active-bufs (delq nil (mapcar #'(lambda (buf)
1368 (when (buffer-live-p buf) buf))
1369 bufs))))
1370 ;; Handle the case where one of the buffers we're searching is the
1371 ;; output buffer. Just rename it.
1372 (when (member buf-name (mapcar 'buffer-name active-bufs))
1373 (with-current-buffer (get-buffer buf-name)
1374 (rename-uniquely)))
1376 ;; Now find or create the output buffer.
1377 ;; If we just renamed that buffer, we will make a new one here.
1378 (setq occur-buf (get-buffer-create buf-name))
1380 (with-current-buffer occur-buf
1381 (if (stringp nlines)
1382 (fundamental-mode) ;; This is for collect operation.
1383 (occur-mode))
1384 (let ((inhibit-read-only t)
1385 ;; Don't generate undo entries for creation of the initial contents.
1386 (buffer-undo-list t))
1387 (erase-buffer)
1388 (let ((count
1389 (if (stringp nlines)
1390 ;; Treat nlines as a regexp to collect.
1391 (let ((bufs active-bufs)
1392 (count 0))
1393 (while bufs
1394 (with-current-buffer (car bufs)
1395 (save-excursion
1396 (goto-char (point-min))
1397 (while (re-search-forward regexp nil t)
1398 ;; Insert the replacement regexp.
1399 (let ((str (match-substitute-replacement nlines)))
1400 (if str
1401 (with-current-buffer occur-buf
1402 (insert str)
1403 (setq count (1+ count))
1404 (or (zerop (current-column))
1405 (insert "\n"))))))))
1406 (setq bufs (cdr bufs)))
1407 count)
1408 ;; Perform normal occur.
1409 (occur-engine
1410 regexp active-bufs occur-buf
1411 (or nlines list-matching-lines-default-context-lines)
1412 (if (and case-fold-search search-upper-case)
1413 (isearch-no-upper-case-p regexp t)
1414 case-fold-search)
1415 list-matching-lines-buffer-name-face
1416 (if (face-differs-from-default-p list-matching-lines-prefix-face)
1417 list-matching-lines-prefix-face)
1418 list-matching-lines-face
1419 (not (eq occur-excluded-properties t))))))
1420 (let* ((bufcount (length active-bufs))
1421 (diff (- (length bufs) bufcount)))
1422 (message "Searched %d buffer%s%s; %s match%s%s"
1423 bufcount (if (= bufcount 1) "" "s")
1424 (if (zerop diff) "" (format " (%d killed)" diff))
1425 (if (zerop count) "no" (format "%d" count))
1426 (if (= count 1) "" "es")
1427 ;; Don't display regexp if with remaining text
1428 ;; it is longer than window-width.
1429 (if (> (+ (length regexp) 42) (window-width))
1430 "" (format " for `%s'" (query-replace-descr regexp)))))
1431 (setq occur-revert-arguments (list regexp nlines bufs))
1432 (if (= count 0)
1433 (kill-buffer occur-buf)
1434 (display-buffer occur-buf)
1435 (setq next-error-last-buffer occur-buf)
1436 (setq buffer-read-only t)
1437 (set-buffer-modified-p nil)
1438 (run-hooks 'occur-hook)))))))
1440 (defun occur-engine (regexp buffers out-buf nlines case-fold
1441 title-face prefix-face match-face keep-props)
1442 (with-current-buffer out-buf
1443 (let ((global-lines 0) ;; total count of matching lines
1444 (global-matches 0) ;; total count of matches
1445 (coding nil)
1446 (case-fold-search case-fold))
1447 ;; Map over all the buffers
1448 (dolist (buf buffers)
1449 (when (buffer-live-p buf)
1450 (let ((lines 0) ;; count of matching lines
1451 (matches 0) ;; count of matches
1452 (curr-line 1) ;; line count
1453 (prev-line nil) ;; line number of prev match endpt
1454 (prev-after-lines nil) ;; context lines of prev match
1455 (matchbeg 0)
1456 (origpt nil)
1457 (begpt nil)
1458 (endpt nil)
1459 (marker nil)
1460 (curstring "")
1461 (ret nil)
1462 (inhibit-field-text-motion t)
1463 (headerpt (with-current-buffer out-buf (point))))
1464 (with-current-buffer buf
1465 (or coding
1466 ;; Set CODING only if the current buffer locally
1467 ;; binds buffer-file-coding-system.
1468 (not (local-variable-p 'buffer-file-coding-system))
1469 (setq coding buffer-file-coding-system))
1470 (save-excursion
1471 (goto-char (point-min)) ;; begin searching in the buffer
1472 (while (not (eobp))
1473 (setq origpt (point))
1474 (when (setq endpt (re-search-forward regexp nil t))
1475 (setq lines (1+ lines)) ;; increment matching lines count
1476 (setq matchbeg (match-beginning 0))
1477 ;; Get beginning of first match line and end of the last.
1478 (save-excursion
1479 (goto-char matchbeg)
1480 (setq begpt (line-beginning-position))
1481 (goto-char endpt)
1482 (setq endpt (line-end-position)))
1483 ;; Sum line numbers up to the first match line.
1484 (setq curr-line (+ curr-line (count-lines origpt begpt)))
1485 (setq marker (make-marker))
1486 (set-marker marker matchbeg)
1487 (setq curstring (occur-engine-line begpt endpt keep-props))
1488 ;; Highlight the matches
1489 (let ((len (length curstring))
1490 (start 0))
1491 (while (and (< start len)
1492 (string-match regexp curstring start))
1493 (setq matches (1+ matches))
1494 (add-text-properties
1495 (match-beginning 0) (match-end 0)
1496 '(occur-match t) curstring)
1497 (when match-face
1498 ;; Add `match-face' to faces copied from the buffer.
1499 (add-face-text-property
1500 (match-beginning 0) (match-end 0)
1501 match-face nil curstring))
1502 ;; Avoid infloop (Bug#7593).
1503 (let ((end (match-end 0)))
1504 (setq start (if (= start end) (1+ start) end)))))
1505 ;; Generate the string to insert for this match
1506 (let* ((match-prefix
1507 ;; Using 7 digits aligns tabs properly.
1508 (apply #'propertize (format "%7d:" curr-line)
1509 (append
1510 (when prefix-face
1511 `(font-lock-face ,prefix-face))
1512 `(occur-prefix t mouse-face (highlight)
1513 ;; Allow insertion of text at
1514 ;; the end of the prefix (for
1515 ;; Occur Edit mode).
1516 front-sticky t rear-nonsticky t
1517 occur-target ,marker follow-link t
1518 help-echo "mouse-2: go to this occurrence"))))
1519 (match-str
1520 ;; We don't put `mouse-face' on the newline,
1521 ;; because that loses. And don't put it
1522 ;; on context lines to reduce flicker.
1523 (propertize curstring 'mouse-face (list 'highlight)
1524 'occur-target marker
1525 'follow-link t
1526 'help-echo
1527 "mouse-2: go to this occurrence"))
1528 (out-line
1529 (concat
1530 match-prefix
1531 ;; Add non-numeric prefix to all non-first lines
1532 ;; of multi-line matches.
1533 (replace-regexp-in-string
1534 "\n"
1535 (if prefix-face
1536 (propertize "\n :" 'font-lock-face prefix-face)
1537 "\n :")
1538 match-str)
1539 ;; Add marker at eol, but no mouse props.
1540 (propertize "\n" 'occur-target marker)))
1541 (data
1542 (if (= nlines 0)
1543 ;; The simple display style
1544 out-line
1545 ;; The complex multi-line display style.
1546 (setq ret (occur-context-lines
1547 out-line nlines keep-props begpt endpt
1548 curr-line prev-line prev-after-lines
1549 prefix-face))
1550 ;; Set first elem of the returned list to `data',
1551 ;; and the second elem to `prev-after-lines'.
1552 (setq prev-after-lines (nth 1 ret))
1553 (nth 0 ret))))
1554 ;; Actually insert the match display data
1555 (with-current-buffer out-buf
1556 (insert data)))
1557 (goto-char endpt))
1558 (if endpt
1559 (progn
1560 ;; Sum line numbers between first and last match lines.
1561 (setq curr-line (+ curr-line (count-lines begpt endpt)
1562 ;; Add 1 for empty last match line since
1563 ;; count-lines returns 1 line less.
1564 (if (and (bolp) (eolp)) 1 0)))
1565 ;; On to the next match...
1566 (forward-line 1))
1567 (goto-char (point-max)))
1568 (setq prev-line (1- curr-line)))
1569 ;; Flush remaining context after-lines.
1570 (when prev-after-lines
1571 (with-current-buffer out-buf
1572 (insert (apply #'concat (occur-engine-add-prefix
1573 prev-after-lines prefix-face)))))))
1574 (when (not (zerop lines)) ;; is the count zero?
1575 (setq global-lines (+ global-lines lines)
1576 global-matches (+ global-matches matches))
1577 (with-current-buffer out-buf
1578 (goto-char headerpt)
1579 (let ((beg (point))
1580 end)
1581 (insert (propertize
1582 (format "%d match%s%s%s in buffer: %s\n"
1583 matches (if (= matches 1) "" "es")
1584 ;; Don't display the same number of lines
1585 ;; and matches in case of 1 match per line.
1586 (if (= lines matches)
1587 "" (format " in %d line%s"
1588 lines (if (= lines 1) "" "s")))
1589 ;; Don't display regexp for multi-buffer.
1590 (if (> (length buffers) 1)
1591 "" (format " for \"%s\""
1592 (query-replace-descr regexp)))
1593 (buffer-name buf))
1594 'read-only t))
1595 (setq end (point))
1596 (add-text-properties beg end `(occur-title ,buf))
1597 (when title-face
1598 (add-face-text-property beg end title-face)))
1599 (goto-char (point-min)))))))
1600 ;; Display total match count and regexp for multi-buffer.
1601 (when (and (not (zerop global-lines)) (> (length buffers) 1))
1602 (goto-char (point-min))
1603 (let ((beg (point))
1604 end)
1605 (insert (format "%d match%s%s total for \"%s\":\n"
1606 global-matches (if (= global-matches 1) "" "es")
1607 ;; Don't display the same number of lines
1608 ;; and matches in case of 1 match per line.
1609 (if (= global-lines global-matches)
1610 "" (format " in %d line%s"
1611 global-lines (if (= global-lines 1) "" "s")))
1612 (query-replace-descr regexp)))
1613 (setq end (point))
1614 (when title-face
1615 (add-face-text-property beg end title-face)))
1616 (goto-char (point-min)))
1617 (if coding
1618 ;; CODING is buffer-file-coding-system of the first buffer
1619 ;; that locally binds it. Let's use it also for the output
1620 ;; buffer.
1621 (set-buffer-file-coding-system coding))
1622 ;; Return the number of matches
1623 global-matches)))
1625 (defun occur-engine-line (beg end &optional keep-props)
1626 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1627 (text-property-not-all beg end 'fontified t))
1628 (if (fboundp 'jit-lock-fontify-now)
1629 (jit-lock-fontify-now beg end)))
1630 (if (and keep-props (not (eq occur-excluded-properties t)))
1631 (let ((str (buffer-substring beg end)))
1632 (remove-list-of-text-properties
1633 0 (length str) occur-excluded-properties str)
1634 str)
1635 (buffer-substring-no-properties beg end)))
1637 (defun occur-engine-add-prefix (lines &optional prefix-face)
1638 (mapcar
1639 #'(lambda (line)
1640 (concat (if prefix-face
1641 (propertize " :" 'font-lock-face prefix-face)
1642 " :")
1643 line "\n"))
1644 lines))
1646 (defun occur-accumulate-lines (count &optional keep-props pt)
1647 (save-excursion
1648 (when pt
1649 (goto-char pt))
1650 (let ((forwardp (> count 0))
1651 result beg end moved)
1652 (while (not (or (zerop count)
1653 (if forwardp
1654 (eobp)
1655 (and (bobp) (not moved)))))
1656 (setq count (+ count (if forwardp -1 1)))
1657 (setq beg (line-beginning-position)
1658 end (line-end-position))
1659 (push (occur-engine-line beg end keep-props) result)
1660 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1661 (nreverse result))))
1663 ;; Generate context display for occur.
1664 ;; OUT-LINE is the line where the match is.
1665 ;; NLINES and KEEP-PROPS are args to occur-engine.
1666 ;; CURR-LINE is line count of the current match,
1667 ;; PREV-LINE is line count of the previous match,
1668 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1669 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1670 ;; then concatenate them all together.
1671 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1672 curr-line prev-line prev-after-lines
1673 &optional prefix-face)
1674 ;; Find after- and before-context lines of the current match.
1675 (let ((before-lines
1676 (nreverse (cdr (occur-accumulate-lines
1677 (- (1+ (abs nlines))) keep-props begpt))))
1678 (after-lines
1679 (cdr (occur-accumulate-lines
1680 (1+ nlines) keep-props endpt)))
1681 separator)
1683 ;; Combine after-lines of the previous match
1684 ;; with before-lines of the current match.
1686 (when prev-after-lines
1687 ;; Don't overlap prev after-lines with current before-lines.
1688 (if (>= (+ prev-line (length prev-after-lines))
1689 (- curr-line (length before-lines)))
1690 (setq prev-after-lines
1691 (butlast prev-after-lines
1692 (- (length prev-after-lines)
1693 (- curr-line prev-line (length before-lines) 1))))
1694 ;; Separate non-overlapping context lines with a dashed line.
1695 (setq separator "-------\n")))
1697 (when prev-line
1698 ;; Don't overlap current before-lines with previous match line.
1699 (if (<= (- curr-line (length before-lines))
1700 prev-line)
1701 (setq before-lines
1702 (nthcdr (- (length before-lines)
1703 (- curr-line prev-line 1))
1704 before-lines))
1705 ;; Separate non-overlapping before-context lines.
1706 (unless (> nlines 0)
1707 (setq separator "-------\n"))))
1709 (list
1710 ;; Return a list where the first element is the output line.
1711 (apply #'concat
1712 (append
1713 (if prev-after-lines
1714 (occur-engine-add-prefix prev-after-lines prefix-face))
1715 (if separator
1716 (list (if prefix-face
1717 (propertize separator 'font-lock-face prefix-face)
1718 separator)))
1719 (occur-engine-add-prefix before-lines prefix-face)
1720 (list out-line)))
1721 ;; And the second element is the list of context after-lines.
1722 (if (> nlines 0) after-lines))))
1725 ;; It would be nice to use \\[...], but there is no reasonable way
1726 ;; to make that display both SPC and Y.
1727 (defconst query-replace-help
1728 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1729 RET or `q' to exit, Period to replace one match and exit,
1730 Comma to replace but not move point immediately,
1731 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1732 C-w to delete match and recursive edit,
1733 C-l to clear the screen, redisplay, and offer same replacement again,
1734 ! to replace all remaining matches in this buffer with no more questions,
1735 ^ to move point back to previous match,
1736 E to edit the replacement string.
1737 In multi-buffer replacements type `Y' to replace all remaining
1738 matches in all remaining buffers with no more questions,
1739 `N' to skip to the next buffer without replacing remaining matches
1740 in the current buffer."
1741 "Help message while in `query-replace'.")
1743 (defvar query-replace-map
1744 (let ((map (make-sparse-keymap)))
1745 (define-key map " " 'act)
1746 (define-key map "\d" 'skip)
1747 (define-key map [delete] 'skip)
1748 (define-key map [backspace] 'skip)
1749 (define-key map "y" 'act)
1750 (define-key map "n" 'skip)
1751 (define-key map "Y" 'act)
1752 (define-key map "N" 'skip)
1753 (define-key map "e" 'edit-replacement)
1754 (define-key map "E" 'edit-replacement)
1755 (define-key map "," 'act-and-show)
1756 (define-key map "q" 'exit)
1757 (define-key map "\r" 'exit)
1758 (define-key map [return] 'exit)
1759 (define-key map "." 'act-and-exit)
1760 (define-key map "\C-r" 'edit)
1761 (define-key map "\C-w" 'delete-and-edit)
1762 (define-key map "\C-l" 'recenter)
1763 (define-key map "!" 'automatic)
1764 (define-key map "^" 'backup)
1765 (define-key map "\C-h" 'help)
1766 (define-key map [f1] 'help)
1767 (define-key map [help] 'help)
1768 (define-key map "?" 'help)
1769 (define-key map "\C-g" 'quit)
1770 (define-key map "\C-]" 'quit)
1771 (define-key map "\C-v" 'scroll-up)
1772 (define-key map "\M-v" 'scroll-down)
1773 (define-key map [next] 'scroll-up)
1774 (define-key map [prior] 'scroll-down)
1775 (define-key map [?\C-\M-v] 'scroll-other-window)
1776 (define-key map [M-next] 'scroll-other-window)
1777 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1778 (define-key map [M-prior] 'scroll-other-window-down)
1779 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1780 ;; should check for ESC specially.
1781 ;; (define-key map "\e" 'exit-prefix)
1782 (define-key map [escape] 'exit-prefix)
1783 map)
1784 "Keymap of responses to questions posed by commands like `query-replace'.
1785 The \"bindings\" in this map are not commands; they are answers.
1786 The valid answers include `act', `skip', `act-and-show',
1787 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1788 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1789 `edit', `edit-replacement', `delete-and-edit', `automatic',
1790 `backup', `quit', and `help'.
1792 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1794 (defvar multi-query-replace-map
1795 (let ((map (make-sparse-keymap)))
1796 (set-keymap-parent map query-replace-map)
1797 (define-key map "Y" 'automatic-all)
1798 (define-key map "N" 'exit-current)
1799 map)
1800 "Keymap that defines additional bindings for multi-buffer replacements.
1801 It extends its parent map `query-replace-map' with new bindings to
1802 operate on a set of buffers/files. The difference with its parent map
1803 is the additional answers `automatic-all' to replace all remaining
1804 matches in all remaining buffers with no more questions, and
1805 `exit-current' to skip remaining matches in the current buffer
1806 and to continue with the next buffer in the sequence.")
1808 (defun replace-match-string-symbols (n)
1809 "Process a list (and any sub-lists), expanding certain symbols.
1810 Symbol Expands To
1811 N (match-string N) (where N is a string of digits)
1812 #N (string-to-number (match-string N))
1813 & (match-string 0)
1814 #& (string-to-number (match-string 0))
1815 # replace-count
1817 Note that these symbols must be preceded by a backslash in order to
1818 type them using Lisp syntax."
1819 (while (consp n)
1820 (cond
1821 ((consp (car n))
1822 (replace-match-string-symbols (car n))) ;Process sub-list
1823 ((symbolp (car n))
1824 (let ((name (symbol-name (car n))))
1825 (cond
1826 ((string-match "^[0-9]+$" name)
1827 (setcar n (list 'match-string (string-to-number name))))
1828 ((string-match "^#[0-9]+$" name)
1829 (setcar n (list 'string-to-number
1830 (list 'match-string
1831 (string-to-number (substring name 1))))))
1832 ((string= "&" name)
1833 (setcar n '(match-string 0)))
1834 ((string= "#&" name)
1835 (setcar n '(string-to-number (match-string 0))))
1836 ((string= "#" name)
1837 (setcar n 'replace-count))))))
1838 (setq n (cdr n))))
1840 (defun replace-eval-replacement (expression count)
1841 (let* ((replace-count count)
1843 (replacement
1844 (condition-case err
1845 (eval expression)
1846 (error
1847 (error "Error evaluating replacement expression: %S" err)))))
1848 (if (stringp replacement)
1849 replacement
1850 (prin1-to-string replacement t))))
1852 (defun replace-quote (replacement)
1853 "Quote a replacement string.
1854 This just doubles all backslashes in REPLACEMENT and
1855 returns the resulting string. If REPLACEMENT is not
1856 a string, it is first passed through `prin1-to-string'
1857 with the `noescape' argument set.
1859 `match-data' is preserved across the call."
1860 (save-match-data
1861 (replace-regexp-in-string "\\\\" "\\\\"
1862 (if (stringp replacement)
1863 replacement
1864 (prin1-to-string replacement t))
1865 t t)))
1867 (defun replace-loop-through-replacements (data count)
1868 ;; DATA is a vector containing the following values:
1869 ;; 0 next-rotate-count
1870 ;; 1 repeat-count
1871 ;; 2 next-replacement
1872 ;; 3 replacements
1873 (if (= (aref data 0) count)
1874 (progn
1875 (aset data 0 (+ count (aref data 1)))
1876 (let ((next (cdr (aref data 2))))
1877 (aset data 2 (if (consp next) next (aref data 3))))))
1878 (car (aref data 2)))
1880 (defun replace-match-data (integers reuse &optional new)
1881 "Like `match-data', but markers in REUSE get invalidated.
1882 If NEW is non-nil, it is set and returned instead of fresh data,
1883 but coerced to the correct value of INTEGERS."
1884 (or (and new
1885 (progn
1886 (set-match-data new)
1887 (and (eq new reuse)
1888 (eq (null integers) (markerp (car reuse)))
1889 new)))
1890 (match-data integers reuse t)))
1892 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data backward)
1893 "Make a replacement with `replace-match', editing `\\?'.
1894 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1895 check for `\\?' is made to save time. MATCH-DATA is used for the
1896 replacement. In case editing is done, it is changed to use markers.
1898 The return value is non-nil if there has been no `\\?' or NOEDIT was
1899 passed in. If LITERAL is set, no checking is done, anyway."
1900 (unless (or literal noedit)
1901 (setq noedit t)
1902 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1903 newtext)
1904 (setq newtext
1905 (read-string "Edit replacement string: "
1906 (prog1
1907 (cons
1908 (replace-match "" t t newtext 3)
1909 (1+ (match-beginning 3)))
1910 (setq match-data
1911 (replace-match-data
1912 nil match-data match-data))))
1913 noedit nil)))
1914 (set-match-data match-data)
1915 (replace-match newtext fixedcase literal)
1916 ;; `replace-match' leaves point at the end of the replacement text,
1917 ;; so move point to the beginning when replacing backward.
1918 (when backward (goto-char (nth 0 match-data)))
1919 noedit)
1921 (defvar replace-search-function nil
1922 "Function to use when searching for strings to replace.
1923 It is used by `query-replace' and `replace-string', and is called
1924 with three arguments, as if it were `search-forward'.")
1926 (defvar replace-re-search-function nil
1927 "Function to use when searching for regexps to replace.
1928 It is used by `query-replace-regexp', `replace-regexp',
1929 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1930 It is called with three arguments, as if it were
1931 `re-search-forward'.")
1933 (defun replace-search (search-string limit regexp-flag delimited-flag
1934 case-fold-search backward)
1935 "Search for the next occurrence of SEARCH-STRING to replace."
1936 ;; Let-bind global isearch-* variables to values used
1937 ;; to search the next replacement. These let-bindings
1938 ;; should be effective both at the time of calling
1939 ;; `isearch-search-fun-default' and also at the
1940 ;; time of funcalling `search-function'.
1941 ;; These isearch-* bindings can't be placed higher
1942 ;; outside of this function because then another I-search
1943 ;; used after `recursive-edit' might override them.
1944 (let* ((isearch-regexp regexp-flag)
1945 (isearch-word delimited-flag)
1946 (isearch-lax-whitespace
1947 replace-lax-whitespace)
1948 (isearch-regexp-lax-whitespace
1949 replace-regexp-lax-whitespace)
1950 (isearch-case-fold-search case-fold-search)
1951 (isearch-adjusted nil)
1952 (isearch-nonincremental t) ; don't use lax word mode
1953 (isearch-forward (not backward))
1954 (search-function
1955 (or (if regexp-flag
1956 replace-re-search-function
1957 replace-search-function)
1958 (isearch-search-fun-default))))
1959 (funcall search-function search-string limit t)))
1961 (defvar replace-overlay nil)
1963 (defun replace-highlight (match-beg match-end range-beg range-end
1964 search-string regexp-flag delimited-flag
1965 case-fold-search backward)
1966 (if query-replace-highlight
1967 (if replace-overlay
1968 (move-overlay replace-overlay match-beg match-end (current-buffer))
1969 (setq replace-overlay (make-overlay match-beg match-end))
1970 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
1971 (overlay-put replace-overlay 'face 'query-replace)))
1972 (if query-replace-lazy-highlight
1973 (let ((isearch-string search-string)
1974 (isearch-regexp regexp-flag)
1975 (isearch-word delimited-flag)
1976 (isearch-lax-whitespace
1977 replace-lax-whitespace)
1978 (isearch-regexp-lax-whitespace
1979 replace-regexp-lax-whitespace)
1980 (isearch-case-fold-search case-fold-search)
1981 (isearch-forward (not backward))
1982 (isearch-other-end match-beg)
1983 (isearch-error nil))
1984 (isearch-lazy-highlight-new-loop range-beg range-end))))
1986 (defun replace-dehighlight ()
1987 (when replace-overlay
1988 (delete-overlay replace-overlay))
1989 (when query-replace-lazy-highlight
1990 (lazy-highlight-cleanup lazy-highlight-cleanup)
1991 (setq isearch-lazy-highlight-last-string nil))
1992 ;; Close overlays opened by `isearch-range-invisible' in `perform-replace'.
1993 (isearch-clean-overlays))
1995 (defun perform-replace (from-string replacements
1996 query-flag regexp-flag delimited-flag
1997 &optional repeat-count map start end backward)
1998 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1999 Don't use this in your own program unless you want to query and set the mark
2000 just as `query-replace' does. Instead, write a simple loop like this:
2002 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
2003 (replace-match \"foobar\" nil nil))
2005 which will run faster and probably do exactly what you want. Please
2006 see the documentation of `replace-match' to find out how to simulate
2007 `case-replace'.
2009 This function returns nil if and only if there were no matches to
2010 make, or the user didn't cancel the call."
2011 (or map (setq map query-replace-map))
2012 (and query-flag minibuffer-auto-raise
2013 (raise-frame (window-frame (minibuffer-window))))
2014 (let* ((case-fold-search
2015 (if (and case-fold-search search-upper-case)
2016 (isearch-no-upper-case-p from-string regexp-flag)
2017 case-fold-search))
2018 (nocasify (not (and case-replace case-fold-search)))
2019 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
2020 (search-string from-string)
2021 (real-match-data nil) ; The match data for the current match.
2022 (next-replacement nil)
2023 ;; This is non-nil if we know there is nothing for the user
2024 ;; to edit in the replacement.
2025 (noedit nil)
2026 (keep-going t)
2027 (stack nil)
2028 (replace-count 0)
2029 (skip-read-only-count 0)
2030 (skip-filtered-count 0)
2031 (skip-invisible-count 0)
2032 (nonempty-match nil)
2033 (multi-buffer nil)
2034 (recenter-last-op nil) ; Start cycling order with initial position.
2036 ;; If non-nil, it is marker saying where in the buffer to stop.
2037 (limit nil)
2039 ;; Data for the next match. If a cons, it has the same format as
2040 ;; (match-data); otherwise it is t if a match is possible at point.
2041 (match-again t)
2043 (message
2044 (if query-flag
2045 (apply 'propertize
2046 (substitute-command-keys
2047 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
2048 minibuffer-prompt-properties))))
2050 ;; If region is active, in Transient Mark mode, operate on region.
2051 (if backward
2052 (when end
2053 (setq limit (copy-marker (min start end)))
2054 (goto-char (max start end))
2055 (deactivate-mark))
2056 (when start
2057 (setq limit (copy-marker (max start end)))
2058 (goto-char (min start end))
2059 (deactivate-mark)))
2061 ;; If last typed key in previous call of multi-buffer perform-replace
2062 ;; was `automatic-all', don't ask more questions in next files
2063 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
2064 (setq query-flag nil multi-buffer t))
2066 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
2067 ;; containing a function and its first argument. The function is
2068 ;; called to generate each replacement like this:
2069 ;; (funcall (car replacements) (cdr replacements) replace-count)
2070 ;; It must return a string.
2071 (cond
2072 ((stringp replacements)
2073 (setq next-replacement replacements
2074 replacements nil))
2075 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
2076 (or repeat-count (setq repeat-count 1))
2077 (setq replacements (cons 'replace-loop-through-replacements
2078 (vector repeat-count repeat-count
2079 replacements replacements)))))
2081 (when query-replace-lazy-highlight
2082 (setq isearch-lazy-highlight-last-string nil))
2084 (push-mark)
2085 (undo-boundary)
2086 (unwind-protect
2087 ;; Loop finding occurrences that perhaps should be replaced.
2088 (while (and keep-going
2089 (if backward
2090 (not (or (bobp) (and limit (<= (point) limit))))
2091 (not (or (eobp) (and limit (>= (point) limit)))))
2092 ;; Use the next match if it is already known;
2093 ;; otherwise, search for a match after moving forward
2094 ;; one char if progress is required.
2095 (setq real-match-data
2096 (cond ((consp match-again)
2097 (goto-char (if backward
2098 (nth 0 match-again)
2099 (nth 1 match-again)))
2100 (replace-match-data
2101 t real-match-data match-again))
2102 ;; MATCH-AGAIN non-nil means accept an
2103 ;; adjacent match.
2104 (match-again
2105 (and
2106 (replace-search search-string limit
2107 regexp-flag delimited-flag
2108 case-fold-search backward)
2109 ;; For speed, use only integers and
2110 ;; reuse the list used last time.
2111 (replace-match-data t real-match-data)))
2112 ((and (if backward
2113 (> (1- (point)) (point-min))
2114 (< (1+ (point)) (point-max)))
2115 (or (null limit)
2116 (if backward
2117 (> (1- (point)) limit)
2118 (< (1+ (point)) limit))))
2119 ;; If not accepting adjacent matches,
2120 ;; move one char to the right before
2121 ;; searching again. Undo the motion
2122 ;; if the search fails.
2123 (let ((opoint (point)))
2124 (forward-char (if backward -1 1))
2125 (if (replace-search search-string limit
2126 regexp-flag delimited-flag
2127 case-fold-search backward)
2128 (replace-match-data
2129 t real-match-data)
2130 (goto-char opoint)
2131 nil))))))
2133 ;; Record whether the match is nonempty, to avoid an infinite loop
2134 ;; repeatedly matching the same empty string.
2135 (setq nonempty-match
2136 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
2138 ;; If the match is empty, record that the next one can't be
2139 ;; adjacent.
2141 ;; Otherwise, if matching a regular expression, do the next
2142 ;; match now, since the replacement for this match may
2143 ;; affect whether the next match is adjacent to this one.
2144 ;; If that match is empty, don't use it.
2145 (setq match-again
2146 (and nonempty-match
2147 (or (not regexp-flag)
2148 (and (if backward
2149 (looking-back search-string)
2150 (looking-at search-string))
2151 (let ((match (match-data)))
2152 (and (/= (nth 0 match) (nth 1 match))
2153 match))))))
2155 (cond
2156 ;; Optionally ignore matches that have a read-only property.
2157 ((not (or (not query-replace-skip-read-only)
2158 (not (text-property-not-all
2159 (nth 0 real-match-data) (nth 1 real-match-data)
2160 'read-only nil))))
2161 (setq skip-read-only-count (1+ skip-read-only-count)))
2162 ;; Optionally filter out matches.
2163 ((not (funcall isearch-filter-predicate
2164 (nth 0 real-match-data) (nth 1 real-match-data)))
2165 (setq skip-filtered-count (1+ skip-filtered-count)))
2166 ;; Optionally ignore invisible matches.
2167 ((not (or (eq search-invisible t)
2168 ;; Don't open overlays for automatic replacements.
2169 (and (not query-flag) search-invisible)
2170 ;; Open hidden overlays for interactive replacements.
2171 (not (isearch-range-invisible
2172 (nth 0 real-match-data) (nth 1 real-match-data)))))
2173 (setq skip-invisible-count (1+ skip-invisible-count)))
2175 ;; Calculate the replacement string, if necessary.
2176 (when replacements
2177 (set-match-data real-match-data)
2178 (setq next-replacement
2179 (funcall (car replacements) (cdr replacements)
2180 replace-count)))
2181 (if (not query-flag)
2182 (progn
2183 (unless (or literal noedit)
2184 (replace-highlight
2185 (nth 0 real-match-data) (nth 1 real-match-data)
2186 start end search-string
2187 regexp-flag delimited-flag case-fold-search backward))
2188 (setq noedit
2189 (replace-match-maybe-edit
2190 next-replacement nocasify literal
2191 noedit real-match-data backward)
2192 replace-count (1+ replace-count)))
2193 (undo-boundary)
2194 (let (done replaced key def)
2195 ;; Loop reading commands until one of them sets done,
2196 ;; which means it has finished handling this
2197 ;; occurrence. Any command that sets `done' should
2198 ;; leave behind proper match data for the stack.
2199 ;; Commands not setting `done' need to adjust
2200 ;; `real-match-data'.
2201 (while (not done)
2202 (set-match-data real-match-data)
2203 (replace-highlight
2204 (match-beginning 0) (match-end 0)
2205 start end search-string
2206 regexp-flag delimited-flag case-fold-search backward)
2207 ;; Bind message-log-max so we don't fill up the message log
2208 ;; with a bunch of identical messages.
2209 (let ((message-log-max nil)
2210 (replacement-presentation
2211 (if query-replace-show-replacement
2212 (save-match-data
2213 (set-match-data real-match-data)
2214 (match-substitute-replacement next-replacement
2215 nocasify literal))
2216 next-replacement)))
2217 (message message
2218 (query-replace-descr from-string)
2219 (query-replace-descr replacement-presentation)))
2220 (setq key (read-event))
2221 ;; Necessary in case something happens during read-event
2222 ;; that clobbers the match data.
2223 (set-match-data real-match-data)
2224 (setq key (vector key))
2225 (setq def (lookup-key map key))
2226 ;; Restore the match data while we process the command.
2227 (cond ((eq def 'help)
2228 (with-output-to-temp-buffer "*Help*"
2229 (princ
2230 (concat "Query replacing "
2231 (if delimited-flag
2232 (or (and (symbolp delimited-flag)
2233 (get delimited-flag 'isearch-message-prefix))
2234 "word ") "")
2235 (if regexp-flag "regexp " "")
2236 (if backward "backward " "")
2237 from-string " with "
2238 next-replacement ".\n\n"
2239 (substitute-command-keys
2240 query-replace-help)))
2241 (with-current-buffer standard-output
2242 (help-mode))))
2243 ((eq def 'exit)
2244 (setq keep-going nil)
2245 (setq done t))
2246 ((eq def 'exit-current)
2247 (setq multi-buffer t keep-going nil done t))
2248 ((eq def 'backup)
2249 (if stack
2250 (let ((elt (pop stack)))
2251 (goto-char (nth 0 elt))
2252 (setq replaced (nth 1 elt)
2253 real-match-data
2254 (replace-match-data
2255 t real-match-data
2256 (nth 2 elt))))
2257 (message "No previous match")
2258 (ding 'no-terminate)
2259 (sit-for 1)))
2260 ((eq def 'act)
2261 (or replaced
2262 (setq noedit
2263 (replace-match-maybe-edit
2264 next-replacement nocasify literal
2265 noedit real-match-data backward)
2266 replace-count (1+ replace-count)))
2267 (setq done t replaced t))
2268 ((eq def 'act-and-exit)
2269 (or replaced
2270 (setq noedit
2271 (replace-match-maybe-edit
2272 next-replacement nocasify literal
2273 noedit real-match-data backward)
2274 replace-count (1+ replace-count)))
2275 (setq keep-going nil)
2276 (setq done t replaced t))
2277 ((eq def 'act-and-show)
2278 (if (not replaced)
2279 (setq noedit
2280 (replace-match-maybe-edit
2281 next-replacement nocasify literal
2282 noedit real-match-data backward)
2283 replace-count (1+ replace-count)
2284 real-match-data (replace-match-data
2285 t real-match-data)
2286 replaced t)))
2287 ((or (eq def 'automatic) (eq def 'automatic-all))
2288 (or replaced
2289 (setq noedit
2290 (replace-match-maybe-edit
2291 next-replacement nocasify literal
2292 noedit real-match-data backward)
2293 replace-count (1+ replace-count)))
2294 (setq done t query-flag nil replaced t)
2295 (if (eq def 'automatic-all) (setq multi-buffer t)))
2296 ((eq def 'skip)
2297 (setq done t))
2298 ((eq def 'recenter)
2299 ;; `this-command' has the value `query-replace',
2300 ;; so we need to bind it to `recenter-top-bottom'
2301 ;; to allow it to detect a sequence of `C-l'.
2302 (let ((this-command 'recenter-top-bottom)
2303 (last-command 'recenter-top-bottom))
2304 (recenter-top-bottom)))
2305 ((eq def 'edit)
2306 (let ((opos (point-marker)))
2307 (setq real-match-data (replace-match-data
2308 nil real-match-data
2309 real-match-data))
2310 (goto-char (match-beginning 0))
2311 (save-excursion
2312 (save-window-excursion
2313 (recursive-edit)))
2314 (goto-char opos)
2315 (set-marker opos nil))
2316 ;; Before we make the replacement,
2317 ;; decide whether the search string
2318 ;; can match again just after this match.
2319 (if (and regexp-flag nonempty-match)
2320 (setq match-again (and (looking-at search-string)
2321 (match-data)))))
2322 ;; Edit replacement.
2323 ((eq def 'edit-replacement)
2324 (setq real-match-data (replace-match-data
2325 nil real-match-data
2326 real-match-data)
2327 next-replacement
2328 (read-string "Edit replacement string: "
2329 next-replacement)
2330 noedit nil)
2331 (if replaced
2332 (set-match-data real-match-data)
2333 (setq noedit
2334 (replace-match-maybe-edit
2335 next-replacement nocasify literal noedit
2336 real-match-data backward)
2337 replaced t))
2338 (setq done t))
2340 ((eq def 'delete-and-edit)
2341 (replace-match "" t t)
2342 (setq real-match-data (replace-match-data
2343 nil real-match-data))
2344 (replace-dehighlight)
2345 (save-excursion (recursive-edit))
2346 (setq replaced t))
2347 ;; Note: we do not need to treat `exit-prefix'
2348 ;; specially here, since we reread
2349 ;; any unrecognized character.
2351 (setq this-command 'mode-exited)
2352 (setq keep-going nil)
2353 (setq unread-command-events
2354 (append (listify-key-sequence key)
2355 unread-command-events))
2356 (setq done t)))
2357 (when query-replace-lazy-highlight
2358 ;; Force lazy rehighlighting only after replacements.
2359 (if (not (memq def '(skip backup)))
2360 (setq isearch-lazy-highlight-last-string nil)))
2361 (unless (eq def 'recenter)
2362 ;; Reset recenter cycling order to initial position.
2363 (setq recenter-last-op nil)))
2364 ;; Record previous position for ^ when we move on.
2365 ;; Change markers to numbers in the match data
2366 ;; since lots of markers slow down editing.
2367 (push (list (point) replaced
2368 ;;; If the replacement has already happened, all we need is the
2369 ;;; current match start and end. We could get this with a trivial
2370 ;;; match like
2371 ;;; (save-excursion (goto-char (match-beginning 0))
2372 ;;; (search-forward (match-string 0))
2373 ;;; (match-data t))
2374 ;;; if we really wanted to avoid manually constructing match data.
2375 ;;; Adding current-buffer is necessary so that match-data calls can
2376 ;;; return markers which are appropriate for editing.
2377 (if replaced
2378 (list
2379 (match-beginning 0)
2380 (match-end 0)
2381 (current-buffer))
2382 (match-data t)))
2383 stack))))))
2385 (replace-dehighlight))
2386 (or unread-command-events
2387 (message "Replaced %d occurrence%s%s"
2388 replace-count
2389 (if (= replace-count 1) "" "s")
2390 (if (> (+ skip-read-only-count
2391 skip-filtered-count
2392 skip-invisible-count) 0)
2393 (format " (skipped %s)"
2394 (mapconcat
2395 'identity
2396 (delq nil (list
2397 (if (> skip-read-only-count 0)
2398 (format "%s read-only"
2399 skip-read-only-count))
2400 (if (> skip-invisible-count 0)
2401 (format "%s invisible"
2402 skip-invisible-count))
2403 (if (> skip-filtered-count 0)
2404 (format "%s filtered out"
2405 skip-filtered-count))))
2406 ", "))
2407 "")))
2408 (or (and keep-going stack) multi-buffer)))
2410 ;;; replace.el ends here