Fix bug #13515 with processing DBCS file names on MS-Windows.
[emacs.git] / lisp / replace.el
blobfb251821445ea80b3066f2eb05dccf62108be4ac
1 ;;; replace.el --- replace commands for Emacs
3 ;; Copyright (C) 1985-1987, 1992, 1994, 1996-1997, 2000-2013 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 current-prefix-arg)))
231 (defun query-replace (from-string to-string &optional delimited start end)
232 "Replace some occurrences of FROM-STRING with TO-STRING.
233 As each match is found, the user must type a character saying
234 what to do with it. For directions, type \\[help-command] at that time.
236 In Transient Mark mode, if the mark is active, operate on the contents
237 of the region. Otherwise, operate from point to the end of the buffer.
239 Use \\<minibuffer-local-map>\\[next-history-element] \
240 to pull the last incremental search string to the minibuffer
241 that reads FROM-STRING, or invoke replacements from
242 incremental search with a key sequence like `C-s C-s M-%'
243 to use its current search string as the string to replace.
245 Matching is independent of case if `case-fold-search' is non-nil and
246 FROM-STRING has no uppercase letters. Replacement transfers the case
247 pattern of the old text to the new text, if `case-replace' and
248 `case-fold-search' are non-nil and FROM-STRING has no uppercase
249 letters. \(Transferring the case pattern means that if the old text
250 matched is all caps, or capitalized, then its replacement is upcased
251 or capitalized.)
253 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
254 to be replaced will match a sequence of whitespace chars defined by the
255 regexp in `search-whitespace-regexp'.
257 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
258 only matches surrounded by word boundaries.
259 Fourth and fifth arg START and END specify the region to operate on.
261 To customize possible responses, change the \"bindings\" in `query-replace-map'."
262 (interactive
263 (let ((common
264 (query-replace-read-args
265 (concat "Query replace"
266 (if current-prefix-arg " word" "")
267 (if (and transient-mark-mode mark-active) " in region" ""))
268 nil)))
269 (list (nth 0 common) (nth 1 common) (nth 2 common)
270 ;; These are done separately here
271 ;; so that command-history will record these expressions
272 ;; rather than the values they had this time.
273 (if (and transient-mark-mode mark-active)
274 (region-beginning))
275 (if (and transient-mark-mode mark-active)
276 (region-end)))))
277 (perform-replace from-string to-string t nil delimited nil nil start end))
279 (define-key esc-map "%" 'query-replace)
281 (defun query-replace-regexp (regexp to-string &optional delimited start end)
282 "Replace some things after point matching REGEXP with TO-STRING.
283 As each match is found, the user must type a character saying
284 what to do with it. For directions, type \\[help-command] at that time.
286 In Transient Mark mode, if the mark is active, operate on the contents
287 of the region. Otherwise, operate from point to the end of the buffer.
289 Use \\<minibuffer-local-map>\\[next-history-element] \
290 to pull the last incremental search regexp to the minibuffer
291 that reads REGEXP, or invoke replacements from
292 incremental search with a key sequence like `C-M-s C-M-s C-M-%'
293 to use its current search regexp as the regexp to replace.
295 Matching is independent of case if `case-fold-search' is non-nil and
296 REGEXP has no uppercase letters. Replacement transfers the case
297 pattern of the old text to the new text, if `case-replace' and
298 `case-fold-search' are non-nil and REGEXP has no uppercase letters.
299 \(Transferring the case pattern means that if the old text matched is
300 all caps, or capitalized, then its replacement is upcased or
301 capitalized.)
303 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
304 to be replaced will match a sequence of whitespace chars defined by the
305 regexp in `search-whitespace-regexp'.
307 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
308 only matches surrounded by word boundaries.
309 Fourth and fifth arg START and END specify the region to operate on.
311 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
312 and `\\=\\N' (where N is a digit) stands for
313 whatever what matched the Nth `\\(...\\)' in REGEXP.
314 `\\?' lets you edit the replacement text in the minibuffer
315 at the given position for each replacement.
317 In interactive calls, the replacement text can contain `\\,'
318 followed by a Lisp expression. Each
319 replacement evaluates that expression to compute the replacement
320 string. Inside of that expression, `\\&' is a string denoting the
321 whole match as a string, `\\N' for a partial match, `\\#&' and `\\#N'
322 for the whole or a partial match converted to a number with
323 `string-to-number', and `\\#' itself for the number of replacements
324 done so far (starting with zero).
326 If the replacement expression is a symbol, write a space after it
327 to terminate it. One space there, if any, will be discarded.
329 When using those Lisp features interactively in the replacement
330 text, TO-STRING is actually made a list instead of a string.
331 Use \\[repeat-complex-command] after this command for details."
332 (interactive
333 (let ((common
334 (query-replace-read-args
335 (concat "Query replace"
336 (if current-prefix-arg " word" "")
337 " regexp"
338 (if (and transient-mark-mode mark-active) " in region" ""))
339 t)))
340 (list (nth 0 common) (nth 1 common) (nth 2 common)
341 ;; These are done separately here
342 ;; so that command-history will record these expressions
343 ;; rather than the values they had this time.
344 (if (and transient-mark-mode mark-active)
345 (region-beginning))
346 (if (and transient-mark-mode mark-active)
347 (region-end)))))
348 (perform-replace regexp to-string t t delimited nil nil start end))
350 (define-key esc-map [?\C-%] 'query-replace-regexp)
352 (defun query-replace-regexp-eval (regexp to-expr &optional delimited start end)
353 "Replace some things after point matching REGEXP with the result of TO-EXPR.
355 Interactive use of this function is deprecated in favor of the
356 `\\,' feature of `query-replace-regexp'. For non-interactive use, a loop
357 using `search-forward-regexp' and `replace-match' is preferred.
359 As each match is found, the user must type a character saying
360 what to do with it. For directions, type \\[help-command] at that time.
362 TO-EXPR is a Lisp expression evaluated to compute each replacement. It may
363 reference `replace-count' to get the number of replacements already made.
364 If the result of TO-EXPR is not a string, it is converted to one using
365 `prin1-to-string' with the NOESCAPE argument (which see).
367 For convenience, when entering TO-EXPR interactively, you can use `\\&' or
368 `\\0' to stand for whatever matched the whole of REGEXP, and `\\N' (where
369 N is a digit) to stand for whatever matched the Nth `\\(...\\)' in REGEXP.
370 Use `\\#&' or `\\#N' if you want a number instead of a string.
371 In interactive use, `\\#' in itself stands for `replace-count'.
373 In Transient Mark mode, if the mark is active, operate on the contents
374 of the region. Otherwise, operate from point to the end of the buffer.
376 Use \\<minibuffer-local-map>\\[next-history-element] \
377 to pull the last incremental search regexp to the minibuffer
378 that reads REGEXP.
380 Preserves case in each replacement if `case-replace' and `case-fold-search'
381 are non-nil and REGEXP has no uppercase letters.
383 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
384 to be replaced will match a sequence of whitespace chars defined by the
385 regexp in `search-whitespace-regexp'.
387 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
388 only matches that are surrounded by word boundaries.
389 Fourth and fifth arg START and END specify the region to operate on."
390 (declare (obsolete "use the `\\,' feature of `query-replace-regexp'
391 for interactive calls, and `search-forward-regexp'/`replace-match'
392 for Lisp calls." "22.1"))
393 (interactive
394 (progn
395 (barf-if-buffer-read-only)
396 (let* ((from
397 ;; Let-bind the history var to disable the "foo -> bar"
398 ;; default. Maybe we shouldn't disable this default, but
399 ;; for now I'll leave it off. --Stef
400 (let ((query-replace-to-history-variable nil))
401 (query-replace-read-from "Query replace regexp" t)))
402 (to (list (read-from-minibuffer
403 (format "Query replace regexp %s with eval: "
404 (query-replace-descr from))
405 nil nil t query-replace-to-history-variable from t))))
406 ;; We make TO a list because replace-match-string-symbols requires one,
407 ;; and the user might enter a single token.
408 (replace-match-string-symbols to)
409 (list from (car to) current-prefix-arg
410 (if (and transient-mark-mode mark-active)
411 (region-beginning))
412 (if (and transient-mark-mode mark-active)
413 (region-end))))))
414 (perform-replace regexp (cons 'replace-eval-replacement to-expr)
415 t 'literal delimited nil nil start end))
417 (defun map-query-replace-regexp (regexp to-strings &optional n start end)
418 "Replace some matches for REGEXP with various strings, in rotation.
419 The second argument TO-STRINGS contains the replacement strings, separated
420 by spaces. This command works like `query-replace-regexp' except that
421 each successive replacement uses the next successive replacement string,
422 wrapping around from the last such string to the first.
424 In Transient Mark mode, if the mark is active, operate on the contents
425 of the region. Otherwise, operate from point to the end of the buffer.
427 Non-interactively, TO-STRINGS may be a list of replacement strings.
429 Use \\<minibuffer-local-map>\\[next-history-element] \
430 to pull the last incremental search regexp to the minibuffer
431 that reads REGEXP.
433 A prefix argument N says to use each replacement string N times
434 before rotating to the next.
435 Fourth and fifth arg START and END specify the region to operate on."
436 (interactive
437 (let* ((from (read-regexp "Map query replace (regexp): " nil
438 query-replace-from-history-variable))
439 (to (read-from-minibuffer
440 (format "Query replace %s with (space-separated strings): "
441 (query-replace-descr from))
442 nil nil nil
443 query-replace-to-history-variable from t)))
444 (list from to
445 (and current-prefix-arg
446 (prefix-numeric-value current-prefix-arg))
447 (if (and transient-mark-mode mark-active)
448 (region-beginning))
449 (if (and transient-mark-mode mark-active)
450 (region-end)))))
451 (let (replacements)
452 (if (listp to-strings)
453 (setq replacements to-strings)
454 (while (/= (length to-strings) 0)
455 (if (string-match " " to-strings)
456 (setq replacements
457 (append replacements
458 (list (substring to-strings 0
459 (string-match " " to-strings))))
460 to-strings (substring to-strings
461 (1+ (string-match " " to-strings))))
462 (setq replacements (append replacements (list to-strings))
463 to-strings ""))))
464 (perform-replace regexp replacements t t nil n nil start end)))
466 (defun replace-string (from-string to-string &optional delimited start end)
467 "Replace occurrences of FROM-STRING with TO-STRING.
468 Preserve case in each match if `case-replace' and `case-fold-search'
469 are non-nil and FROM-STRING has no uppercase letters.
470 \(Preserving case means that if the string matched is all caps, or capitalized,
471 then its replacement is upcased or capitalized.)
473 If `replace-lax-whitespace' is non-nil, a space or spaces in the string
474 to be replaced will match a sequence of whitespace chars defined by the
475 regexp in `search-whitespace-regexp'.
477 In Transient Mark mode, if the mark is active, operate on the contents
478 of the region. Otherwise, operate from point to the end of the buffer.
480 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
481 only matches surrounded by word boundaries.
482 Fourth and fifth arg START and END specify the region to operate on.
484 Use \\<minibuffer-local-map>\\[next-history-element] \
485 to pull the last incremental search string to the minibuffer
486 that reads FROM-STRING.
488 This function is usually the wrong thing to use in a Lisp program.
489 What you probably want is a loop like this:
490 (while (search-forward FROM-STRING nil t)
491 (replace-match TO-STRING nil t))
492 which will run faster and will not set the mark or print anything.
493 \(You may need a more complex loop if FROM-STRING can match the null string
494 and TO-STRING is also null.)"
495 (interactive
496 (let ((common
497 (query-replace-read-args
498 (concat "Replace"
499 (if current-prefix-arg " word" "")
500 " string"
501 (if (and transient-mark-mode mark-active) " in region" ""))
502 nil)))
503 (list (nth 0 common) (nth 1 common) (nth 2 common)
504 (if (and transient-mark-mode mark-active)
505 (region-beginning))
506 (if (and transient-mark-mode mark-active)
507 (region-end)))))
508 (perform-replace from-string to-string nil nil delimited nil nil start end))
510 (defun replace-regexp (regexp to-string &optional delimited start end)
511 "Replace things after point matching REGEXP with TO-STRING.
512 Preserve case in each match if `case-replace' and `case-fold-search'
513 are non-nil and REGEXP has no uppercase letters.
515 If `replace-regexp-lax-whitespace' is non-nil, a space or spaces in the regexp
516 to be replaced will match a sequence of whitespace chars defined by the
517 regexp in `search-whitespace-regexp'.
519 In Transient Mark mode, if the mark is active, operate on the contents
520 of the region. Otherwise, operate from point to the end of the buffer.
522 Third arg DELIMITED (prefix arg if interactive), if non-nil, means replace
523 only matches surrounded by word boundaries.
524 Fourth and fifth arg START and END specify the region to operate on.
526 In TO-STRING, `\\&' stands for whatever matched the whole of REGEXP,
527 and `\\=\\N' (where N is a digit) stands for
528 whatever what matched the Nth `\\(...\\)' in REGEXP.
529 `\\?' lets you edit the replacement text in the minibuffer
530 at the given position for each replacement.
532 In interactive calls, the replacement text may contain `\\,'
533 followed by a Lisp expression used as part of the replacement
534 text. Inside of that expression, `\\&' is a string denoting the
535 whole match, `\\N' a partial match, `\\#&' and `\\#N' the respective
536 numeric values from `string-to-number', and `\\#' itself for
537 `replace-count', the number of replacements occurred so far.
539 If your Lisp expression is an identifier and the next letter in
540 the replacement string would be interpreted as part of it, you
541 can wrap it with an expression like `\\,(or \\#)'. Incidentally,
542 for this particular case you may also enter `\\#' in the
543 replacement text directly.
545 When using those Lisp features interactively in the replacement
546 text, TO-STRING is actually made a list instead of a string.
547 Use \\[repeat-complex-command] after this command for details.
549 Use \\<minibuffer-local-map>\\[next-history-element] \
550 to pull the last incremental search regexp to the minibuffer
551 that reads REGEXP.
553 This function is usually the wrong thing to use in a Lisp program.
554 What you probably want is a loop like this:
555 (while (re-search-forward REGEXP nil t)
556 (replace-match TO-STRING nil nil))
557 which will run faster and will not set the mark or print anything."
558 (interactive
559 (let ((common
560 (query-replace-read-args
561 (concat "Replace"
562 (if current-prefix-arg " word" "")
563 " regexp"
564 (if (and transient-mark-mode mark-active) " in region" ""))
565 t)))
566 (list (nth 0 common) (nth 1 common) (nth 2 common)
567 (if (and transient-mark-mode mark-active)
568 (region-beginning))
569 (if (and transient-mark-mode mark-active)
570 (region-end)))))
571 (perform-replace regexp to-string nil t delimited nil nil start end))
574 (defvar regexp-history nil
575 "History list for some commands that read regular expressions.
577 Maximum length of the history list is determined by the value
578 of `history-length', which see.")
580 (defvar occur-collect-regexp-history '("\\1")
581 "History of regexp for occur's collect operation")
583 (defun read-regexp (prompt &optional defaults history)
584 "Read and return a regular expression as a string.
585 When PROMPT doesn't end with a colon and space, it adds a final \": \".
586 If DEFAULTS is non-nil, it displays the first default in the prompt.
588 Non-nil optional arg DEFAULTS is a string or a list of strings that
589 are prepended to a list of standard default values, which include the
590 string at point, the last isearch regexp, the last isearch string, and
591 the last replacement regexp.
593 Non-nil HISTORY is a symbol to use for the history list.
594 If HISTORY is nil, `regexp-history' is used."
595 (let* ((default (if (consp defaults) (car defaults) defaults))
596 (defaults
597 (append
598 (if (listp defaults) defaults (list defaults))
599 (list (regexp-quote
600 (or (funcall (or find-tag-default-function
601 (get major-mode 'find-tag-default-function)
602 'find-tag-default))
603 ""))
604 (car regexp-search-ring)
605 (regexp-quote (or (car search-ring) ""))
606 (car (symbol-value
607 query-replace-from-history-variable)))))
608 (defaults (delete-dups (delq nil (delete "" defaults))))
609 ;; Do not automatically add default to the history for empty input.
610 (history-add-new-input nil)
611 (input (read-from-minibuffer
612 (cond ((string-match-p ":[ \t]*\\'" prompt)
613 prompt)
614 (default
615 (format "%s (default %s): " prompt
616 (query-replace-descr default)))
618 (format "%s: " prompt)))
619 nil nil nil (or history 'regexp-history) defaults t)))
620 (if (equal input "")
621 (or default input)
622 (prog1 input
623 (add-to-history (or history 'regexp-history) input)))))
626 (defalias 'delete-non-matching-lines 'keep-lines)
627 (defalias 'delete-matching-lines 'flush-lines)
628 (defalias 'count-matches 'how-many)
631 (defun keep-lines-read-args (prompt)
632 "Read arguments for `keep-lines' and friends.
633 Prompt for a regexp with PROMPT.
634 Value is a list, (REGEXP)."
635 (list (read-regexp prompt) nil nil t))
637 (defun keep-lines (regexp &optional rstart rend interactive)
638 "Delete all lines except those containing matches for REGEXP.
639 A match split across lines preserves all the lines it lies in.
640 When called from Lisp (and usually interactively as well, see below)
641 applies to all lines starting after point.
643 If REGEXP contains upper case characters (excluding those preceded by `\\')
644 and `search-upper-case' is non-nil, the matching is case-sensitive.
646 Second and third arg RSTART and REND specify the region to operate on.
647 This command operates on (the accessible part of) all lines whose
648 accessible part is entirely contained in the region determined by RSTART
649 and REND. (A newline ending a line counts as part of that line.)
651 Interactively, in Transient Mark mode when the mark is active, operate
652 on all lines whose accessible part is entirely contained in the region.
653 Otherwise, the command applies to all lines starting after point.
654 When calling this function from Lisp, you can pretend that it was
655 called interactively by passing a non-nil INTERACTIVE argument.
657 This function starts looking for the next match from the end of
658 the previous match. Hence, it ignores matches that overlap
659 a previously found match."
661 (interactive
662 (progn
663 (barf-if-buffer-read-only)
664 (keep-lines-read-args "Keep lines containing match for regexp")))
665 (if rstart
666 (progn
667 (goto-char (min rstart rend))
668 (setq rend
669 (progn
670 (save-excursion
671 (goto-char (max rstart rend))
672 (unless (or (bolp) (eobp))
673 (forward-line 0))
674 (point-marker)))))
675 (if (and interactive transient-mark-mode mark-active)
676 (setq rstart (region-beginning)
677 rend (progn
678 (goto-char (region-end))
679 (unless (or (bolp) (eobp))
680 (forward-line 0))
681 (point-marker)))
682 (setq rstart (point)
683 rend (point-max-marker)))
684 (goto-char rstart))
685 (save-excursion
686 (or (bolp) (forward-line 1))
687 (let ((start (point))
688 (case-fold-search
689 (if (and case-fold-search search-upper-case)
690 (isearch-no-upper-case-p regexp t)
691 case-fold-search)))
692 (while (< (point) rend)
693 ;; Start is first char not preserved by previous match.
694 (if (not (re-search-forward regexp rend 'move))
695 (delete-region start rend)
696 (let ((end (save-excursion (goto-char (match-beginning 0))
697 (forward-line 0)
698 (point))))
699 ;; Now end is first char preserved by the new match.
700 (if (< start end)
701 (delete-region start end))))
703 (setq start (save-excursion (forward-line 1) (point)))
704 ;; If the match was empty, avoid matching again at same place.
705 (and (< (point) rend)
706 (= (match-beginning 0) (match-end 0))
707 (forward-char 1)))))
708 (set-marker rend nil)
709 nil)
712 (defun flush-lines (regexp &optional rstart rend interactive)
713 "Delete lines containing matches for REGEXP.
714 When called from Lisp (and usually when called interactively as
715 well, see below), applies to the part of the buffer after point.
716 The line point is in is deleted if and only if it contains a
717 match for regexp starting after point.
719 If REGEXP contains upper case characters (excluding those preceded by `\\')
720 and `search-upper-case' is non-nil, the matching is case-sensitive.
722 Second and third arg RSTART and REND specify the region to operate on.
723 Lines partially contained in this region are deleted if and only if
724 they contain a match entirely contained in it.
726 Interactively, in Transient Mark mode when the mark is active, operate
727 on the contents of the region. Otherwise, operate from point to the
728 end of (the accessible portion of) the buffer. When calling this function
729 from Lisp, you can pretend that it was called interactively by passing
730 a non-nil INTERACTIVE argument.
732 If a match is split across lines, all the lines it lies in are deleted.
733 They are deleted _before_ looking for the next match. Hence, a match
734 starting on the same line at which another match ended is ignored."
736 (interactive
737 (progn
738 (barf-if-buffer-read-only)
739 (keep-lines-read-args "Flush lines containing match for regexp")))
740 (if rstart
741 (progn
742 (goto-char (min rstart rend))
743 (setq rend (copy-marker (max rstart rend))))
744 (if (and interactive transient-mark-mode mark-active)
745 (setq rstart (region-beginning)
746 rend (copy-marker (region-end)))
747 (setq rstart (point)
748 rend (point-max-marker)))
749 (goto-char rstart))
750 (let ((case-fold-search
751 (if (and case-fold-search search-upper-case)
752 (isearch-no-upper-case-p regexp t)
753 case-fold-search)))
754 (save-excursion
755 (while (and (< (point) rend)
756 (re-search-forward regexp rend t))
757 (delete-region (save-excursion (goto-char (match-beginning 0))
758 (forward-line 0)
759 (point))
760 (progn (forward-line 1) (point))))))
761 (set-marker rend nil)
762 nil)
765 (defun how-many (regexp &optional rstart rend interactive)
766 "Print and return number of matches for REGEXP following point.
767 When called from Lisp and INTERACTIVE is omitted or nil, just return
768 the number, do not print it; if INTERACTIVE is t, the function behaves
769 in all respects as if it had been called interactively.
771 If REGEXP contains upper case characters (excluding those preceded by `\\')
772 and `search-upper-case' is non-nil, the matching is case-sensitive.
774 Second and third arg RSTART and REND specify the region to operate on.
776 Interactively, in Transient Mark mode when the mark is active, operate
777 on the contents of the region. Otherwise, operate from point to the
778 end of (the accessible portion of) the buffer.
780 This function starts looking for the next match from the end of
781 the previous match. Hence, it ignores matches that overlap
782 a previously found match."
784 (interactive
785 (keep-lines-read-args "How many matches for regexp"))
786 (save-excursion
787 (if rstart
788 (progn
789 (goto-char (min rstart rend))
790 (setq rend (max rstart rend)))
791 (if (and interactive transient-mark-mode mark-active)
792 (setq rstart (region-beginning)
793 rend (region-end))
794 (setq rstart (point)
795 rend (point-max)))
796 (goto-char rstart))
797 (let ((count 0)
798 opoint
799 (case-fold-search
800 (if (and case-fold-search search-upper-case)
801 (isearch-no-upper-case-p regexp t)
802 case-fold-search)))
803 (while (and (< (point) rend)
804 (progn (setq opoint (point))
805 (re-search-forward regexp rend t)))
806 (if (= opoint (point))
807 (forward-char 1)
808 (setq count (1+ count))))
809 (when interactive (message "%d occurrence%s"
810 count
811 (if (= count 1) "" "s")))
812 count)))
815 (defvar occur-menu-map
816 (let ((map (make-sparse-keymap)))
817 (bindings--define-key map [next-error-follow-minor-mode]
818 '(menu-item "Auto Occurrence Display"
819 next-error-follow-minor-mode
820 :help "Display another occurrence when moving the cursor"
821 :button (:toggle . (and (boundp 'next-error-follow-minor-mode)
822 next-error-follow-minor-mode))))
823 (bindings--define-key map [separator-1] menu-bar-separator)
824 (bindings--define-key map [kill-this-buffer]
825 '(menu-item "Kill Occur Buffer" kill-this-buffer
826 :help "Kill the current *Occur* buffer"))
827 (bindings--define-key map [quit-window]
828 '(menu-item "Quit Occur Window" quit-window
829 :help "Quit the current *Occur* buffer. Bury it, and maybe delete the selected frame"))
830 (bindings--define-key map [revert-buffer]
831 '(menu-item "Revert Occur Buffer" revert-buffer
832 :help "Replace the text in the *Occur* buffer with the results of rerunning occur"))
833 (bindings--define-key map [clone-buffer]
834 '(menu-item "Clone Occur Buffer" clone-buffer
835 :help "Create and return a twin copy of the current *Occur* buffer"))
836 (bindings--define-key map [occur-rename-buffer]
837 '(menu-item "Rename Occur Buffer" occur-rename-buffer
838 :help "Rename the current *Occur* buffer to *Occur: original-buffer-name*."))
839 (bindings--define-key map [occur-edit-buffer]
840 '(menu-item "Edit Occur Buffer" occur-edit-mode
841 :help "Edit the *Occur* buffer and apply changes to the original buffers."))
842 (bindings--define-key map [separator-2] menu-bar-separator)
843 (bindings--define-key map [occur-mode-goto-occurrence-other-window]
844 '(menu-item "Go To Occurrence Other Window" occur-mode-goto-occurrence-other-window
845 :help "Go to the occurrence the current line describes, in another window"))
846 (bindings--define-key map [occur-mode-goto-occurrence]
847 '(menu-item "Go To Occurrence" occur-mode-goto-occurrence
848 :help "Go to the occurrence the current line describes"))
849 (bindings--define-key map [occur-mode-display-occurrence]
850 '(menu-item "Display Occurrence" occur-mode-display-occurrence
851 :help "Display in another window the occurrence the current line describes"))
852 (bindings--define-key map [occur-next]
853 '(menu-item "Move to Next Match" occur-next
854 :help "Move to the Nth (default 1) next match in an Occur mode buffer"))
855 (bindings--define-key map [occur-prev]
856 '(menu-item "Move to Previous Match" occur-prev
857 :help "Move to the Nth (default 1) previous match in an Occur mode buffer"))
858 map)
859 "Menu keymap for `occur-mode'.")
861 (defvar occur-mode-map
862 (let ((map (make-sparse-keymap)))
863 ;; We use this alternative name, so we can use \\[occur-mode-mouse-goto].
864 (define-key map [mouse-2] 'occur-mode-mouse-goto)
865 (define-key map "\C-c\C-c" 'occur-mode-goto-occurrence)
866 (define-key map "e" 'occur-edit-mode)
867 (define-key map "\C-m" 'occur-mode-goto-occurrence)
868 (define-key map "o" 'occur-mode-goto-occurrence-other-window)
869 (define-key map "\C-o" 'occur-mode-display-occurrence)
870 (define-key map "\M-n" 'occur-next)
871 (define-key map "\M-p" 'occur-prev)
872 (define-key map "r" 'occur-rename-buffer)
873 (define-key map "c" 'clone-buffer)
874 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
875 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
876 map)
877 "Keymap for `occur-mode'.")
879 (defvar occur-revert-arguments nil
880 "Arguments to pass to `occur-1' to revert an Occur mode buffer.
881 See `occur-revert-function'.")
882 (make-variable-buffer-local 'occur-revert-arguments)
883 (put 'occur-revert-arguments 'permanent-local t)
885 (defcustom occur-mode-hook '(turn-on-font-lock)
886 "Hook run when entering Occur mode."
887 :type 'hook
888 :group 'matching)
890 (defcustom occur-hook nil
891 "Hook run by Occur when there are any matches."
892 :type 'hook
893 :group 'matching)
895 (defcustom occur-mode-find-occurrence-hook nil
896 "Hook run by Occur after locating an occurrence.
897 This will be called with the cursor position at the occurrence. An application
898 for this is to reveal context in an outline-mode when the occurrence is hidden."
899 :type 'hook
900 :group 'matching)
902 (put 'occur-mode 'mode-class 'special)
903 (define-derived-mode occur-mode special-mode "Occur"
904 "Major mode for output from \\[occur].
905 \\<occur-mode-map>Move point to one of the items in this buffer, then use
906 \\[occur-mode-goto-occurrence] to go to the occurrence that the item refers to.
907 Alternatively, click \\[occur-mode-mouse-goto] on an item to go to it.
909 \\{occur-mode-map}"
910 (set (make-local-variable 'revert-buffer-function) 'occur-revert-function)
911 (setq next-error-function 'occur-next-error))
914 ;;; Occur Edit mode
916 (defvar occur-edit-mode-map
917 (let ((map (make-sparse-keymap)))
918 (set-keymap-parent map text-mode-map)
919 (define-key map [mouse-2] 'occur-mode-mouse-goto)
920 (define-key map "\C-c\C-c" 'occur-cease-edit)
921 (define-key map "\C-o" 'occur-mode-display-occurrence)
922 (define-key map "\C-c\C-f" 'next-error-follow-minor-mode)
923 (bindings--define-key map [menu-bar occur] (cons "Occur" occur-menu-map))
924 map)
925 "Keymap for `occur-edit-mode'.")
927 (define-derived-mode occur-edit-mode occur-mode "Occur-Edit"
928 "Major mode for editing *Occur* buffers.
929 In this mode, changes to the *Occur* buffer are also applied to
930 the originating buffer.
932 To return to ordinary Occur mode, use \\[occur-cease-edit]."
933 (setq buffer-read-only nil)
934 (add-hook 'after-change-functions 'occur-after-change-function nil t)
935 (message (substitute-command-keys
936 "Editing: Type \\[occur-cease-edit] to return to Occur mode.")))
938 (defun occur-cease-edit ()
939 "Switch from Occur Edit mode to Occur mode."
940 (interactive)
941 (when (derived-mode-p 'occur-edit-mode)
942 (occur-mode)
943 (message "Switching to Occur mode.")))
945 (defun occur-after-change-function (beg end length)
946 (save-excursion
947 (goto-char beg)
948 (let* ((line-beg (line-beginning-position))
949 (m (get-text-property line-beg 'occur-target))
950 (buf (marker-buffer m))
951 col)
952 (when (and (get-text-property line-beg 'occur-prefix)
953 (not (get-text-property end 'occur-prefix)))
954 (when (= length 0)
955 ;; Apply occur-target property to inserted (e.g. yanked) text.
956 (put-text-property beg end 'occur-target m)
957 ;; Did we insert a newline? Occur Edit mode can't create new
958 ;; Occur entries; just discard everything after the newline.
959 (save-excursion
960 (and (search-forward "\n" end t)
961 (delete-region (1- (point)) end))))
962 (let* ((line (- (line-number-at-pos)
963 (line-number-at-pos (window-start))))
964 (readonly (with-current-buffer buf buffer-read-only))
965 (win (or (get-buffer-window buf)
966 (display-buffer buf
967 '(nil (inhibit-same-window . t)
968 (inhibit-switch-frame . t)))))
969 (line-end (line-end-position))
970 (text (save-excursion
971 (goto-char (next-single-property-change
972 line-beg 'occur-prefix nil
973 line-end))
974 (setq col (- (point) line-beg))
975 (buffer-substring-no-properties (point) line-end))))
976 (with-selected-window win
977 (goto-char m)
978 (recenter line)
979 (if readonly
980 (message "Buffer `%s' is read only." buf)
981 (delete-region (line-beginning-position) (line-end-position))
982 (insert text))
983 (move-to-column col)))))))
986 (defun occur-revert-function (_ignore1 _ignore2)
987 "Handle `revert-buffer' for Occur mode buffers."
988 (apply 'occur-1 (append occur-revert-arguments (list (buffer-name)))))
990 (defun occur-mode-find-occurrence ()
991 (let ((pos (get-text-property (point) 'occur-target)))
992 (unless pos
993 (error "No occurrence on this line"))
994 (unless (buffer-live-p (marker-buffer pos))
995 (error "Buffer for this occurrence was killed"))
996 pos))
998 (defalias 'occur-mode-mouse-goto 'occur-mode-goto-occurrence)
999 (defun occur-mode-goto-occurrence (&optional event)
1000 "Go to the occurrence on the current line."
1001 (interactive (list last-nonmenu-event))
1002 (let ((pos
1003 (if (null event)
1004 ;; Actually `event-end' works correctly with a nil argument as
1005 ;; well, so we could dispense with this test, but let's not
1006 ;; rely on this undocumented behavior.
1007 (occur-mode-find-occurrence)
1008 (with-current-buffer (window-buffer (posn-window (event-end event)))
1009 (save-excursion
1010 (goto-char (posn-point (event-end event)))
1011 (occur-mode-find-occurrence))))))
1012 (pop-to-buffer (marker-buffer pos))
1013 (goto-char pos)
1014 (run-hooks 'occur-mode-find-occurrence-hook)))
1016 (defun occur-mode-goto-occurrence-other-window ()
1017 "Go to the occurrence the current line describes, in another window."
1018 (interactive)
1019 (let ((pos (occur-mode-find-occurrence)))
1020 (switch-to-buffer-other-window (marker-buffer pos))
1021 (goto-char pos)
1022 (run-hooks 'occur-mode-find-occurrence-hook)))
1024 (defun occur-mode-display-occurrence ()
1025 "Display in another window the occurrence the current line describes."
1026 (interactive)
1027 (let ((pos (occur-mode-find-occurrence))
1028 window)
1029 (setq window (display-buffer (marker-buffer pos) t))
1030 ;; This is the way to set point in the proper window.
1031 (save-selected-window
1032 (select-window window)
1033 (goto-char pos)
1034 (run-hooks 'occur-mode-find-occurrence-hook))))
1036 (defun occur-find-match (n search message)
1037 (if (not n) (setq n 1))
1038 (let ((r))
1039 (while (> n 0)
1040 (setq r (funcall search (point) 'occur-match))
1041 (and r
1042 (get-text-property r 'occur-match)
1043 (setq r (funcall search r 'occur-match)))
1044 (if r
1045 (goto-char r)
1046 (error message))
1047 (setq n (1- n)))))
1049 (defun occur-next (&optional n)
1050 "Move to the Nth (default 1) next match in an Occur mode buffer."
1051 (interactive "p")
1052 (occur-find-match n #'next-single-property-change "No more matches"))
1054 (defun occur-prev (&optional n)
1055 "Move to the Nth (default 1) previous match in an Occur mode buffer."
1056 (interactive "p")
1057 (occur-find-match n #'previous-single-property-change "No earlier matches"))
1059 (defun occur-next-error (&optional argp reset)
1060 "Move to the Nth (default 1) next match in an Occur mode buffer.
1061 Compatibility function for \\[next-error] invocations."
1062 (interactive "p")
1063 ;; we need to run occur-find-match from within the Occur buffer
1064 (with-current-buffer
1065 ;; Choose the buffer and make it current.
1066 (if (next-error-buffer-p (current-buffer))
1067 (current-buffer)
1068 (next-error-find-buffer nil nil
1069 (lambda ()
1070 (eq major-mode 'occur-mode))))
1072 (goto-char (cond (reset (point-min))
1073 ((< argp 0) (line-beginning-position))
1074 ((> argp 0) (line-end-position))
1075 ((point))))
1076 (occur-find-match
1077 (abs argp)
1078 (if (> 0 argp)
1079 #'previous-single-property-change
1080 #'next-single-property-change)
1081 "No more matches")
1082 ;; In case the *Occur* buffer is visible in a nonselected window.
1083 (let ((win (get-buffer-window (current-buffer) t)))
1084 (if win (set-window-point win (point))))
1085 (occur-mode-goto-occurrence)))
1087 (defface match
1088 '((((class color) (min-colors 88) (background light))
1089 :background "yellow1")
1090 (((class color) (min-colors 88) (background dark))
1091 :background "RoyalBlue3")
1092 (((class color) (min-colors 8) (background light))
1093 :background "yellow" :foreground "black")
1094 (((class color) (min-colors 8) (background dark))
1095 :background "blue" :foreground "white")
1096 (((type tty) (class mono))
1097 :inverse-video t)
1098 (t :background "gray"))
1099 "Face used to highlight matches permanently."
1100 :group 'matching
1101 :version "22.1")
1103 (defcustom list-matching-lines-default-context-lines 0
1104 "Default number of context lines included around `list-matching-lines' matches.
1105 A negative number means to include that many lines before the match.
1106 A positive number means to include that many lines both before and after."
1107 :type 'integer
1108 :group 'matching)
1110 (defalias 'list-matching-lines 'occur)
1112 (defcustom list-matching-lines-face 'match
1113 "Face used by \\[list-matching-lines] to show the text that matches.
1114 If the value is nil, don't highlight the matching portions specially."
1115 :type 'face
1116 :group 'matching)
1118 (defcustom list-matching-lines-buffer-name-face 'underline
1119 "Face used by \\[list-matching-lines] to show the names of buffers.
1120 If the value is nil, don't highlight the buffer names specially."
1121 :type 'face
1122 :group 'matching)
1124 (defcustom occur-excluded-properties
1125 '(read-only invisible intangible field mouse-face help-echo local-map keymap
1126 yank-handler follow-link)
1127 "Text properties to discard when copying lines to the *Occur* buffer.
1128 The value should be a list of text properties to discard or t,
1129 which means to discard all text properties."
1130 :type '(choice (const :tag "All" t) (repeat symbol))
1131 :group 'matching
1132 :version "22.1")
1134 (defun occur-read-primary-args ()
1135 (let* ((perform-collect (consp current-prefix-arg))
1136 (regexp (read-regexp (if perform-collect
1137 "Collect strings matching regexp"
1138 "List lines matching regexp")
1139 (car regexp-history))))
1140 (list regexp
1141 (if perform-collect
1142 ;; Perform collect operation
1143 (if (zerop (regexp-opt-depth regexp))
1144 ;; No subexpression so collect the entire match.
1145 "\\&"
1146 ;; Get the regexp for collection pattern.
1147 (let ((default (car occur-collect-regexp-history)))
1148 (read-regexp
1149 (format "Regexp to collect (default %s): " default)
1150 default 'occur-collect-regexp-history)))
1151 ;; Otherwise normal occur takes numerical prefix argument.
1152 (when current-prefix-arg
1153 (prefix-numeric-value current-prefix-arg))))))
1155 (defun occur-rename-buffer (&optional unique-p interactive-p)
1156 "Rename the current *Occur* buffer to *Occur: original-buffer-name*.
1157 Here `original-buffer-name' is the buffer name where Occur was originally run.
1158 When given the prefix argument, or called non-interactively, the renaming
1159 will not clobber the existing buffer(s) of that name, but use
1160 `generate-new-buffer-name' instead. You can add this to `occur-hook'
1161 if you always want a separate *Occur* buffer for each buffer where you
1162 invoke `occur'."
1163 (interactive "P\np")
1164 (with-current-buffer
1165 (if (eq major-mode 'occur-mode) (current-buffer) (get-buffer "*Occur*"))
1166 (rename-buffer (concat "*Occur: "
1167 (mapconcat #'buffer-name
1168 (car (cddr occur-revert-arguments)) "/")
1169 "*")
1170 (or unique-p (not interactive-p)))))
1172 (defun occur (regexp &optional nlines)
1173 "Show all lines in the current buffer containing a match for REGEXP.
1174 If a match spreads across multiple lines, all those lines are shown.
1176 Each line is displayed with NLINES lines before and after, or -NLINES
1177 before if NLINES is negative.
1178 NLINES defaults to `list-matching-lines-default-context-lines'.
1179 Interactively it is the prefix arg.
1181 The lines are shown in a buffer named `*Occur*'.
1182 It serves as a menu to find any of the occurrences in this buffer.
1183 \\<occur-mode-map>\\[describe-mode] in that buffer will explain how.
1185 If REGEXP contains upper case characters (excluding those preceded by `\\')
1186 and `search-upper-case' is non-nil, the matching is case-sensitive.
1188 When NLINES is a string or when the function is called
1189 interactively with prefix argument without a number (`C-u' alone
1190 as prefix) the matching strings are collected into the `*Occur*'
1191 buffer by using NLINES as a replacement regexp. NLINES may
1192 contain \\& and \\N which convention follows `replace-match'.
1193 For example, providing \"defun\\s +\\(\\S +\\)\" for REGEXP and
1194 \"\\1\" for NLINES collects all the function names in a lisp
1195 program. When there is no parenthesized subexpressions in REGEXP
1196 the entire match is collected. In any case the searched buffer
1197 is not modified."
1198 (interactive (occur-read-primary-args))
1199 (occur-1 regexp nlines (list (current-buffer))))
1201 (defvar ido-ignore-item-temp-list)
1203 (defun multi-occur (bufs regexp &optional nlines)
1204 "Show all lines in buffers BUFS containing a match for REGEXP.
1205 This function acts on multiple buffers; otherwise, it is exactly like
1206 `occur'. When you invoke this command interactively, you must specify
1207 the buffer names that you want, one by one.
1208 See also `multi-occur-in-matching-buffers'."
1209 (interactive
1210 (cons
1211 (let* ((bufs (list (read-buffer "First buffer to search: "
1212 (current-buffer) t)))
1213 (buf nil)
1214 (ido-ignore-item-temp-list bufs))
1215 (while (not (string-equal
1216 (setq buf (read-buffer
1217 (if (eq read-buffer-function 'ido-read-buffer)
1218 "Next buffer to search (C-j to end): "
1219 "Next buffer to search (RET to end): ")
1220 nil t))
1221 ""))
1222 (add-to-list 'bufs buf)
1223 (setq ido-ignore-item-temp-list bufs))
1224 (nreverse (mapcar #'get-buffer bufs)))
1225 (occur-read-primary-args)))
1226 (occur-1 regexp nlines bufs))
1228 (defun multi-occur-in-matching-buffers (bufregexp regexp &optional allbufs)
1229 "Show all lines matching REGEXP in buffers specified by BUFREGEXP.
1230 Normally BUFREGEXP matches against each buffer's visited file name,
1231 but if you specify a prefix argument, it matches against the buffer name.
1232 See also `multi-occur'."
1233 (interactive
1234 (cons
1235 (let* ((default (car regexp-history))
1236 (input
1237 (read-regexp
1238 (if current-prefix-arg
1239 "List lines in buffers whose names match regexp: "
1240 "List lines in buffers whose filenames match regexp: "))))
1241 (if (equal input "")
1242 default
1243 input))
1244 (occur-read-primary-args)))
1245 (when bufregexp
1246 (occur-1 regexp nil
1247 (delq nil
1248 (mapcar (lambda (buf)
1249 (when (if allbufs
1250 (string-match bufregexp
1251 (buffer-name buf))
1252 (and (buffer-file-name buf)
1253 (string-match bufregexp
1254 (buffer-file-name buf))))
1255 buf))
1256 (buffer-list))))))
1258 (defun occur-1 (regexp nlines bufs &optional buf-name)
1259 (unless (and regexp (not (equal regexp "")))
1260 (error "Occur doesn't work with the empty regexp"))
1261 (unless buf-name
1262 (setq buf-name "*Occur*"))
1263 (let (occur-buf
1264 (active-bufs (delq nil (mapcar #'(lambda (buf)
1265 (when (buffer-live-p buf) buf))
1266 bufs))))
1267 ;; Handle the case where one of the buffers we're searching is the
1268 ;; output buffer. Just rename it.
1269 (when (member buf-name (mapcar 'buffer-name active-bufs))
1270 (with-current-buffer (get-buffer buf-name)
1271 (rename-uniquely)))
1273 ;; Now find or create the output buffer.
1274 ;; If we just renamed that buffer, we will make a new one here.
1275 (setq occur-buf (get-buffer-create buf-name))
1277 (with-current-buffer occur-buf
1278 (if (stringp nlines)
1279 (fundamental-mode) ;; This is for collect operation.
1280 (occur-mode))
1281 (let ((inhibit-read-only t)
1282 ;; Don't generate undo entries for creation of the initial contents.
1283 (buffer-undo-list t))
1284 (erase-buffer)
1285 (let ((count
1286 (if (stringp nlines)
1287 ;; Treat nlines as a regexp to collect.
1288 (let ((bufs active-bufs)
1289 (count 0))
1290 (while bufs
1291 (with-current-buffer (car bufs)
1292 (save-excursion
1293 (goto-char (point-min))
1294 (while (re-search-forward regexp nil t)
1295 ;; Insert the replacement regexp.
1296 (let ((str (match-substitute-replacement nlines)))
1297 (if str
1298 (with-current-buffer occur-buf
1299 (insert str)
1300 (setq count (1+ count))
1301 (or (zerop (current-column))
1302 (insert "\n"))))))))
1303 (setq bufs (cdr bufs)))
1304 count)
1305 ;; Perform normal occur.
1306 (occur-engine
1307 regexp active-bufs occur-buf
1308 (or nlines list-matching-lines-default-context-lines)
1309 (if (and case-fold-search search-upper-case)
1310 (isearch-no-upper-case-p regexp t)
1311 case-fold-search)
1312 list-matching-lines-buffer-name-face
1313 nil list-matching-lines-face
1314 (not (eq occur-excluded-properties t))))))
1315 (let* ((bufcount (length active-bufs))
1316 (diff (- (length bufs) bufcount)))
1317 (message "Searched %d buffer%s%s; %s match%s%s"
1318 bufcount (if (= bufcount 1) "" "s")
1319 (if (zerop diff) "" (format " (%d killed)" diff))
1320 (if (zerop count) "no" (format "%d" count))
1321 (if (= count 1) "" "es")
1322 ;; Don't display regexp if with remaining text
1323 ;; it is longer than window-width.
1324 (if (> (+ (length regexp) 42) (window-width))
1325 "" (format " for `%s'" (query-replace-descr regexp)))))
1326 (setq occur-revert-arguments (list regexp nlines bufs))
1327 (if (= count 0)
1328 (kill-buffer occur-buf)
1329 (display-buffer occur-buf)
1330 (setq next-error-last-buffer occur-buf)
1331 (setq buffer-read-only t)
1332 (set-buffer-modified-p nil)
1333 (run-hooks 'occur-hook)))))))
1335 (defun occur-engine (regexp buffers out-buf nlines case-fold
1336 title-face prefix-face match-face keep-props)
1337 (with-current-buffer out-buf
1338 (let ((globalcount 0)
1339 (coding nil)
1340 (case-fold-search case-fold))
1341 ;; Map over all the buffers
1342 (dolist (buf buffers)
1343 (when (buffer-live-p buf)
1344 (let ((matches 0) ;; count of matched lines
1345 (lines 1) ;; line count
1346 (prev-after-lines nil) ;; context lines of prev match
1347 (prev-lines nil) ;; line number of prev match endpt
1348 (matchbeg 0)
1349 (origpt nil)
1350 (begpt nil)
1351 (endpt nil)
1352 (marker nil)
1353 (curstring "")
1354 (ret nil)
1355 (inhibit-field-text-motion t)
1356 (headerpt (with-current-buffer out-buf (point))))
1357 (with-current-buffer buf
1358 (or coding
1359 ;; Set CODING only if the current buffer locally
1360 ;; binds buffer-file-coding-system.
1361 (not (local-variable-p 'buffer-file-coding-system))
1362 (setq coding buffer-file-coding-system))
1363 (save-excursion
1364 (goto-char (point-min)) ;; begin searching in the buffer
1365 (while (not (eobp))
1366 (setq origpt (point))
1367 (when (setq endpt (re-search-forward regexp nil t))
1368 (setq matches (1+ matches)) ;; increment match count
1369 (setq matchbeg (match-beginning 0))
1370 ;; Get beginning of first match line and end of the last.
1371 (save-excursion
1372 (goto-char matchbeg)
1373 (setq begpt (line-beginning-position))
1374 (goto-char endpt)
1375 (setq endpt (line-end-position)))
1376 ;; Sum line numbers up to the first match line.
1377 (setq lines (+ lines (count-lines origpt begpt)))
1378 (setq marker (make-marker))
1379 (set-marker marker matchbeg)
1380 (setq curstring (occur-engine-line begpt endpt keep-props))
1381 ;; Highlight the matches
1382 (let ((len (length curstring))
1383 (start 0))
1384 (while (and (< start len)
1385 (string-match regexp curstring start))
1386 (add-text-properties
1387 (match-beginning 0) (match-end 0)
1388 (append
1389 `(occur-match t)
1390 (when match-face
1391 ;; Use `face' rather than `font-lock-face' here
1392 ;; so as to override faces copied from the buffer.
1393 `(face ,match-face)))
1394 curstring)
1395 (setq start (match-end 0))))
1396 ;; Generate the string to insert for this match
1397 (let* ((match-prefix
1398 ;; Using 7 digits aligns tabs properly.
1399 (apply #'propertize (format "%7d:" lines)
1400 (append
1401 (when prefix-face
1402 `(font-lock-face prefix-face))
1403 `(occur-prefix t mouse-face (highlight)
1404 ;; Allow insertion of text at
1405 ;; the end of the prefix (for
1406 ;; Occur Edit mode).
1407 front-sticky t rear-nonsticky t
1408 occur-target ,marker follow-link t
1409 help-echo "mouse-2: go to this occurrence"))))
1410 (match-str
1411 ;; We don't put `mouse-face' on the newline,
1412 ;; because that loses. And don't put it
1413 ;; on context lines to reduce flicker.
1414 (propertize curstring 'mouse-face (list 'highlight)
1415 'occur-target marker
1416 'follow-link t
1417 'help-echo
1418 "mouse-2: go to this occurrence"))
1419 (out-line
1420 (concat
1421 match-prefix
1422 ;; Add non-numeric prefix to all non-first lines
1423 ;; of multi-line matches.
1424 (replace-regexp-in-string
1425 "\n"
1426 "\n :"
1427 match-str)
1428 ;; Add marker at eol, but no mouse props.
1429 (propertize "\n" 'occur-target marker)))
1430 (data
1431 (if (= nlines 0)
1432 ;; The simple display style
1433 out-line
1434 ;; The complex multi-line display style.
1435 (setq ret (occur-context-lines
1436 out-line nlines keep-props begpt endpt
1437 lines prev-lines prev-after-lines))
1438 ;; Set first elem of the returned list to `data',
1439 ;; and the second elem to `prev-after-lines'.
1440 (setq prev-after-lines (nth 1 ret))
1441 (nth 0 ret))))
1442 ;; Actually insert the match display data
1443 (with-current-buffer out-buf
1444 (insert data)))
1445 (goto-char endpt))
1446 (if endpt
1447 (progn
1448 ;; Sum line numbers between first and last match lines.
1449 (setq lines (+ lines (count-lines begpt endpt)
1450 ;; Add 1 for empty last match line since
1451 ;; count-lines returns 1 line less.
1452 (if (and (bolp) (eolp)) 1 0)))
1453 ;; On to the next match...
1454 (forward-line 1))
1455 (goto-char (point-max)))
1456 (setq prev-lines (1- lines)))
1457 ;; Flush remaining context after-lines.
1458 (when prev-after-lines
1459 (with-current-buffer out-buf
1460 (insert (apply #'concat (occur-engine-add-prefix
1461 prev-after-lines)))))))
1462 (when (not (zerop matches)) ;; is the count zero?
1463 (setq globalcount (+ globalcount matches))
1464 (with-current-buffer out-buf
1465 (goto-char headerpt)
1466 (let ((beg (point))
1467 end)
1468 (insert (propertize
1469 (format "%d match%s%s in buffer: %s\n"
1470 matches (if (= matches 1) "" "es")
1471 ;; Don't display regexp for multi-buffer.
1472 (if (> (length buffers) 1)
1473 "" (format " for \"%s\""
1474 (query-replace-descr regexp)))
1475 (buffer-name buf))
1476 'read-only t))
1477 (setq end (point))
1478 (add-text-properties beg end
1479 (append
1480 (when title-face
1481 `(font-lock-face ,title-face))
1482 `(occur-title ,buf))))
1483 (goto-char (point-min)))))))
1484 ;; Display total match count and regexp for multi-buffer.
1485 (when (and (not (zerop globalcount)) (> (length buffers) 1))
1486 (goto-char (point-min))
1487 (let ((beg (point))
1488 end)
1489 (insert (format "%d match%s total for \"%s\":\n"
1490 globalcount (if (= globalcount 1) "" "es")
1491 (query-replace-descr regexp)))
1492 (setq end (point))
1493 (add-text-properties beg end (when title-face
1494 `(font-lock-face ,title-face))))
1495 (goto-char (point-min)))
1496 (if coding
1497 ;; CODING is buffer-file-coding-system of the first buffer
1498 ;; that locally binds it. Let's use it also for the output
1499 ;; buffer.
1500 (set-buffer-file-coding-system coding))
1501 ;; Return the number of matches
1502 globalcount)))
1504 (defun occur-engine-line (beg end &optional keep-props)
1505 (if (and keep-props (if (boundp 'jit-lock-mode) jit-lock-mode)
1506 (text-property-not-all beg end 'fontified t))
1507 (if (fboundp 'jit-lock-fontify-now)
1508 (jit-lock-fontify-now beg end)))
1509 (if (and keep-props (not (eq occur-excluded-properties t)))
1510 (let ((str (buffer-substring beg end)))
1511 (remove-list-of-text-properties
1512 0 (length str) occur-excluded-properties str)
1513 str)
1514 (buffer-substring-no-properties beg end)))
1516 (defun occur-engine-add-prefix (lines)
1517 (mapcar
1518 #'(lambda (line)
1519 (concat " :" line "\n"))
1520 lines))
1522 (defun occur-accumulate-lines (count &optional keep-props pt)
1523 (save-excursion
1524 (when pt
1525 (goto-char pt))
1526 (let ((forwardp (> count 0))
1527 result beg end moved)
1528 (while (not (or (zerop count)
1529 (if forwardp
1530 (eobp)
1531 (and (bobp) (not moved)))))
1532 (setq count (+ count (if forwardp -1 1)))
1533 (setq beg (line-beginning-position)
1534 end (line-end-position))
1535 (push (occur-engine-line beg end keep-props) result)
1536 (setq moved (= 0 (forward-line (if forwardp 1 -1)))))
1537 (nreverse result))))
1539 ;; Generate context display for occur.
1540 ;; OUT-LINE is the line where the match is.
1541 ;; NLINES and KEEP-PROPS are args to occur-engine.
1542 ;; LINES is line count of the current match,
1543 ;; PREV-LINES is line count of the previous match,
1544 ;; PREV-AFTER-LINES is a list of after-context lines of the previous match.
1545 ;; Generate a list of lines, add prefixes to all but OUT-LINE,
1546 ;; then concatenate them all together.
1547 (defun occur-context-lines (out-line nlines keep-props begpt endpt
1548 lines prev-lines prev-after-lines)
1549 ;; Find after- and before-context lines of the current match.
1550 (let ((before-lines
1551 (nreverse (cdr (occur-accumulate-lines
1552 (- (1+ (abs nlines))) keep-props begpt))))
1553 (after-lines
1554 (cdr (occur-accumulate-lines
1555 (1+ nlines) keep-props endpt)))
1556 separator)
1558 ;; Combine after-lines of the previous match
1559 ;; with before-lines of the current match.
1561 (when prev-after-lines
1562 ;; Don't overlap prev after-lines with current before-lines.
1563 (if (>= (+ prev-lines (length prev-after-lines))
1564 (- lines (length before-lines)))
1565 (setq prev-after-lines
1566 (butlast prev-after-lines
1567 (- (length prev-after-lines)
1568 (- lines prev-lines (length before-lines) 1))))
1569 ;; Separate non-overlapping context lines with a dashed line.
1570 (setq separator "-------\n")))
1572 (when prev-lines
1573 ;; Don't overlap current before-lines with previous match line.
1574 (if (<= (- lines (length before-lines))
1575 prev-lines)
1576 (setq before-lines
1577 (nthcdr (- (length before-lines)
1578 (- lines prev-lines 1))
1579 before-lines))
1580 ;; Separate non-overlapping before-context lines.
1581 (unless (> nlines 0)
1582 (setq separator "-------\n"))))
1584 (list
1585 ;; Return a list where the first element is the output line.
1586 (apply #'concat
1587 (append
1588 (and prev-after-lines
1589 (occur-engine-add-prefix prev-after-lines))
1590 (and separator (list separator))
1591 (occur-engine-add-prefix before-lines)
1592 (list out-line)))
1593 ;; And the second element is the list of context after-lines.
1594 (if (> nlines 0) after-lines))))
1597 ;; It would be nice to use \\[...], but there is no reasonable way
1598 ;; to make that display both SPC and Y.
1599 (defconst query-replace-help
1600 "Type Space or `y' to replace one match, Delete or `n' to skip to next,
1601 RET or `q' to exit, Period to replace one match and exit,
1602 Comma to replace but not move point immediately,
1603 C-r to enter recursive edit (\\[exit-recursive-edit] to get out again),
1604 C-w to delete match and recursive edit,
1605 C-l to clear the screen, redisplay, and offer same replacement again,
1606 ! to replace all remaining matches in this buffer with no more questions,
1607 ^ to move point back to previous match,
1608 E to edit the replacement string.
1609 In multi-buffer replacements type `Y' to replace all remaining
1610 matches in all remaining buffers with no more questions,
1611 `N' to skip to the next buffer without replacing remaining matches
1612 in the current buffer."
1613 "Help message while in `query-replace'.")
1615 (defvar query-replace-map
1616 (let ((map (make-sparse-keymap)))
1617 (define-key map " " 'act)
1618 (define-key map "\d" 'skip)
1619 (define-key map [delete] 'skip)
1620 (define-key map [backspace] 'skip)
1621 (define-key map "y" 'act)
1622 (define-key map "n" 'skip)
1623 (define-key map "Y" 'act)
1624 (define-key map "N" 'skip)
1625 (define-key map "e" 'edit-replacement)
1626 (define-key map "E" 'edit-replacement)
1627 (define-key map "," 'act-and-show)
1628 (define-key map "q" 'exit)
1629 (define-key map "\r" 'exit)
1630 (define-key map [return] 'exit)
1631 (define-key map "." 'act-and-exit)
1632 (define-key map "\C-r" 'edit)
1633 (define-key map "\C-w" 'delete-and-edit)
1634 (define-key map "\C-l" 'recenter)
1635 (define-key map "!" 'automatic)
1636 (define-key map "^" 'backup)
1637 (define-key map "\C-h" 'help)
1638 (define-key map [f1] 'help)
1639 (define-key map [help] 'help)
1640 (define-key map "?" 'help)
1641 (define-key map "\C-g" 'quit)
1642 (define-key map "\C-]" 'quit)
1643 (define-key map "\C-v" 'scroll-up)
1644 (define-key map "\M-v" 'scroll-down)
1645 (define-key map [next] 'scroll-up)
1646 (define-key map [prior] 'scroll-down)
1647 (define-key map [?\C-\M-v] 'scroll-other-window)
1648 (define-key map [M-next] 'scroll-other-window)
1649 (define-key map [?\C-\M-\S-v] 'scroll-other-window-down)
1650 (define-key map [M-prior] 'scroll-other-window-down)
1651 ;; Binding ESC would prohibit the M-v binding. Instead, callers
1652 ;; should check for ESC specially.
1653 ;; (define-key map "\e" 'exit-prefix)
1654 (define-key map [escape] 'exit-prefix)
1655 map)
1656 "Keymap of responses to questions posed by commands like `query-replace'.
1657 The \"bindings\" in this map are not commands; they are answers.
1658 The valid answers include `act', `skip', `act-and-show',
1659 `act-and-exit', `exit', `exit-prefix', `recenter', `scroll-up',
1660 `scroll-down', `scroll-other-window', `scroll-other-window-down',
1661 `edit', `edit-replacement', `delete-and-edit', `automatic',
1662 `backup', `quit', and `help'.
1664 This keymap is used by `y-or-n-p' as well as `query-replace'.")
1666 (defvar multi-query-replace-map
1667 (let ((map (make-sparse-keymap)))
1668 (set-keymap-parent map query-replace-map)
1669 (define-key map "Y" 'automatic-all)
1670 (define-key map "N" 'exit-current)
1671 map)
1672 "Keymap that defines additional bindings for multi-buffer replacements.
1673 It extends its parent map `query-replace-map' with new bindings to
1674 operate on a set of buffers/files. The difference with its parent map
1675 is the additional answers `automatic-all' to replace all remaining
1676 matches in all remaining buffers with no more questions, and
1677 `exit-current' to skip remaining matches in the current buffer
1678 and to continue with the next buffer in the sequence.")
1680 (defun replace-match-string-symbols (n)
1681 "Process a list (and any sub-lists), expanding certain symbols.
1682 Symbol Expands To
1683 N (match-string N) (where N is a string of digits)
1684 #N (string-to-number (match-string N))
1685 & (match-string 0)
1686 #& (string-to-number (match-string 0))
1687 # replace-count
1689 Note that these symbols must be preceded by a backslash in order to
1690 type them using Lisp syntax."
1691 (while (consp n)
1692 (cond
1693 ((consp (car n))
1694 (replace-match-string-symbols (car n))) ;Process sub-list
1695 ((symbolp (car n))
1696 (let ((name (symbol-name (car n))))
1697 (cond
1698 ((string-match "^[0-9]+$" name)
1699 (setcar n (list 'match-string (string-to-number name))))
1700 ((string-match "^#[0-9]+$" name)
1701 (setcar n (list 'string-to-number
1702 (list 'match-string
1703 (string-to-number (substring name 1))))))
1704 ((string= "&" name)
1705 (setcar n '(match-string 0)))
1706 ((string= "#&" name)
1707 (setcar n '(string-to-number (match-string 0))))
1708 ((string= "#" name)
1709 (setcar n 'replace-count))))))
1710 (setq n (cdr n))))
1712 (defun replace-eval-replacement (expression count)
1713 (let* ((replace-count count)
1714 (replacement (eval expression)))
1715 (if (stringp replacement)
1716 replacement
1717 (prin1-to-string replacement t))))
1719 (defun replace-quote (replacement)
1720 "Quote a replacement string.
1721 This just doubles all backslashes in REPLACEMENT and
1722 returns the resulting string. If REPLACEMENT is not
1723 a string, it is first passed through `prin1-to-string'
1724 with the `noescape' argument set.
1726 `match-data' is preserved across the call."
1727 (save-match-data
1728 (replace-regexp-in-string "\\\\" "\\\\"
1729 (if (stringp replacement)
1730 replacement
1731 (prin1-to-string replacement t))
1732 t t)))
1734 (defun replace-loop-through-replacements (data count)
1735 ;; DATA is a vector containing the following values:
1736 ;; 0 next-rotate-count
1737 ;; 1 repeat-count
1738 ;; 2 next-replacement
1739 ;; 3 replacements
1740 (if (= (aref data 0) count)
1741 (progn
1742 (aset data 0 (+ count (aref data 1)))
1743 (let ((next (cdr (aref data 2))))
1744 (aset data 2 (if (consp next) next (aref data 3))))))
1745 (car (aref data 2)))
1747 (defun replace-match-data (integers reuse &optional new)
1748 "Like `match-data', but markers in REUSE get invalidated.
1749 If NEW is non-nil, it is set and returned instead of fresh data,
1750 but coerced to the correct value of INTEGERS."
1751 (or (and new
1752 (progn
1753 (set-match-data new)
1754 (and (eq new reuse)
1755 (eq (null integers) (markerp (car reuse)))
1756 new)))
1757 (match-data integers reuse t)))
1759 (defun replace-match-maybe-edit (newtext fixedcase literal noedit match-data)
1760 "Make a replacement with `replace-match', editing `\\?'.
1761 NEWTEXT, FIXEDCASE, LITERAL are just passed on. If NOEDIT is true, no
1762 check for `\\?' is made to save time. MATCH-DATA is used for the
1763 replacement. In case editing is done, it is changed to use markers.
1765 The return value is non-nil if there has been no `\\?' or NOEDIT was
1766 passed in. If LITERAL is set, no checking is done, anyway."
1767 (unless (or literal noedit)
1768 (setq noedit t)
1769 (while (string-match "\\(\\`\\|[^\\]\\)\\(\\\\\\\\\\)*\\(\\\\\\?\\)"
1770 newtext)
1771 (setq newtext
1772 (read-string "Edit replacement string: "
1773 (prog1
1774 (cons
1775 (replace-match "" t t newtext 3)
1776 (1+ (match-beginning 3)))
1777 (setq match-data
1778 (replace-match-data
1779 nil match-data match-data))))
1780 noedit nil)))
1781 (set-match-data match-data)
1782 (replace-match newtext fixedcase literal)
1783 noedit)
1785 (defvar replace-search-function nil
1786 "Function to use when searching for strings to replace.
1787 It is used by `query-replace' and `replace-string', and is called
1788 with three arguments, as if it were `search-forward'.")
1790 (defvar replace-re-search-function nil
1791 "Function to use when searching for regexps to replace.
1792 It is used by `query-replace-regexp', `replace-regexp',
1793 `query-replace-regexp-eval', and `map-query-replace-regexp'.
1794 It is called with three arguments, as if it were
1795 `re-search-forward'.")
1797 (defun perform-replace (from-string replacements
1798 query-flag regexp-flag delimited-flag
1799 &optional repeat-count map start end)
1800 "Subroutine of `query-replace'. Its complexity handles interactive queries.
1801 Don't use this in your own program unless you want to query and set the mark
1802 just as `query-replace' does. Instead, write a simple loop like this:
1804 (while (re-search-forward \"foo[ \\t]+bar\" nil t)
1805 (replace-match \"foobar\" nil nil))
1807 which will run faster and probably do exactly what you want. Please
1808 see the documentation of `replace-match' to find out how to simulate
1809 `case-replace'.
1811 This function returns nil if and only if there were no matches to
1812 make, or the user didn't cancel the call."
1813 (or map (setq map query-replace-map))
1814 (and query-flag minibuffer-auto-raise
1815 (raise-frame (window-frame (minibuffer-window))))
1816 (let* ((case-fold-search
1817 (if (and case-fold-search search-upper-case)
1818 (isearch-no-upper-case-p from-string regexp-flag)
1819 case-fold-search))
1820 (nocasify (not (and case-replace case-fold-search)))
1821 (literal (or (not regexp-flag) (eq regexp-flag 'literal)))
1822 (search-function
1823 (or (if regexp-flag
1824 replace-re-search-function
1825 replace-search-function)
1826 (let ((isearch-regexp regexp-flag)
1827 (isearch-word delimited-flag)
1828 (isearch-lax-whitespace
1829 replace-lax-whitespace)
1830 (isearch-regexp-lax-whitespace
1831 replace-regexp-lax-whitespace)
1832 (isearch-case-fold-search case-fold-search)
1833 (isearch-forward t))
1834 (isearch-search-fun))))
1835 (search-string from-string)
1836 (real-match-data nil) ; The match data for the current match.
1837 (next-replacement nil)
1838 ;; This is non-nil if we know there is nothing for the user
1839 ;; to edit in the replacement.
1840 (noedit nil)
1841 (keep-going t)
1842 (stack nil)
1843 (replace-count 0)
1844 (nonempty-match nil)
1845 (multi-buffer nil)
1846 (recenter-last-op nil) ; Start cycling order with initial position.
1848 ;; If non-nil, it is marker saying where in the buffer to stop.
1849 (limit nil)
1851 ;; Data for the next match. If a cons, it has the same format as
1852 ;; (match-data); otherwise it is t if a match is possible at point.
1853 (match-again t)
1855 (message
1856 (if query-flag
1857 (apply 'propertize
1858 (substitute-command-keys
1859 "Query replacing %s with %s: (\\<query-replace-map>\\[help] for help) ")
1860 minibuffer-prompt-properties))))
1862 ;; If region is active, in Transient Mark mode, operate on region.
1863 (when start
1864 (setq limit (copy-marker (max start end)))
1865 (goto-char (min start end))
1866 (deactivate-mark))
1868 ;; If last typed key in previous call of multi-buffer perform-replace
1869 ;; was `automatic-all', don't ask more questions in next files
1870 (when (eq (lookup-key map (vector last-input-event)) 'automatic-all)
1871 (setq query-flag nil multi-buffer t))
1873 ;; REPLACEMENTS is either a string, a list of strings, or a cons cell
1874 ;; containing a function and its first argument. The function is
1875 ;; called to generate each replacement like this:
1876 ;; (funcall (car replacements) (cdr replacements) replace-count)
1877 ;; It must return a string.
1878 (cond
1879 ((stringp replacements)
1880 (setq next-replacement replacements
1881 replacements nil))
1882 ((stringp (car replacements)) ; If it isn't a string, it must be a cons
1883 (or repeat-count (setq repeat-count 1))
1884 (setq replacements (cons 'replace-loop-through-replacements
1885 (vector repeat-count repeat-count
1886 replacements replacements)))))
1888 (when query-replace-lazy-highlight
1889 (setq isearch-lazy-highlight-last-string nil))
1891 (push-mark)
1892 (undo-boundary)
1893 (unwind-protect
1894 ;; Loop finding occurrences that perhaps should be replaced.
1895 (while (and keep-going
1896 (not (or (eobp) (and limit (>= (point) limit))))
1897 ;; Use the next match if it is already known;
1898 ;; otherwise, search for a match after moving forward
1899 ;; one char if progress is required.
1900 (setq real-match-data
1901 (cond ((consp match-again)
1902 (goto-char (nth 1 match-again))
1903 (replace-match-data
1904 t real-match-data match-again))
1905 ;; MATCH-AGAIN non-nil means accept an
1906 ;; adjacent match.
1907 (match-again
1908 (and
1909 (funcall search-function search-string
1910 limit t)
1911 ;; For speed, use only integers and
1912 ;; reuse the list used last time.
1913 (replace-match-data t real-match-data)))
1914 ((and (< (1+ (point)) (point-max))
1915 (or (null limit)
1916 (< (1+ (point)) limit)))
1917 ;; If not accepting adjacent matches,
1918 ;; move one char to the right before
1919 ;; searching again. Undo the motion
1920 ;; if the search fails.
1921 (let ((opoint (point)))
1922 (forward-char 1)
1923 (if (funcall
1924 search-function search-string
1925 limit t)
1926 (replace-match-data
1927 t real-match-data)
1928 (goto-char opoint)
1929 nil))))))
1931 ;; Record whether the match is nonempty, to avoid an infinite loop
1932 ;; repeatedly matching the same empty string.
1933 (setq nonempty-match
1934 (/= (nth 0 real-match-data) (nth 1 real-match-data)))
1936 ;; If the match is empty, record that the next one can't be
1937 ;; adjacent.
1939 ;; Otherwise, if matching a regular expression, do the next
1940 ;; match now, since the replacement for this match may
1941 ;; affect whether the next match is adjacent to this one.
1942 ;; If that match is empty, don't use it.
1943 (setq match-again
1944 (and nonempty-match
1945 (or (not regexp-flag)
1946 (and (looking-at search-string)
1947 (let ((match (match-data)))
1948 (and (/= (nth 0 match) (nth 1 match))
1949 match))))))
1951 ;; Optionally ignore matches that have a read-only property.
1952 (unless (and query-replace-skip-read-only
1953 (text-property-not-all
1954 (nth 0 real-match-data) (nth 1 real-match-data)
1955 'read-only nil))
1957 ;; Calculate the replacement string, if necessary.
1958 (when replacements
1959 (set-match-data real-match-data)
1960 (setq next-replacement
1961 (funcall (car replacements) (cdr replacements)
1962 replace-count)))
1963 (if (not query-flag)
1964 (progn
1965 (unless (or literal noedit)
1966 (replace-highlight
1967 (nth 0 real-match-data) (nth 1 real-match-data)
1968 start end search-string
1969 regexp-flag delimited-flag case-fold-search))
1970 (setq noedit
1971 (replace-match-maybe-edit
1972 next-replacement nocasify literal
1973 noedit real-match-data)
1974 replace-count (1+ replace-count)))
1975 (undo-boundary)
1976 (let (done replaced key def)
1977 ;; Loop reading commands until one of them sets done,
1978 ;; which means it has finished handling this
1979 ;; occurrence. Any command that sets `done' should
1980 ;; leave behind proper match data for the stack.
1981 ;; Commands not setting `done' need to adjust
1982 ;; `real-match-data'.
1983 (while (not done)
1984 (set-match-data real-match-data)
1985 (replace-highlight
1986 (match-beginning 0) (match-end 0)
1987 start end search-string
1988 regexp-flag delimited-flag case-fold-search)
1989 ;; Bind message-log-max so we don't fill up the message log
1990 ;; with a bunch of identical messages.
1991 (let ((message-log-max nil)
1992 (replacement-presentation
1993 (if query-replace-show-replacement
1994 (save-match-data
1995 (set-match-data real-match-data)
1996 (match-substitute-replacement next-replacement
1997 nocasify literal))
1998 next-replacement)))
1999 (message message
2000 (query-replace-descr from-string)
2001 (query-replace-descr replacement-presentation)))
2002 (setq key (read-event))
2003 ;; Necessary in case something happens during read-event
2004 ;; that clobbers the match data.
2005 (set-match-data real-match-data)
2006 (setq key (vector key))
2007 (setq def (lookup-key map key))
2008 ;; Restore the match data while we process the command.
2009 (cond ((eq def 'help)
2010 (with-output-to-temp-buffer "*Help*"
2011 (princ
2012 (concat "Query replacing "
2013 (if delimited-flag "word " "")
2014 (if regexp-flag "regexp " "")
2015 from-string " with "
2016 next-replacement ".\n\n"
2017 (substitute-command-keys
2018 query-replace-help)))
2019 (with-current-buffer standard-output
2020 (help-mode))))
2021 ((eq def 'exit)
2022 (setq keep-going nil)
2023 (setq done t))
2024 ((eq def 'exit-current)
2025 (setq multi-buffer t keep-going nil done t))
2026 ((eq def 'backup)
2027 (if stack
2028 (let ((elt (pop stack)))
2029 (goto-char (nth 0 elt))
2030 (setq replaced (nth 1 elt)
2031 real-match-data
2032 (replace-match-data
2033 t real-match-data
2034 (nth 2 elt))))
2035 (message "No previous match")
2036 (ding 'no-terminate)
2037 (sit-for 1)))
2038 ((eq def 'act)
2039 (or replaced
2040 (setq noedit
2041 (replace-match-maybe-edit
2042 next-replacement nocasify literal
2043 noedit real-match-data)
2044 replace-count (1+ replace-count)))
2045 (setq done t replaced t))
2046 ((eq def 'act-and-exit)
2047 (or replaced
2048 (setq noedit
2049 (replace-match-maybe-edit
2050 next-replacement nocasify literal
2051 noedit real-match-data)
2052 replace-count (1+ replace-count)))
2053 (setq keep-going nil)
2054 (setq done t replaced t))
2055 ((eq def 'act-and-show)
2056 (if (not replaced)
2057 (setq noedit
2058 (replace-match-maybe-edit
2059 next-replacement nocasify literal
2060 noedit real-match-data)
2061 replace-count (1+ replace-count)
2062 real-match-data (replace-match-data
2063 t real-match-data)
2064 replaced t)))
2065 ((or (eq def 'automatic) (eq def 'automatic-all))
2066 (or replaced
2067 (setq noedit
2068 (replace-match-maybe-edit
2069 next-replacement nocasify literal
2070 noedit real-match-data)
2071 replace-count (1+ replace-count)))
2072 (setq done t query-flag nil replaced t)
2073 (if (eq def 'automatic-all) (setq multi-buffer t)))
2074 ((eq def 'skip)
2075 (setq done t))
2076 ((eq def 'recenter)
2077 ;; `this-command' has the value `query-replace',
2078 ;; so we need to bind it to `recenter-top-bottom'
2079 ;; to allow it to detect a sequence of `C-l'.
2080 (let ((this-command 'recenter-top-bottom)
2081 (last-command 'recenter-top-bottom))
2082 (recenter-top-bottom)))
2083 ((eq def 'edit)
2084 (let ((opos (point-marker)))
2085 (setq real-match-data (replace-match-data
2086 nil real-match-data
2087 real-match-data))
2088 (goto-char (match-beginning 0))
2089 (save-excursion
2090 (save-window-excursion
2091 (recursive-edit)))
2092 (goto-char opos)
2093 (set-marker opos nil))
2094 ;; Before we make the replacement,
2095 ;; decide whether the search string
2096 ;; can match again just after this match.
2097 (if (and regexp-flag nonempty-match)
2098 (setq match-again (and (looking-at search-string)
2099 (match-data)))))
2100 ;; Edit replacement.
2101 ((eq def 'edit-replacement)
2102 (setq real-match-data (replace-match-data
2103 nil real-match-data
2104 real-match-data)
2105 next-replacement
2106 (read-string "Edit replacement string: "
2107 next-replacement)
2108 noedit nil)
2109 (if replaced
2110 (set-match-data real-match-data)
2111 (setq noedit
2112 (replace-match-maybe-edit
2113 next-replacement nocasify literal noedit
2114 real-match-data)
2115 replaced t))
2116 (setq done t))
2118 ((eq def 'delete-and-edit)
2119 (replace-match "" t t)
2120 (setq real-match-data (replace-match-data
2121 nil real-match-data))
2122 (replace-dehighlight)
2123 (save-excursion (recursive-edit))
2124 (setq replaced t))
2125 ;; Note: we do not need to treat `exit-prefix'
2126 ;; specially here, since we reread
2127 ;; any unrecognized character.
2129 (setq this-command 'mode-exited)
2130 (setq keep-going nil)
2131 (setq unread-command-events
2132 (append (listify-key-sequence key)
2133 unread-command-events))
2134 (setq done t)))
2135 (when query-replace-lazy-highlight
2136 ;; Force lazy rehighlighting only after replacements.
2137 (if (not (memq def '(skip backup)))
2138 (setq isearch-lazy-highlight-last-string nil)))
2139 (unless (eq def 'recenter)
2140 ;; Reset recenter cycling order to initial position.
2141 (setq recenter-last-op nil)))
2142 ;; Record previous position for ^ when we move on.
2143 ;; Change markers to numbers in the match data
2144 ;; since lots of markers slow down editing.
2145 (push (list (point) replaced
2146 ;;; If the replacement has already happened, all we need is the
2147 ;;; current match start and end. We could get this with a trivial
2148 ;;; match like
2149 ;;; (save-excursion (goto-char (match-beginning 0))
2150 ;;; (search-forward (match-string 0))
2151 ;;; (match-data t))
2152 ;;; if we really wanted to avoid manually constructing match data.
2153 ;;; Adding current-buffer is necessary so that match-data calls can
2154 ;;; return markers which are appropriate for editing.
2155 (if replaced
2156 (list
2157 (match-beginning 0)
2158 (match-end 0)
2159 (current-buffer))
2160 (match-data t)))
2161 stack)))))
2163 (replace-dehighlight))
2164 (or unread-command-events
2165 (message "Replaced %d occurrence%s"
2166 replace-count
2167 (if (= replace-count 1) "" "s")))
2168 (or (and keep-going stack) multi-buffer)))
2170 (defvar replace-overlay nil)
2172 (defun replace-highlight (match-beg match-end range-beg range-end
2173 search-string regexp-flag delimited-flag
2174 case-fold-search)
2175 (if query-replace-highlight
2176 (if replace-overlay
2177 (move-overlay replace-overlay match-beg match-end (current-buffer))
2178 (setq replace-overlay (make-overlay match-beg match-end))
2179 (overlay-put replace-overlay 'priority 1001) ;higher than lazy overlays
2180 (overlay-put replace-overlay 'face 'query-replace)))
2181 (if query-replace-lazy-highlight
2182 (let ((isearch-string search-string)
2183 (isearch-regexp regexp-flag)
2184 (isearch-word delimited-flag)
2185 (isearch-lax-whitespace
2186 replace-lax-whitespace)
2187 (isearch-regexp-lax-whitespace
2188 replace-regexp-lax-whitespace)
2189 (isearch-case-fold-search case-fold-search)
2190 (isearch-forward t)
2191 (isearch-error nil))
2192 (isearch-lazy-highlight-new-loop range-beg range-end))))
2194 (defun replace-dehighlight ()
2195 (when replace-overlay
2196 (delete-overlay replace-overlay))
2197 (when query-replace-lazy-highlight
2198 (lazy-highlight-cleanup lazy-highlight-cleanup)
2199 (setq isearch-lazy-highlight-last-string nil)))
2201 ;;; replace.el ends here